[richfaces-svn-commits] JBoss Rich Faces SVN: r15799 - in root/framework/trunk/impl/src/main/java/org/ajax4jsf: application and 21 other directories.

richfaces-svn-commits at lists.jboss.org richfaces-svn-commits at lists.jboss.org
Sun Nov 1 12:06:55 EST 2009


Author: Alex.Kolonitsky
Date: 2009-11-01 12:06:52 -0500 (Sun, 01 Nov 2009)
New Revision: 15799

Removed:
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/Test.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Base64.java
Modified:
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/AjaxViewHandler.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugLifecycle.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugLifecycleFactory.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugOutputMaker.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/FacesErrorStateHolder.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCache.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCacheFactory.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCache.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMap.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMapEntry.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheMap.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCache.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxActionComponent.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxInputComponent.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxLoadBundleComponent.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxRegionBrige.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxViewRoot.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/ContextCallbackWrapper.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/EventValueBinding.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/EventValueExpression.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/InvokerCallbackWrapper.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/QueueRegistry.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FacesConfig.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FacesConfigHandler.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FilterBean.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FilterMapping.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FrameworkConfiguration.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ParsingException.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ServletBean.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ServletMapping.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/StateHandler.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/StringContentHandler.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/WebXMLParser.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/WebappHandler.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/AjaxContextImpl.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ComponentInvoker.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ContextInitParameters.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/InvokerCallback.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ResponseWriterContentHandler.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ViewResources.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/css/CssCompressor.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/css/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/el/ELContextWrapper.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/el/ELResolverWrapper.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxListenerHelper.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxPhaseListener.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxValidationActionEvent.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/CacheInitializationListener.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/EventsQueue.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/InitPhaseListener.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/InitializationListener.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/exception/FileUploadException.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/exception/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/ByteBuffer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/CharBuffer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferInputStream.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferOutputStream.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferReader.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferWriter.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/SAXResponseWriter.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/XMLResponseWriterState.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/javascript/JSMin.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/javascript/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AJAXDataSerializer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxChildrenRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxComponentRendererBase.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxContainerRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxEventOptions.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxRendererUtils.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxViewRootRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKit.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitFactory.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitImpl.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentRendererBase.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentVariables.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentsVariableResolver.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/HandlersChain.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererBase.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererUtils.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/MultipartRequest.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/MultipartRequestRegistry.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/BaseResourceRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CacheContext.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CachedResourceContext.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CompressedScriptRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CountingOutputWriter.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/FacesResourceContext.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/HTMLRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceBase.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceService.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/JarResource.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/Java2Dresource.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/LogfileRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/MimeRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/OneTimeRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ResourceLifecycle.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ScriptRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ServletResourceContext.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/StaticResource.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/StyleRenderer.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/URIInternetResource.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/UserResource.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/DualLRUMap.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceBean.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceBytesDataBean.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceDataBean.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/image/ImageInfo.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/image/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/CapturingELResolver.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/ELUtils.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/GenericsIntrospectionCache.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/HtmlColor.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/HtmlDimensions.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/InputUtils.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/LRUMap.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/NumericDataInputStream.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/NumericDataOutputStream.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/SelectUtils.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/ServicesUtils.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/Zipper.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/Zipper2.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/BinaryDecoder.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/BinaryEncoder.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Codec.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Decoder.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/DecoderException.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Encoder.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/EncoderException.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/URL64Codec.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/URLCodec.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/CSSFormat.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/CSSSelector.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/FontFamily.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/BaseFilter.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/BaseXMLFilter.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/CacheContent.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/FilterServletResponseWrapper.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/HtmlParser.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/ParserConfig.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/PollEventsManager.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/PushEventsCounter.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/ServletStreamWriter.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/WebXml.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/XMLResponseWriterState.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/package-info.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxActionsRule.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxComponentHandler.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxContainerBaseRule.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxReRendrRule.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/EmptyHandler.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/HtmlComponentTagBase.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/MethodExpressionAjaxListener.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/RowKeyConverterRule.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/UIComponentTagBase.java
   root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/package-info.java
Log:
Code style policy
https://jira.jboss.org/jira/browse/RFPL-195

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/AjaxViewHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/AjaxViewHandler.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/AjaxViewHandler.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,18 +19,9 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.application;
 
-import java.io.IOException;
-import java.util.Map;
 
-import javax.faces.FacesException;
-import javax.faces.application.Resource;
-import javax.faces.application.ResourceHandler;
-import javax.faces.application.ViewHandler;
-import javax.faces.component.UIViewRoot;
-import javax.faces.context.FacesContext;
-import javax.faces.context.ResponseWriter;
+package org.ajax4jsf.application;
 
 import org.ajax4jsf.Messages;
 import org.ajax4jsf.component.AjaxViewRoot;
@@ -40,162 +31,186 @@
 import org.ajax4jsf.resource.InternetResource;
 import org.ajax4jsf.webapp.BaseFilter;
 import org.ajax4jsf.webapp.FilterServletResponseWrapper;
+
 import org.richfaces.log.RichfacesLogger;
+
 import org.slf4j.Logger;
 
+import java.io.IOException;
 
+import java.util.Map;
+
+import javax.faces.FacesException;
+import javax.faces.application.Resource;
+import javax.faces.application.ResourceHandler;
+import javax.faces.application.ViewHandler;
+import javax.faces.component.UIViewRoot;
+import javax.faces.context.FacesContext;
+import javax.faces.context.ResponseWriter;
+
 /**
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.5 $ $Date: 2007/02/08 15:02:04 $
- * 
+ *
  */
 public class AjaxViewHandler extends ViewHandlerWrapper {
+    public static final String SERIALIZED_STATE_KEY = "org.ajax4jsf.view.serializedstate";
+    public static final String STATE_MARKER_KEY = "org.ajax4jsf.view.state";
+    public static final String VIEW_EXPIRED = "org.ajax4jsf.view.EXPIRED";
+    public static final String VIEW_ID_KEY = "org.ajax4jsf.VIEW_ID";
+    private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
 
-	public static final String STATE_MARKER_KEY = "org.ajax4jsf.view.state";
+    /**
+     * @param parent
+     */
+    public AjaxViewHandler(ViewHandler parent) {
+        super(parent);
 
-	public static final String SERIALIZED_STATE_KEY = "org.ajax4jsf.view.serializedstate";
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Create instance of Ajax ViewHandler");
+        }
+    }
 
-	private static final Logger _log = RichfacesLogger.APPLICATION.getLogger();
+    /*
+     * (non-Javadoc) For creating ViewRoot by Application Instead of new . Not
+     * nessesary for MyFaces ( simple copy from it ) or RI 1.2
+     *
+     * @see javax.faces.application.ViewHandler#createView(javax.faces.context.FacesContext,
+     *      java.lang.String)
+     */
+    @Override
+    public UIViewRoot createView(FacesContext facesContext, String viewId) {
+        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(facesContext);
 
-	public static final String VIEW_EXPIRED = "org.ajax4jsf.view.EXPIRED";
+        // Check for simple keep new ViewId in navigation cases.
+        ViewIdHolder viewIdHolder = ajaxContext.getViewIdHolder();
+        UIViewRoot riRoot;
 
-	public static final String VIEW_ID_KEY = "org.ajax4jsf.VIEW_ID";
+        if ((null != viewIdHolder) && viewIdHolder.skipNavigation(viewId)) {
+            viewIdHolder.setViewId(viewId);
+            riRoot = facesContext.getViewRoot();
+        } else {
+            riRoot = super.createView(facesContext, viewId);
 
-	/**
-	 * @param parent
-	 */
-	public AjaxViewHandler(ViewHandler parent) {
-		super(parent);
-		if (_log.isDebugEnabled()) {
-			_log.debug("Create instance of Ajax ViewHandler");
-		}
-	}
+            // Reset ajax request status for a navigation case.
+            if (null != facesContext.getViewRoot()) {
+                ajaxContext.setAjaxRequest(false);
+            }
+        }
 
-	/*
-	 * (non-Javadoc) For creating ViewRoot by Application Instead of new . Not
-	 * nessesary for MyFaces ( simple copy from it ) or RI 1.2
-	 * 
-	 * @see javax.faces.application.ViewHandler#createView(javax.faces.context.FacesContext,
-	 *      java.lang.String)
-	 */
-	public UIViewRoot createView(FacesContext facesContext, String viewId) {
-		AjaxContext ajaxContext = AjaxContext.getCurrentInstance(facesContext);
-		// Check for simple keep new ViewId in navigation cases.
-		ViewIdHolder viewIdHolder = ajaxContext.getViewIdHolder();
-		UIViewRoot riRoot;
-		if (null != viewIdHolder && viewIdHolder.skipNavigation(viewId)) {
-			viewIdHolder.setViewId(viewId);
-			riRoot = facesContext.getViewRoot();
-		} else {
-			riRoot = super.createView(facesContext, viewId);
-			// Reset ajax request status for a navigation case.
-			if(null != facesContext.getViewRoot()){
-				ajaxContext.setAjaxRequest(false);
-			}
-		}
-		
-		return riRoot;
-	}
+        return riRoot;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ViewHandlerWrapper#writeState(javax.faces.context.FacesContext)
-	 */
-	public void writeState(FacesContext context) throws IOException {
-		AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-		if (ajaxContext.isAjaxRequest() && ajaxContext.isSelfRender()) {
-			// We need own
-			// state marker for
-			// self-rendered regions only.
-			// write marker html element - input field. Will be parsed in filter
-			// and
-			// replaced with real state.
-			ResponseWriter writer = context.getResponseWriter();
-			writer.startElement(HTML.SPAN_ELEM, null);
-			writer.writeAttribute(HTML.id_ATTRIBUTE, STATE_MARKER_KEY, null);
-			writer.writeAttribute(HTML.NAME_ATTRIBUTE, STATE_MARKER_KEY, null);
-//			// writer.writeAttribute("style", "display:none;", null);
-//			if (!ajaxContext.isSelfRender()) {
-//				super.writeState(context);
-//			}
-			writer.endElement(HTML.SPAN_ELEM);
-		} else {
-			super.writeState(context);
-		}
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ViewHandlerWrapper#writeState(javax.faces.context.FacesContext)
+     */
+    @Override
+    public void writeState(FacesContext context) throws IOException {
+        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
 
+        if (ajaxContext.isAjaxRequest() && ajaxContext.isSelfRender()) {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ViewHandlerWrapper#getResourceURL(javax.faces.context.FacesContext,
-	 *      java.lang.String)
-	 */
-	public String getResourceURL(FacesContext context, String url) {
-		if (url.startsWith(InternetResource.RESOURCE_URI_PREFIX)) {
-			ResourceHandler resourceHandler = context.getApplication().getResourceHandler();
-			String resourceURL = url.substring(InternetResource.RESOURCE_URI_PREFIX_LENGTH);
+            // We need own
+            // state marker for
+            // self-rendered regions only.
+            // write marker html element - input field. Will be parsed in filter
+            // and
+            // replaced with real state.
+            ResponseWriter writer = context.getResponseWriter();
 
-			Resource resource = resourceHandler.createResource(resourceURL);
-			
-			if (resource != null) {
-				return resource.getRequestPath();
-			} else {
-				return super.getResourceURL(context, resourceURL);
-			}
-		}
+            writer.startElement(HTML.SPAN_ELEM, null);
+            writer.writeAttribute(HTML.ID_ATTRIBUTE, STATE_MARKER_KEY, null);
+            writer.writeAttribute(HTML.NAME_ATTRIBUTE, STATE_MARKER_KEY, null);
 
-		return super.getResourceURL(context, url);
-	}
+//          // writer.writeAttribute("style", "display:none;", null);
+//          if (!ajaxContext.isSelfRender()) {
+//              super.writeState(context);
+//          }
+            writer.endElement(HTML.SPAN_ELEM);
+        } else {
+            super.writeState(context);
+        }
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ViewHandlerWrapper#renderView(javax.faces.context.FacesContext,
-	 *      javax.faces.component.UIViewRoot)
-	 */
-	public void renderView(FacesContext context, UIViewRoot root)
-			throws IOException, FacesException {
-		AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-		// Broadcast Ajax events before rendering, to setup areas to update.
-		if (root instanceof AjaxViewRoot) {
-			AjaxViewRoot ajaxRoot = (AjaxViewRoot) root;
-			// broadcast ajax events before render response.
-			if (ajaxContext.isAjaxRequest()) {
-				processAjaxEvents(context, ajaxRoot);
-				if(ajaxContext.isSelfRender()){
-					// Render view directly.
-					ajaxContext.renderAjax(context);
-				}
-			}
-			if (!context.getResponseComplete()) {
-				super.renderView(context, root);
-			}
-		} else {
-			super.renderView(context, root);
-		}
-		
-		Map<String,Object> requestMap = context.getExternalContext().getRequestMap();
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ViewHandlerWrapper#getResourceURL(javax.faces.context.FacesContext,
+     *      java.lang.String)
+     */
+    @Override
+    public String getResourceURL(FacesContext context, String url) {
+        if (url.startsWith(InternetResource.RESOURCE_URI_PREFIX)) {
+            ResourceHandler resourceHandler = context.getApplication().getResourceHandler();
+            String resourceURL = url.substring(InternetResource.RESOURCE_URI_PREFIX_LENGTH);
+            Resource resource = resourceHandler.createResource(resourceURL);
 
-		FilterServletResponseWrapper filterServletResponseWrapper = (FilterServletResponseWrapper) 
-			requestMap.get(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE);
-		if (null != filterServletResponseWrapper) {
-			// Save viewId for a parser selection
-			requestMap.put(AjaxViewHandler.VIEW_ID_KEY, context.getViewRoot().getViewId());
-		}
-	}
+            if (resource != null) {
+                return resource.getRequestPath();
+            } else {
+                return super.getResourceURL(context, resourceURL);
+            }
+        }
 
-	/**
-	 * @param context
-	 * @param ajaxRoot
-	 */
-	private void processAjaxEvents(FacesContext context, AjaxViewRoot ajaxRoot) {
-		// First - process reRender from active components.
-		if (_log.isDebugEnabled()) {
-			_log.debug(Messages.getMessage(Messages.PROCESS_AJAX_EVENTS_INFO));
-		}
-		ajaxRoot.broadcastAjaxEvents(context);
-	}
+        return super.getResourceURL(context, url);
+    }
 
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ViewHandlerWrapper#renderView(javax.faces.context.FacesContext,
+     *      javax.faces.component.UIViewRoot)
+     */
+    @Override
+    public void renderView(FacesContext context, UIViewRoot root) throws IOException, FacesException {
+        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
+
+        // Broadcast Ajax events before rendering, to setup areas to update.
+        if (root instanceof AjaxViewRoot) {
+            AjaxViewRoot ajaxRoot = (AjaxViewRoot) root;
+
+            // broadcast ajax events before render response.
+            if (ajaxContext.isAjaxRequest()) {
+                processAjaxEvents(context, ajaxRoot);
+
+                if (ajaxContext.isSelfRender()) {
+
+                    // Render view directly.
+                    ajaxContext.renderAjax(context);
+                }
+            }
+
+            if (!context.getResponseComplete()) {
+                super.renderView(context, root);
+            }
+        } else {
+            super.renderView(context, root);
+        }
+
+        Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
+        FilterServletResponseWrapper filterServletResponseWrapper =
+            (FilterServletResponseWrapper) requestMap.get(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE);
+
+        if (null != filterServletResponseWrapper) {
+
+            // Save viewId for a parser selection
+            requestMap.put(AjaxViewHandler.VIEW_ID_KEY, context.getViewRoot().getViewId());
+        }
+    }
+
+    /**
+     * @param context
+     * @param ajaxRoot
+     */
+    private void processAjaxEvents(FacesContext context, AjaxViewRoot ajaxRoot) {
+
+        // First - process reRender from active components.
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.PROCESS_AJAX_EVENTS_INFO));
+        }
+
+        ajaxRoot.broadcastAjaxEvents(context);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugLifecycle.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugLifecycle.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugLifecycle.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,14 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.application;
 
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import javax.faces.FacesException;
 import javax.faces.context.FacesContext;
 import javax.faces.event.PhaseEvent;
@@ -29,142 +35,133 @@
 import javax.faces.lifecycle.Lifecycle;
 import javax.faces.lifecycle.LifecycleFactory;
 
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:12 $
- * 
+ *
  */
-public class DebugLifecycle extends Lifecycle implements PhaseListener{
+public class DebugLifecycle extends Lifecycle implements PhaseListener {
+    public static final String DEBUG_LYFECYCLE_ID = "DEBUG";
+    public static final String LIFECYCLE_ID_ATTR = "javax.faces.LIFECYCLE_ID";
+    public static final String PHASE_ID_PARAM = "org.ajax4jsf.CURRENT_PHASE";
+    private static final long serialVersionUID = -3247965217553145312L;
+    private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
+    private static final DebugOutputMaker DEBUG_OUTPUT = new DebugOutputMaker();
+    private Lifecycle defaultLifecycle;
 
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -3247965217553145312L;
+    /**
+     * @param default1
+     */
+    public DebugLifecycle(Lifecycle default1) {
+        super();
 
-	private Lifecycle _default;
-	
-	private static Logger _log = RichfacesLogger.APPLICATION.getLogger();
+        // TODO Auto-generated constructor stub
+        this.defaultLifecycle = default1;
+    }
 
-	public static final String DEBUG_LYFECYCLE_ID = "DEBUG";
+    /**
+     *
+     */
+    public DebugLifecycle(LifecycleFactory defaultFactory) {
+        super();
+        defaultLifecycle = defaultFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
+        defaultLifecycle.addPhaseListener(this);
+    }
 
-	public static final String LIFECYCLE_ID_ATTR = "javax.faces.LIFECYCLE_ID";
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#addPhaseListener(javax.faces.event.PhaseListener)
+     */
+    public void addPhaseListener(PhaseListener arg0) {
+        defaultLifecycle.addPhaseListener(arg0);
+    }
 
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#execute(javax.faces.context.FacesContext)
+     */
+    public void execute(FacesContext context) throws FacesException {
+        try {
+            defaultLifecycle.execute(context);
 
-	public static final String PHASE_ID_PARAM = "org.ajax4jsf.CURRENT_PHASE";
-	
-	private static final DebugOutputMaker debugOutput = new DebugOutputMaker();
+//          TODO Refactoring:       } catch (Throwable e) {
+        } catch (FacesException e) {
 
-	/**
-	 * @param default1
-	 */
-	public DebugLifecycle(Lifecycle default1) {
-		super();
-		// TODO Auto-generated constructor stub
-		this._default = default1;
-	}
+//          DebugOutputMaker debugOutput = new DebugOutputMaker();
+            DEBUG_OUTPUT.writeErrorMessage(context, e, "execute");
+            context.responseComplete();
+        }
+    }
 
-	/**
-	 * 
-	 */
-	public DebugLifecycle(LifecycleFactory defaultFactory) {
-		super();
-		_default = defaultFactory
-				.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
-		_default.addPhaseListener(this);
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#getPhaseListeners()
+     */
+    public PhaseListener[] getPhaseListeners() {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#addPhaseListener(javax.faces.event.PhaseListener)
-	 */
-	public void addPhaseListener(PhaseListener arg0) {
-		_default.addPhaseListener(arg0);
+        // TODO Auto-generated method stub
+        return defaultLifecycle.getPhaseListeners();
+    }
 
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#removePhaseListener(javax.faces.event.PhaseListener)
+     */
+    public void removePhaseListener(PhaseListener arg0) {
+        defaultLifecycle.removePhaseListener(arg0);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#execute(javax.faces.context.FacesContext)
-	 */
-	public void execute(FacesContext context) throws FacesException {
-		try {
-			_default.execute(context);
-		} catch (Throwable e) {
-//			DebugOutputMaker debugOutput = new DebugOutputMaker();
-			debugOutput.writeErrorMessage(context, e, "execute");
-			context.responseComplete();
-		}
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#render(javax.faces.context.FacesContext)
+     */
+    public void render(FacesContext context) throws FacesException {
+        try {
+            defaultLifecycle.render(context);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#getPhaseListeners()
-	 */
-	public PhaseListener[] getPhaseListeners() {
-		// TODO Auto-generated method stub
-		return _default.getPhaseListeners();
-	}
+//          TODO Refactoring:        } catch (Throwable e) {
+        } catch (FacesException e) {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#removePhaseListener(javax.faces.event.PhaseListener)
-	 */
-	public void removePhaseListener(PhaseListener arg0) {
-		_default.removePhaseListener(arg0);
+//          DebugOutputMaker debugOutput = new DebugOutputMaker();
+            DEBUG_OUTPUT.writeErrorMessage(context, e, "render");
+            context.responseComplete();
+        }
+    }
 
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
+     */
+    public void afterPhase(PhaseEvent event) {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("End phase " + event.getPhaseId().toString());
+        }
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#render(javax.faces.context.FacesContext)
-	 */
-	public void render(FacesContext context) throws FacesException {
-		try {
-			_default.render(context);
-		} catch (Throwable e) {
-//			DebugOutputMaker debugOutput = new DebugOutputMaker();
-			debugOutput.writeErrorMessage(context, e, "render");
-			context.responseComplete();
-		}
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
+     */
+    public void beforePhase(PhaseEvent event) {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Start phase " + event.getPhaseId().toString());
+        }
 
+        event.getFacesContext().getExternalContext().getRequestMap().put(PHASE_ID_PARAM, event.getPhaseId());
+    }
 
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.event.PhaseListener#getPhaseId()
+     */
+    public PhaseId getPhaseId() {
 
-
-	/* (non-Javadoc)
-	 * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
-	 */
-	public void afterPhase(PhaseEvent event) {
-		if (_log.isDebugEnabled()) {
-			_log.debug("End phase "+event.getPhaseId().toString());
-		}
-		
-	}
-
-	/* (non-Javadoc)
-	 * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
-	 */
-	public void beforePhase(PhaseEvent event) {
-		if (_log.isDebugEnabled()) {
-			_log.debug("Start phase "+event.getPhaseId().toString());
-		}
-		event.getFacesContext().getExternalContext().getRequestMap().put(PHASE_ID_PARAM,event.getPhaseId());
-		
-	}
-
-	/* (non-Javadoc)
-	 * @see javax.faces.event.PhaseListener#getPhaseId()
-	 */
-	public PhaseId getPhaseId() {
-		// TODO Auto-generated method stub
-		return PhaseId.ANY_PHASE;
-	}
+        // TODO Auto-generated method stub
+        return PhaseId.ANY_PHASE;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugLifecycleFactory.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugLifecycleFactory.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugLifecycleFactory.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,80 +19,89 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.application;
 
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.util.Iterator;
 
 import javax.faces.lifecycle.Lifecycle;
 import javax.faces.lifecycle.LifecycleFactory;
 
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * @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 Logger _log = RichfacesLogger.APPLICATION.getLogger();
-	
-	private LifecycleFactory _defaultFactory;
-	
-	private DebugLifecycle _debugLifecycle ;
-	
-//	private Map _lifecycles = new HashMap();
+    private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
+    private DebugLifecycle debugLifecycle;
+    private LifecycleFactory defaultFactory;
 
-	/**
-	 * @return the debugLifecycle
-	 */
-	private DebugLifecycle getDebugLifecycle() {
-		if (_debugLifecycle == null) {
-			_debugLifecycle = new DebugLifecycle(_defaultFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE));			
-		}
-		return _debugLifecycle;
-	}
+    /**
+     * @param defaultFactory
+     */
+    public DebugLifecycleFactory(LifecycleFactory defaultFactory) {
+        super();
+        this.defaultFactory = defaultFactory;
 
-	/**
-	 * @param defaultFactory
-	 */
-	public DebugLifecycleFactory(LifecycleFactory defaultFactory) {
-		super();
-		this._defaultFactory = defaultFactory;
-		if (_log.isDebugEnabled()) {
-		    _log.debug("Created Lifecycle instance");
-		}
-	}
+        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 lifecycleId, Lifecycle lifecycle) {
-		this._defaultFactory.addLifecycle(lifecycleId, lifecycle);
-		if (_log.isDebugEnabled()) {
-		    _log.debug("Added lifecycle with ID "+lifecycleId);
-		}
-	}
+//  private Map _lifecycles = new HashMap();
 
-	/* (non-Javadoc)
-	 * @see javax.faces.lifecycle.LifecycleFactory#getLifecycle(java.lang.String)
-	 */
-	public Lifecycle getLifecycle(String lifecycleId) {
-		Lifecycle life;
-		if(DebugLifecycle.DEBUG_LYFECYCLE_ID.equals(lifecycleId)) {
-			life = getDebugLifecycle();
-		} else {
-			life = this._defaultFactory.getLifecycle(lifecycleId);
-		}
-		return life;
-	}
+    /**
+     * @return the debugLifecycle
+     */
+    private DebugLifecycle getDebugLifecycle() {
+        if (debugLifecycle == null) {
+            debugLifecycle = new DebugLifecycle(defaultFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE));
+        }
 
-	/* (non-Javadoc)
-	 * @see javax.faces.lifecycle.LifecycleFactory#getLifecycleIds()
-	 */
-	public Iterator getLifecycleIds() {
-		return this._defaultFactory.getLifecycleIds();
-	}
+        return debugLifecycle;
+    }
 
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.lifecycle.LifecycleFactory#addLifecycle(java.lang.String, javax.faces.lifecycle.Lifecycle)
+     */
+    @Override
+    public void addLifecycle(String lifecycleId, Lifecycle lifecycle) {
+        this.defaultFactory.addLifecycle(lifecycleId, lifecycle);
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Added lifecycle with ID " + lifecycleId);
+        }
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.lifecycle.LifecycleFactory#getLifecycle(java.lang.String)
+     */
+    @Override
+    public Lifecycle getLifecycle(String lifecycleId) {
+        Lifecycle life;
+
+        if (DebugLifecycle.DEBUG_LYFECYCLE_ID.equals(lifecycleId)) {
+            life = getDebugLifecycle();
+        } else {
+            life = this.defaultFactory.getLifecycle(lifecycleId);
+        }
+
+        return life;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.lifecycle.LifecycleFactory#getLifecycleIds()
+     */
+    public Iterator getLifecycleIds() {
+        return this.defaultFactory.getLifecycleIds();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugOutputMaker.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugOutputMaker.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/DebugOutputMaker.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,10 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.application;
 
 import java.io.IOException;
 import java.io.PrintWriter;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashSet;
@@ -36,6 +39,7 @@
 
 import javax.el.Expression;
 import javax.el.ValueExpression;
+
 import javax.faces.FacesException;
 import javax.faces.application.Resource;
 import javax.faces.component.UIComponent;
@@ -43,426 +47,461 @@
 import javax.faces.context.ExternalContext;
 import javax.faces.context.FacesContext;
 import javax.faces.event.PhaseId;
+
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import org.ajax4jsf.Messages;
 
-
 /**
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:11 $
- *
  */
 public class DebugOutputMaker {
-    private final static String LT = "&lt;";
-    private final static String GT = "&gt;";
-	// Attributes that should not be printed
-	static public final Set<String> IGNORE_ATTRIBUTES;
+    // Attributes that should not be printed
+    public static final Set<String> IGNORE_ATTRIBUTES;
 
-	static {
-		IGNORE_ATTRIBUTES = new HashSet<String>();
-		IGNORE_ATTRIBUTES.add("attributes");
-		IGNORE_ATTRIBUTES.add("children");
-		IGNORE_ATTRIBUTES.add("childCount");
-		IGNORE_ATTRIBUTES.add("class");
-		IGNORE_ATTRIBUTES.add("facets");
-		IGNORE_ATTRIBUTES.add("facetsAndChildren");
-		IGNORE_ATTRIBUTES.add("parent");
-		IGNORE_ATTRIBUTES.add("actionListeners");
-		IGNORE_ATTRIBUTES.add("valueChangeListeners");
-		IGNORE_ATTRIBUTES.add("validators");
-		IGNORE_ATTRIBUTES.add("rowData");
-		IGNORE_ATTRIBUTES.add("javax.faces.webapp.COMPONENT_IDS");
-		IGNORE_ATTRIBUTES.add("javax.faces.webapp.FACET_NAMES");
-		IGNORE_ATTRIBUTES.add("javax.faces.webapp.CURRENT_VIEW_ROOT");
-	}
-	
-	private static final String LOGFILE_PARAM = "org.ajax4jsf.LOGFILE";
+    private static final String GT = "&gt;";
+    private static final String LOGFILE_PARAM = "org.ajax4jsf.LOGFILE";
 
-	/**
-	 * Output error state for lifecycle.
-	 * 
-	 * @param context
-	 * @param phase
-	 *            TODO
-	 * @param error
-	 * @throws IOException
-	 */
-	public void writeErrorMessage(FacesContext context, Throwable e, String phase)
-			throws FacesException {
-		if (null == context) {
-			throw new FacesException(Messages.getMessage(Messages.FACES_CONTEXT_NOT_CREATED), e);
-		}
-		ExternalContext externalContext = context
-		.getExternalContext();
-		if (null == externalContext) {
-			throw new FacesException(Messages.getMessage(Messages.FACES_CONTEXT_HAS_NOT_EXTERNAL), e);
-		}
-		// debug for http servlet environment, portlets needs other debugger
-		HttpServletResponse response;
-		HttpServletRequest request;
-		try {
-			response = (HttpServletResponse) externalContext
-					.getResponse();
-			request = (HttpServletRequest) externalContext.getRequest();
-			response.setContentType("text/html;charset=UTF-8");
-			// set internal server error status
-			response.setStatus(500);
-		} catch (Exception er) {
-			throw new FacesException(Messages.getMessage(Messages.FACES_CONTEXT_HAS_NOT_RESPONSE), e);
-		}
-		PrintWriter out;
-		try {
-			out = response.getWriter();
-		} catch (IOException e1) {
-			throw new FacesException(e1.getMessage(), e);
-		}
-		UIViewRoot viewRoot = context.getViewRoot();
-		String viewId;
-		if (null != viewRoot) {
-			viewId = viewRoot.getViewId();
-		} else {
-			viewId = request.getRequestURL().toString();
-		}
-		// output html prolog
-		out.println("<html><head><title>" +
-				Messages.getMessage(Messages.ERROR_ON_PAGE, viewId) +
-				"</title></head><body>");
-		// write script
-		writeScriptAndStyle(out);
-		// Header
-		PhaseId facesPhase = (PhaseId) context.getExternalContext().getRequestMap().get(DebugLifecycle.PHASE_ID_PARAM);
-		
-		String errorMessage = 
-			(facesPhase == null) 
-					? Messages.getMessage(Messages.LIFECYCLE_ERROR, viewId, phase)
-					: Messages.getMessage(Messages.LIFECYCLE_ERROR_AT_PHASE, new Object[]{viewId, phase, facesPhase.toString()});
-		out.println("<h1 >");
-		out.println(errorMessage);
-		out.println("</h1>");
-		response.setHeader("Ajax-Error-Message", errorMessage+",\n caused by "+e.getClass().getName()+", with message: "+e.getMessage());
-		// Output exceptions
-		writeExceptionStack(e, out);
-		// Output view tree :
-		if (null != viewRoot) {
-			writeComponentsTree(context, out);
-		} else {
-			out.print("<h2 class=' a4j_debug'> " +
-					Messages.getMessage(Messages.COMPONENT_TREE_NOT_CREATED) +
-					" </h2>");
-		}
-		// Out scope variables
-		writeContextVariables(context, out);
-		// Write log output iframe :
-		writeLog(context, out);
-		// out html tail
-		out.println("</body></html>");
-		out.flush();
-		out.close();
-	}
-	/**
-	 * @param e
-	 * @param out
-	 */
-	public void writeExceptionStack(Throwable e, PrintWriter out) {
-		out.println("<h2 class=\"a4j_debug\">Exceptions: </h2>");
-		Throwable error = e;
-		int errorId = 0;
-		String caused = "exception ";
-		while (null != error) {
-			out.print("<h3 onclick=\"toggle('exception" + errorId + "')\"  class='exception a4j_debug'>");
-			writeToggleMark(out,"exception" + errorId);					
-			out.print( caused + error.getClass().getName() + " : "
-					+ error.getMessage() + "</h3>");
-			out.println("<div id='exception" + errorId
-					+ "' style='display: none;' class='exception'><p>Exception stack :</p><pre>");
-			StackTraceElement[] stackTrace = error.getStackTrace();
-			for (int i = 0; i < stackTrace.length; i++) {
-				out.print("  at " + stackTrace[i].getClassName());
-				out.print("." + stackTrace[i].getMethodName());
-				out.println(" in " + stackTrace[i].getFileName() + " line "
-						+ stackTrace[i].getLineNumber());
-			}
-			// error.printStackTrace(out);
-			out.println("</pre></div>");
-			error = error.getCause();
-			caused = "caused by ";
-			errorId++;
-		}
-	}
-	
-	/**
-	 * @param context
-	 * @param out
-	 */
-	public void writeContextVariables(FacesContext context, PrintWriter out) {
-		out.print("<h2  class=\"a4j_debug\" onclick=\"toggle('variables')\">");
-		writeToggleMark(out,"variables");
-		out.println("Faces variables: </h2><div id='variables' style='display: none;'  class='variables a4j_debug'>");
-		writeVariables(out,context);
-		out.println("</div>");
-	}
+    private static final String LT = "&lt;";
 
-	/**
-	 * @param context
-	 * @param out
-	 */
-	public void writeComponentsTree(FacesContext context, PrintWriter out) {
-		out
-				.print("<h2 class=\"a4j_debug\" onclick=\"toggle('tree')\">");
-		writeToggleMark(out,"tree");
-		out.println("Component tree: </h2><div id='tree' style='display: none;'  class='tree a4j_debug'><dl>");
-		writeComponent(context, out, context.getViewRoot(), null);
-		out.println("</dl></div>");
-	}
-	
-	public void writeScriptAndStyle(PrintWriter out) {
-		writeScript(out);
-		writeStyleSheet(out);
-	}
+    static {
+        IGNORE_ATTRIBUTES = new HashSet<String>();
+        IGNORE_ATTRIBUTES.add("attributes");
+        IGNORE_ATTRIBUTES.add("children");
+        IGNORE_ATTRIBUTES.add("childCount");
+        IGNORE_ATTRIBUTES.add("class");
+        IGNORE_ATTRIBUTES.add("facets");
+        IGNORE_ATTRIBUTES.add("facetsAndChildren");
+        IGNORE_ATTRIBUTES.add("parent");
+        IGNORE_ATTRIBUTES.add("actionListeners");
+        IGNORE_ATTRIBUTES.add("valueChangeListeners");
+        IGNORE_ATTRIBUTES.add("validators");
+        IGNORE_ATTRIBUTES.add("rowData");
+        IGNORE_ATTRIBUTES.add("javax.faces.webapp.COMPONENT_IDS");
+        IGNORE_ATTRIBUTES.add("javax.faces.webapp.FACET_NAMES");
+        IGNORE_ATTRIBUTES.add("javax.faces.webapp.CURRENT_VIEW_ROOT");
+    }
 
-	/**
-	 * @param context
-	 * @param out
-	 * @throws FacesException
-	 */
-	public void writeLog(FacesContext context, PrintWriter out) throws FacesException {
-		String logname = context.getExternalContext().getInitParameter(LOGFILE_PARAM);
-		if (null != logname) {
-			Resource logResource = context.getApplication().getResourceHandler().createResource(logname);
-			out.print("<h2 onclick=\"toggle('log')\" class=\"a4j_debug\">");
-			writeToggleMark(out, "log");
-			out
-					.println("Faces log: </h2><div id='log' style='display: none;'  class='log a4j_debug'>");
-			String logResourceRequestPath = logResource.getRequestPath();
-			out.print("<iframe name='log' class='log' src='"+logResourceRequestPath+"'><a href='src='"+logResourceRequestPath+"'>Faces log file </a> </iframe>");
-			out.println("</div>");
-		}
-	}
+    /**
+     * Output error state for lifecycle.
+     *
+     * @param context
+     * @param phase   TODO
+     * @param error
+     * @throws IOException
+     */
+    public void writeErrorMessage(FacesContext context, Throwable e, String phase) throws FacesException {
+        if (null == context) {
+            throw new FacesException(Messages.getMessage(Messages.FACES_CONTEXT_NOT_CREATED), e);
+        }
 
-	public void writeToggleMark(PrintWriter out,String id) {
-		out.print("<span style=\"display:none;\" id=\""+id+"_expanded\" >-&nbsp;</span>");
-		out.print("<span style=\"display:inline;\" id=\""+id+"_collapsed\" >+</span>&nbsp;");
-	}
+        ExternalContext externalContext = context.getExternalContext();
 
+        if (null == externalContext) {
+            throw new FacesException(Messages.getMessage(Messages.FACES_CONTEXT_HAS_NOT_EXTERNAL), e);
+        }
 
-	/**
-	 * Out component with properties and it's facets and childrens
-	 * @param context TODO
-	 * @param out
-	 * @param viewRoot
-	 */
-	private void writeComponent(FacesContext context, PrintWriter out,
-			UIComponent component, String facetName) {
-		String clientId = "_tree:"+component.getClientId(context);
-		out.println("<dt onclick=\"toggle('"+clientId+"')\" class='tree'>");
-		writeToggleMark(out,clientId);
-		// out component name
-		if (null != facetName) {
-			out.print("Facet:'" + facetName + "' ");
-		}
-		out.println("<code>" + component.getClass().getName() + "</code> Id:["+component.getId()+"]");
-		out.println("</dt>");
-		out.println("<dd id='"+clientId+"' style='display:none;'   class='tree' ><ul   class='tree'>");
-		// out bean properties
-		try {
-			Map<String, Object> attributes = component.getAttributes();
-			List<String> attributeNamesList = new ArrayList<String>(attributes.keySet());
-			Collections.sort(attributeNamesList);
-			for (String attributeName : attributeNamesList) {
-				ValueExpression ve = component.getValueExpression(attributeName);
-				if (ve != null) {
-					writeAttribute(out, attributeName, ve.getExpressionString());
-				} else {
-					if (!IGNORE_ATTRIBUTES.contains(attributeName)) {
-						try {
-							Object value = attributes.get(attributeName);
-							writeAttribute(out, attributeName, value);
-						} catch (Exception e) {
-							writeAttribute(out, attributeName, null);
-						}
-					}
-				}
-			}
-		} catch (Exception e) {
-			// Do nothing - we in error page.
-		}
+        // debug for http servlet environment, portlets needs other debugger
+        HttpServletResponse response;
+        HttpServletRequest request;
 
-		// out bindings
-		// out attributes map
-		for (Iterator<Entry<String, Object>> it = component.getAttributes().entrySet().iterator(); it
-				.hasNext();) {
-			Entry<String, Object> entry = it.next();
-			writeAttribute(out, entry.getKey(), entry.getValue());
-		}
-		// out listeners
-		out.println("</ul></dd>");
-		if (component.getFacetCount() > 0 || component.getChildCount() > 0) {
-			out.println("<dd class='tree_childs'><dl class='tree_childs'>");
-			// out childs of this component
-			// facets
-			Map<String, UIComponent> facetsMap = component.getFacets();
-			List<String> facetNamesList = new ArrayList<String>(facetsMap.keySet());
-			Collections.sort(facetNamesList);
-			
-			for (String nextFacetName : facetNamesList) {
-				writeComponent(context, out, facetsMap.get(nextFacetName), nextFacetName);
-			}
+        try {
+            response = (HttpServletResponse) externalContext.getResponse();
+            request = (HttpServletRequest) externalContext.getRequest();
+            response.setContentType("text/html;charset=UTF-8");
 
-			// childs components
-			for (Iterator<UIComponent> childIter = component.getChildren().iterator(); childIter
-					.hasNext();) {
-				UIComponent child = childIter.next();
-				writeComponent(context, out, child, null);
-			}
-			out.println("</dl></dd>");
-		}
+            // set internal server error status
+            response.setStatus(500);
+        } catch (Exception er) {
+            throw new FacesException(Messages.getMessage(Messages.FACES_CONTEXT_HAS_NOT_RESPONSE), e);
+        }
 
-	}
+        PrintWriter out;
 
-	private void writeAttribute(PrintWriter out, String name, Object value) {
-		if (IGNORE_ATTRIBUTES.contains(name))
-			return;
-		if (name.startsWith("javax.faces.webapp.UIComponentTag.")) {
-			name = name
-					.substring("javax.faces.webapp.UIComponentTag.".length());
-		}
-		out.print("<li>");
-		out.print(name);
-		out.print("=\"");
-		if (value != null) {
-			if (value instanceof UIComponent) {
-				out.print("[id:");
-				out.print(((UIComponent) value).getId());
-				out.print(']');
-			} else if (value instanceof Expression) {
-				out.print(((Expression) value).getExpressionString());
-			} else {
-				out.print(value.toString());
-			}
-		} else {
-			out.print("NULL");
-		}
-		out.println("\"</li>");
-	}
+        try {
+            out = response.getWriter();
+        } catch (IOException e1) {
+            throw new FacesException(e1.getMessage(), e);
+        }
 
-    private  void writeVariables(PrintWriter out, FacesContext faces)  {
+        UIViewRoot viewRoot = context.getViewRoot();
+        String viewId;
+
+        if (null != viewRoot) {
+            viewId = viewRoot.getViewId();
+        } else {
+            viewId = request.getRequestURL().toString();
+        }
+
+        // output html prolog
+        out.println("<html><head><title>" + Messages.getMessage(Messages.ERROR_ON_PAGE, viewId)
+                    + "</title></head><body>");
+
+        // write script
+        writeScriptAndStyle(out);
+
+        // Header
+        PhaseId facesPhase = (PhaseId) context.getExternalContext().getRequestMap().get(DebugLifecycle.PHASE_ID_PARAM);
+        String errorMessage = (facesPhase == null) ? Messages.getMessage(Messages.LIFECYCLE_ERROR, viewId, phase)
+            : Messages.getMessage(Messages.LIFECYCLE_ERROR_AT_PHASE,
+                new Object[] {viewId, phase, facesPhase.toString()});
+
+        out.println("<h1 >");
+        out.println(errorMessage);
+        out.println("</h1>");
+        response.setHeader("Ajax-Error-Message",
+                           errorMessage + ",\n caused by " + e.getClass().getName() + ", with message: "
+                           + e.getMessage());
+
+        // Output exceptions
+        writeExceptionStack(e, out);
+
+        // Output view tree :
+        if (null != viewRoot) {
+            writeComponentsTree(context, out);
+        } else {
+            out.print("<h2 class=' a4j_debug'> " + Messages.getMessage(Messages.COMPONENT_TREE_NOT_CREATED) + " </h2>");
+        }
+
+        // Out scope variables
+        writeContextVariables(context, out);
+
+        // Write log output iframe :
+        writeLog(context, out);
+
+        // out html tail
+        out.println("</body></html>");
+        out.flush();
+        out.close();
+    }
+
+    /**
+     * @param e
+     * @param out
+     */
+    public void writeExceptionStack(Throwable e, PrintWriter out) {
+        out.println("<h2 class=\"a4j_debug\">Exceptions: </h2>");
+
+        Throwable error = e;
+        int errorId = 0;
+        String caused = "exception ";
+
+        while (null != error) {
+            out.print("<h3 onclick=\"toggle('exception" + errorId + "')\"  class='exception a4j_debug'>");
+            writeToggleMark(out, "exception" + errorId);
+            out.print(caused + error.getClass().getName() + " : " + error.getMessage() + "</h3>");
+            out.println("<div id='exception" + errorId
+                        + "' style='display: none;' class='exception'><p>Exception stack :</p><pre>");
+
+            StackTraceElement[] stackTrace = error.getStackTrace();
+
+            for (int i = 0; i < stackTrace.length; i++) {
+                out.print("  at " + stackTrace[i].getClassName());
+                out.print("." + stackTrace[i].getMethodName());
+                out.println(" in " + stackTrace[i].getFileName() + " line " + stackTrace[i].getLineNumber());
+            }
+
+            // error.printStackTrace(out);
+            out.println("</pre></div>");
+            error = error.getCause();
+            caused = "caused by ";
+            errorId++;
+        }
+    }
+
+    /**
+     * @param context
+     * @param out
+     */
+    public void writeContextVariables(FacesContext context, PrintWriter out) {
+        out.print("<h2  class=\"a4j_debug\" onclick=\"toggle('variables')\">");
+        writeToggleMark(out, "variables");
+        out.println("Faces variables: </h2><div id='variables' style='display: none;'  class='variables a4j_debug'>");
+        writeVariables(out, context);
+        out.println("</div>");
+    }
+
+    /**
+     * @param context
+     * @param out
+     */
+    public void writeComponentsTree(FacesContext context, PrintWriter out) {
+        out.print("<h2 class=\"a4j_debug\" onclick=\"toggle('tree')\">");
+        writeToggleMark(out, "tree");
+        out.println("Component tree: </h2><div id='tree' style='display: none;'  class='tree a4j_debug'><dl>");
+        writeComponent(context, out, context.getViewRoot(), null);
+        out.println("</dl></div>");
+    }
+
+    public void writeScriptAndStyle(PrintWriter out) {
+        writeScript(out);
+        writeStyleSheet(out);
+    }
+
+    /**
+     * @param context
+     * @param out
+     * @throws FacesException
+     */
+    public void writeLog(FacesContext context, PrintWriter out) throws FacesException {
+        String logname = context.getExternalContext().getInitParameter(LOGFILE_PARAM);
+
+        if (null != logname) {
+            Resource logResource = context.getApplication().getResourceHandler().createResource(logname);
+
+            out.print("<h2 onclick=\"toggle('log')\" class=\"a4j_debug\">");
+            writeToggleMark(out, "log");
+            out.println("Faces log: </h2><div id='log' style='display: none;'  class='log a4j_debug'>");
+
+            String logResourceRequestPath = logResource.getRequestPath();
+
+            out.print("<iframe name='log' class='log' src='" + logResourceRequestPath + "'><a href='src='"
+                      + logResourceRequestPath + "'>Faces log file </a> </iframe>");
+            out.println("</div>");
+        }
+    }
+
+    public void writeToggleMark(PrintWriter out, String id) {
+        out.print("<span style=\"display:none;\" id=\"" + id + "_expanded\" >-&nbsp;</span>");
+        out.print("<span style=\"display:inline;\" id=\"" + id + "_collapsed\" >+</span>&nbsp;");
+    }
+
+    /**
+     * Out component with properties and it's facets and childrens
+     *
+     * @param context  TODO
+     * @param out
+     * @param viewRoot
+     */
+    private void writeComponent(FacesContext context, PrintWriter out, UIComponent component, String facetName) {
+        String clientId = "_tree:" + component.getClientId(context);
+
+        out.println("<dt onclick=\"toggle('" + clientId + "')\" class='tree'>");
+        writeToggleMark(out, clientId);
+
+        // out component name
+        if (null != facetName) {
+            out.print("Facet:'" + facetName + "' ");
+        }
+
+        out.println("<code>" + component.getClass().getName() + "</code> Id:[" + component.getId() + "]");
+        out.println("</dt>");
+        out.println("<dd id='" + clientId + "' style='display:none;'   class='tree' ><ul   class='tree'>");
+
+        // out bean properties
+        try {
+            Map<String, Object> attributes = component.getAttributes();
+            List<String> attributeNamesList = new ArrayList<String>(attributes.keySet());
+
+            Collections.sort(attributeNamesList);
+
+            for (String attributeName : attributeNamesList) {
+                ValueExpression ve = component.getValueExpression(attributeName);
+
+                if (ve != null) {
+                    writeAttribute(out, attributeName, ve.getExpressionString());
+                } else {
+                    if (!IGNORE_ATTRIBUTES.contains(attributeName)) {
+                        try {
+                            Object value = attributes.get(attributeName);
+
+                            writeAttribute(out, attributeName, value);
+                        } catch (Exception e) {
+                            writeAttribute(out, attributeName, null);
+                        }
+                    }
+                }
+            }
+        } catch (Exception e) {
+
+            // Do nothing - we in error page.
+        }
+
+        // out bindings
+        // out attributes map
+        for (Iterator<Entry<String, Object>> it = component.getAttributes().entrySet().iterator(); it.hasNext(); ) {
+            Entry<String, Object> entry = it.next();
+
+            writeAttribute(out, entry.getKey(), entry.getValue());
+        }
+
+        // out listeners
+        out.println("</ul></dd>");
+
+        if (component.getFacetCount() > 0 || component.getChildCount() > 0) {
+            out.println("<dd class='tree_childs'><dl class='tree_childs'>");
+
+            // out childs of this component
+            // facets
+            Map<String, UIComponent> facetsMap = component.getFacets();
+            List<String> facetNamesList = new ArrayList<String>(facetsMap.keySet());
+
+            Collections.sort(facetNamesList);
+
+            for (String nextFacetName : facetNamesList) {
+                writeComponent(context, out, facetsMap.get(nextFacetName), nextFacetName);
+            }
+
+            // childs components
+            for (Iterator<UIComponent> childIter = component.getChildren().iterator(); childIter.hasNext(); ) {
+                UIComponent child = childIter.next();
+
+                writeComponent(context, out, child, null);
+            }
+
+            out.println("</dl></dd>");
+        }
+    }
+
+    private void writeAttribute(PrintWriter out, String name, Object value) {
+        if (IGNORE_ATTRIBUTES.contains(name)) {
+            return;
+        }
+
+        if (name.startsWith("javax.faces.webapp.UIComponentTag.")) {
+            name = name.substring("javax.faces.webapp.UIComponentTag.".length());
+        }
+
+        out.print("<li>");
+        out.print(name);
+        out.print("=\"");
+
+        if (value != null) {
+            if (value instanceof UIComponent) {
+                out.print("[id:");
+                out.print(((UIComponent) value).getId());
+                out.print(']');
+            } else if (value instanceof Expression) {
+                out.print(((Expression) value).getExpressionString());
+            } else {
+                out.print(value.toString());
+            }
+        } else {
+            out.print("NULL");
+        }
+
+        out.println("\"</li>");
+    }
+
+    private void writeVariables(PrintWriter out, FacesContext faces) {
         ExternalContext ctx = faces.getExternalContext();
+
         writeVariables(out, ctx.getRequestParameterMap(), "Request Parameters");
         writeVariables(out, ctx.getRequestMap(), "Request Attributes");
+
         if (ctx.getSession(false) != null) {
             writeVariables(out, ctx.getSessionMap(), "Session Attributes");
         }
+
         writeVariables(out, ctx.getApplicationMap(), "Application Attributes");
     }
-    
-    private <K, V> void writeVariables(PrintWriter out, Map<K, V> vars, String caption)  {
+
+    private <K, V> void writeVariables(PrintWriter out, Map<K, V> vars, String caption) {
         out.print("<table><caption>");
         out.print(caption);
-        out.println("</caption><thead><tr><th style=\"width: 10%; \">Name</th><th style=\"width: 90%; \">Value</th></tr></thead><tbody>");
+        out.println("</caption><thead><tr><th style=\"width: 10%; \">Name</th><th style=\"width: 90%; \">"
+                    + "Value</th></tr></thead><tbody>");
+
         boolean written = false;
+
         if (!vars.isEmpty()) {
             SortedMap<K, V> map = new TreeMap<K, V>(vars);
             Map.Entry<K, V> entry = null;
             String key = null;
+
             for (Iterator<Entry<K, V>> itr = map.entrySet().iterator(); itr.hasNext(); ) {
                 entry = itr.next();
                 key = entry.getKey().toString();
+
                 if (key.indexOf('.') == -1) {
                     out.println("<tr><td>");
                     out.println(key.replaceAll("<", LT).replaceAll(">", GT));
                     out.println("</td><td><span class='value'>");
+
                     Object value = entry.getValue();
+
                     out.println(value.toString().replaceAll("<", LT).replaceAll(">", GT));
                     out.println("</span>");
-                    
-                    //TODO - commented after beanutils dependency removed - review
-//            		try {
-//            			PropertyDescriptor propertyDescriptors[] = PropertyUtils.getPropertyDescriptors(value);
-//            			if (propertyDescriptors.length>0) {
-//                			out.print("<div class='properties'><ul class=\'properties\'>");
-//							for (int i = 0; i < propertyDescriptors.length; i++) {
-//								String beanPropertyName = propertyDescriptors[i].getName(); 
-//								if (PropertyUtils.isReadable(value,beanPropertyName
-//										)) {
-//			            			out.print("<li class=\'properties\'>");
-//			            			out.print(beanPropertyName+" = "+BeanUtils.getProperty(value,beanPropertyName));
-//			            			out.print("</li>");
+
+                    // TODO - commented after beanutils dependency removed - review
+//                  try {
+//                        PropertyDescriptor propertyDescriptors[] = PropertyUtils.getPropertyDescriptors(value);
+//                        if (propertyDescriptors.length>0) {
+//                            out.print("<div class='properties'><ul class=\'properties\'>");
+//                            for (int i = 0; i < propertyDescriptors.length; i++) {
+//                                String beanPropertyName = propertyDescriptors[i].getName(); 
+//                                if (PropertyUtils.isReadable(value,beanPropertyName
+//                                        )) {
+//                                    out.print("<li class=\'properties\'>");
+//                                    out.print(beanPropertyName+" = "+BeanUtils.getProperty(value,beanPropertyName));
+//                                    out.print("</li>");
 //
-//								}
-//							}
-//	            			out.print("</ul></div>");
-//						}
-//            		} catch (Exception e) {
-//						// TODO: log exception
-//					}
-
+//                                }
+//                            }
+//                            out.print("</ul></div>");
+//                        }
+//                    } catch (Exception e) {
+//                        // TODO: log exception
+//                    }
                     out.println("</td></tr>");
                     written = true;
                 }
             }
         }
+
         if (!written) {
             out.println("<tr><td colspan=\"2\"><em>None</em></td></tr>");
         }
+
         out.println("</tbody></table>");
     }
-	/**
-	 * @param out
-	 */
-	private void writeScript(PrintWriter out) {
-		out
-				.println("<script type='text/javascript' language='javascript'>\n"
-						+ "function toggle(id) {\n"
-						+ "var style = document.getElementById(id).style;\n"
-						+ "if ('block' == style.display) {\n"
-						+ "style.display = 'none';\n"
-						+ "document.getElementById(id+'_collapsed').style.display = 'inline';\n"
-						+ "document.getElementById(id+'_expanded').style.display = 'none';\n"
-						+ "} else {\n"
-						+ "style.display = 'block';\n"
-						+ "document.getElementById(id+'_collapsed').style.display = 'none';\n"
-						+ "document.getElementById(id+'_expanded').style.display = 'inline';\n"
-						+ "}\n" + "}\n\n" +
 
-						"</script>");
-	}
+    /**
+     * @param out
+     */
+    private void writeScript(PrintWriter out) {
+        out.println("<script type='text/javascript' language='javascript'>\n" + "function toggle(id) {\n"
+                    + "var style = document.getElementById(id).style;\n" + "if ('block' == style.display) {\n"
+                    + "style.display = 'none';\n"
+                    + "document.getElementById(id+'_collapsed').style.display = 'inline';\n"
+                    + "document.getElementById(id+'_expanded').style.display = 'none';\n" + "} else {\n"
+                    + "style.display = 'block';\n"
+                    + "document.getElementById(id+'_collapsed').style.display = 'none';\n"
+                    + "document.getElementById(id+'_expanded').style.display = 'inline';\n" + "}\n" + "}\n\n"
+                    + "</script>");
+    }
 
-	/**
-	 * @param out
-	 */
-	private void writeStyleSheet(PrintWriter out) {
-		out
-				.println("<style type=\'text/css\' >\n" + 
-						"div.a4j_debug, .a4j_debug span, .a4j_debug td, .a4j_debug th, .a4j_debug caption { font-family: Verdana, Arial, Sans-Serif; }\n" + 
-						".a4j_debug li{\n" + 
-						"   list-style-position : inside;\n" + 
-						"}\n" + 
-						"\n" + 
-						".a4j_debug li, .a4j_debug pre { padding: 0; margin: 0;  font-size : 12px;}\n" + 
-						".a4j_debug ul { padding: 0 0 10 0; margin: 0;  font-size : 12px;}\n" + 
-						".a4j_debug h1 { color: #fff; background-color : #a00; font-size : 17px; padding : 7px 10px 10px 10px}\n" + 
-						"h2.a4j_debug , h2.a4j_debug  span { color: #a00;  font-size : 17px; padding : 0px 0px 0px 10px;}\n" + 
-						"h2.a4j_debug  a { text-decoration: none; color: #a00; }\n" + 
-						".exception { color: #000;  font-size : 14px; padding : 0px 0px 0px 10px;}\n" + 
-						".grayBox { padding: 8px; margin: 10px 0; border: 1px solid #CCC; background-color: #f9f9f9;   font-size : 12px; }\n" + 
-						"#error { color: #900; font-weight: bold; font-size: medium; }\n" + 
-						"#trace, #tree, #vars { display: none; }\n" + 
-						".a4j_debug code { font-size: medium;   font-size : 14px;}\n" + 
-						"#tree dl { color: #666; }\n" + 
-						"#tree dd {   font-size : 12px;}\n" + 
-						"#tree dt { border: 1px solid #DDD; padding: 2px 4px 4px 4px; border-left: 2px solid #a00; font-family: \"Courier New\", Courier, mono; font-size: small;   font-size : 12px; margin-top: 2px; margin-bottom: 2px;}\n" + 
-						".uicText { color: #999;  }\n" + 
-						".a4j_debug table { border: 1px solid #CCC; border-collapse: collapse; border-spacing: 0px; width: 100%; text-align: left; }\n" + 
-						".a4j_debug td { border: 1px solid #CCC;    font-size : 12px; vertical-align : top}\n" + 
-						".a4j_debug thead tr th { padding: 2px; color: #030; background-color: #F9F9F9;   font-size : 12px;}\n" + 
-						".a4j_debug tbody tr td { padding: 10px 6px; }\n" + 
-						".a4j_debug table caption { text-align: left; padding: 20 0 5 0; font-size : 12px; font-weight : bold;}\n" + 
-						".value {font-size : 12px; font-weight : bold;}\n" + 
-						"div.log { width: 100%; height: 400px;}\n" + 
-						"iframe.log { width: 99%; height: 99%; border: 1px solid #CCC;}\n" + 
-						"</style>");
-	}
-
+    /**
+     * @param out
+     */
+    private void writeStyleSheet(PrintWriter out) {
+        out.println(
+            "<style type=\'text/css\' >\n"
+            + "div.a4j_debug, .a4j_debug span, .a4j_debug td, .a4j_debug th, .a4j_debug caption { font-family: "
+            + "Verdana, Arial, Sans-Serif; }\n" + ".a4j_debug li{\n list-style-position : inside;\n}\n\n"
+            + ".a4j_debug li, .a4j_debug pre { padding: 0; margin: 0;  font-size : 12px;}\n"
+            + ".a4j_debug ul { padding: 0 0 10 0; margin: 0;  font-size : 12px;}\n"
+            + ".a4j_debug h1 { color: #fff; background-color :#a00; font-size :17px; padding :7px 10px 10px 10px}\n"
+            + "h2.a4j_debug , h2.a4j_debug  span { color: #a00;  font-size : 17px; padding : 0px 0px 0px 10px;}\n"
+            + "h2.a4j_debug  a { text-decoration: none; color: #a00; }\n"
+            + ".exception { color: #000;  font-size : 14px; padding : 0px 0px 0px 10px;}\n"
+            + ".grayBox { padding: 8px; margin: 10px 0; border: 1px solid #CCC; background-color:#f9f9f9; "
+            + "font-size:12px;}\n" + "#error { color: #900; font-weight: bold; font-size: medium; }\n"
+            + "#trace, #tree, #vars { display: none; }\n"
+            + ".a4j_debug code { font-size: medium;   font-size : 14px;}\n" + "#tree dl { color: #666; }\n"
+            + "#tree dd {   font-size : 12px;}\n"
+            + "#tree dt { border: 1px solid #DDD; padding: 2px 4px 4px 4px; border-left: 2px solid #a00; "
+            + "font-family: \"Courier New\", Courier, mono; font-size: small;   font-size : 12px; margin-top: 2px; "
+            + "margin-bottom: 2px;}\n" + ".uicText { color: #999;  }\n"
+            + ".a4j_debug table { border: 1px solid #CCC; border-collapse: collapse; border-spacing: 0px; width: "
+            + "100%; text-align: left; }\n"
+            + ".a4j_debug td { border: 1px solid #CCC;    font-size : 12px; vertical-align : top}\n"
+            + ".a4j_debug thead tr th { padding: 2px; color: #030; background-color: #F9F9F9; font-size : 12px;}\n"
+            + ".a4j_debug tbody tr td { padding: 10px 6px; }\n"
+            + ".a4j_debug table caption { text-align:left; padding: 20 0 5 0; font-size:12px; font-weight:bold;}\n"
+            + ".value {font-size : 12px; font-weight : bold;}\n" + "div.log { width: 100%; height: 400px;}\n"
+            + "iframe.log { width: 99%; height: 99%; border: 1px solid #CCC;}\n" + "</style>");
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/FacesErrorStateHolder.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/FacesErrorStateHolder.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/FacesErrorStateHolder.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.application;
 
 import javax.faces.component.UIViewRoot;
@@ -30,15 +32,14 @@
  *
  */
 public interface FacesErrorStateHolder {
-	
-	/**
-	 * @return detailed message about faces state on error in Html format 
-	 */
-	public String getFacesErrorStateMessage();
-	
-	/**
-	 * @return faces view tree at error point. 
-	 */
-	public UIViewRoot getFacesView();
 
+    /**
+     * @return detailed message about faces state on error in Html format
+     */
+    public String getFacesErrorStateMessage();
+
+    /**
+     * @return faces view tree at error point.
+     */
+    public UIViewRoot getFacesView();
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/application/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Classes required to implement and support application-level logic
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -14,41 +14,42 @@
  * limitations under the License.
  */
 
+
+
 package org.ajax4jsf.cache;
 
+import org.ajax4jsf.cache.lru.LRUMapCacheFactory;
+import org.ajax4jsf.resource.util.URLToStreamHelper;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Properties;
 
-import org.ajax4jsf.resource.util.URLToStreamHelper;
-import org.ajax4jsf.cache.lru.LRUMapCacheFactory;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * TODO stop caches on application stop
  * CacheManager is used in J2SE environments for looking up named caches.
  */
 public class CacheManager {
+    public static final String CACHE_MANAGER_FACTORY_CLASS = "org.ajax4jsf.cache.CACHE_MANAGER_FACTORY_CLASS";
 
+    private static final String[] DEFAULT_FACTORIES_CHAIN = {"org.ajax4jsf.cache.JBossCacheCacheFactory",
+        "org.ajax4jsf.cache.EhCacheCacheFactory"};
+    private static final String FACTORY_PROPERTY_NAME = "org.ajax4jsf.cache.CacheFactory";
     private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
+    private static final CacheManager INSTANCE = new CacheManager();
 
-    private static final String FACTORY_PROPERTY_NAME = "org.ajax4jsf.cache.CacheFactory";
-    public static final String CACHE_MANAGER_FACTORY_CLASS = "org.ajax4jsf.cache.CACHE_MANAGER_FACTORY_CLASS";
-
-    private static final String[] DEFAULT_FACTORIES_CHAIN = {
-            "org.ajax4jsf.cache.JBossCacheCacheFactory", "org.ajax4jsf.cache.EhCacheCacheFactory"
-    };
-
-    private static final CacheManager instance = new CacheManager();
-
     // REVIEW brian at quiotix.com
     // Should this be a HashMap<String, WeakReference<Cache>>?
     private final Map<String, Cache> caches = Collections.synchronizedMap(new HashMap<String, Cache>());
@@ -57,7 +58,7 @@
      * Returns the singleton CacheManager
      */
     public static CacheManager getInstance() {
-        return instance;
+        return INSTANCE;
     }
 
     public Cache getCache(String cacheName) {
@@ -66,6 +67,7 @@
 
     public Cache getNewCache(String cacheName, Map<?, ?> env) {
         createCache(cacheName, env);
+
         return getCache(cacheName);
     }
 
@@ -76,27 +78,30 @@
     public void createCache(String cacheName, Map<?, ?> env) {
         CacheFactory factory = getCacheFactory(env);
         Cache cache = factory.createCache(env);
+
         registerCache(cacheName, cache);
         cache.start();
     }
 
     public void destroyCache(String cacheName) {
         Cache cache = caches.remove(cacheName);
+
         cache.stop();
     }
 
     public CacheFactory getCacheFactory(Map<?, ?> env) {
         String[] factories;
+        String configuredFactoryName = findFactory(FACTORY_PROPERTY_NAME, env);
 
-        String configuredFactoryName = findFactory(FACTORY_PROPERTY_NAME, env);
         if (configuredFactoryName != null) {
             LOG.info("Configured to use [{0}] cache factory", configuredFactoryName);
-            factories = new String[]{configuredFactoryName};
+            factories = new String[] {configuredFactoryName};
         } else {
             factories = DEFAULT_FACTORIES_CHAIN;
         }
 
         ClassLoader loader = findClassLoader();
+
         for (String factoryName : factories) {
             try {
                 Class<?> spiClass = Class.forName(factoryName, true, loader);
@@ -106,11 +111,13 @@
 
                 return cacheFactory;
             } catch (Throwable iae) {
-                //TODO LOG debug
+
+                // TODO LOG debug
             }
         }
 
         LOG.info("Selected fallback cache factory");
+
         return new LRUMapCacheFactory();
     }
 
@@ -120,37 +127,42 @@
 
     private ClassLoader findClassLoader() {
         ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
         if (cl == null) {
             cl = ClassLoader.getSystemClassLoader();
         }
+
         return cl;
     }
 
     private static boolean isEmptyString(String s) {
-        return s == null || "".equals(s);
+        return (s == null) || "".equals(s);
     }
 
     String findFactory(String factoryId, Map<?, ?> env) {
+        String envFactoryClass = (String) env.get(CACHE_MANAGER_FACTORY_CLASS);
 
-        String envFactoryClass = (String) env.get(CACHE_MANAGER_FACTORY_CLASS);
         if (!isEmptyString(envFactoryClass)) {
             return envFactoryClass;
         }
 
         // Use the system property first
         String systemPropertyFactoryClass = searchInSystemProperty(factoryId);
+
         if (!isEmptyString(systemPropertyFactoryClass)) {
             return systemPropertyFactoryClass;
         }
 
         // try to read from $java.home/lib/jcache.properties
         String jcacheFactoryClass = searchInJcacheProperties(factoryId);
+
         if (!isEmptyString(jcacheFactoryClass)) {
             return jcacheFactoryClass;
         }
 
         // try to find services in CLASSPATH
         String classpathFactoryClass = searchInClasspath(factoryId);
+
         if (!isEmptyString(classpathFactoryClass)) {
             return classpathFactoryClass;
         }
@@ -161,10 +173,11 @@
     private String searchInClasspath(String factoryId) {
         try {
             ClassLoader cl = findClassLoader();
-            InputStream is = URLToStreamHelper.urlToStreamSafe(
-                    cl.getResource("META-INF/services/" + factoryId));
+            InputStream is = URLToStreamHelper.urlToStreamSafe(cl.getResource("META-INF/services/" + factoryId));
+
             if (is != null) {
                 BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
+
                 try {
                     return r.readLine();
                 } finally {
@@ -172,27 +185,38 @@
                 }
             }
         } catch (IOException ignore) {
+
+            // TODO Refactoring
         }
+
         return null;
     }
 
     private static String searchInJcacheProperties(String factoryId) {
         try {
-            String configFile = System.getProperty("java.home") +
-                    File.separator + "lib" + File.separator + "jcache.properties";
+            String configFile = System.getProperty("java.home") + File.separator + "lib" + File.separator
+                                + "jcache.properties";
             File file = new File(configFile);
+
             if (file.exists()) {
                 InputStream in = new FileInputStream(file);
+
                 try {
                     Properties props = new Properties();
+
                     props.load(in);
+
                     return props.getProperty(factoryId);
                 } finally {
                     in.close();
                 }
             }
         } catch (SecurityException ignore) {
+
+            // TODO Refactoring
         } catch (IOException ignore) {
+
+            // TODO Refactoring
         }
 
         return null;
@@ -202,7 +226,10 @@
         try {
             return System.getProperty(factoryId);
         } catch (SecurityException ignore) {
+
+            // TODO Refactoring
         }
+
         return null;
     }
 

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,54 +1,56 @@
+
 /**
- * 
+ *
  */
 package org.ajax4jsf.cache;
 
-import java.util.Date;
-
 import net.sf.ehcache.Ehcache;
 import net.sf.ehcache.Element;
 
+import java.util.Date;
+
 /**
  * @author Nick Belaevski
  * @since 4.0
  */
-
 public class EhCacheCache implements org.ajax4jsf.cache.Cache {
+    private net.sf.ehcache.Ehcache cache;
 
-	private net.sf.ehcache.Ehcache cache;
-	
-	public EhCacheCache(Ehcache cache) {
-		super();
-		this.cache = cache;
-	}
+    public EhCacheCache(Ehcache cache) {
+        super();
+        this.cache = cache;
+    }
 
-	public void start() {
-		cache.initialise();
-		cache.bootstrap();
-	}
-	
-	public void stop() {
-		cache.dispose();
-	}
-	
-	public Object get(Object key) {
-		Element element = cache.get(key);
-		if (element != null) {
-			return element.getObjectValue();
-		}
-		
-		return null;
-	}
+    public void start() {
+        cache.initialise();
+        cache.bootstrap();
+    }
 
-	public void put(Object key, Object value, Date expired) {
-		Boolean eternal = null; // use cache defaults
-		Integer ttl = null; 
-		if (expired != null) {
-			eternal = Boolean.FALSE;
-			ttl = (int) (expired.getTime() - System.currentTimeMillis()) / 1000;
-		}
+    public void stop() {
+        cache.dispose();
+    }
 
-		Element element = new Element(key, value, eternal, null, ttl);
-		cache.putQuiet(element);
-	}
+    public Object get(Object key) {
+        Element element = cache.get(key);
+
+        if (element != null) {
+            return element.getObjectValue();
+        }
+
+        return null;
+    }
+
+    public void put(Object key, Object value, Date expired) {
+        Boolean eternal = null; // use cache defaults
+        Integer ttl = null;
+
+        if (expired != null) {
+            eternal = Boolean.FALSE;
+            ttl = (int) (expired.getTime() - System.currentTimeMillis()) / 1000;
+        }
+
+        Element element = new Element(key, value, eternal, null, ttl);
+
+        cache.putQuiet(element);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  *
  */
@@ -3,15 +4,15 @@
 package org.ajax4jsf.cache;
 
-import java.util.Map;
+import org.richfaces.log.RichfacesLogger;
 
-import org.richfaces.log.RichfacesLogger;
 import org.slf4j.Logger;
 
+import java.util.Map;
+
 /**
  * @author Nick Belaevski
  * @since 4.0
  */
 public class EhCacheCacheFactory implements CacheFactory {
-
     private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
 
@@ -20,7 +21,7 @@
         LOG.info("Creating EhCache cache instance");
 
         net.sf.ehcache.Ehcache cache = new net.sf.ehcache.Cache("org.richfaces", 256, false, true, 0, 0);
+
         return new EhCacheCache(cache);
     }
-
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCache.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCache.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCache.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,8 +1,13 @@
+
 /**
- * 
+ *
  */
 package org.ajax4jsf.cache;
 
+import org.jboss.cache.Cache;
+import org.jboss.cache.Fqn;
+import org.jboss.cache.eviction.ExpirationAlgorithmConfig;
+
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
@@ -14,76 +19,78 @@
 import javax.transaction.SystemException;
 import javax.transaction.Transaction;
 
-import org.jboss.cache.Cache;
-import org.jboss.cache.Fqn;
-import org.jboss.cache.eviction.ExpirationAlgorithmConfig;
-
 /**
  * @author Nick Belaevski
  * @since 4.0
  */
 public class JBossCacheCache implements org.ajax4jsf.cache.Cache {
+    private static final String RESOURCE = "resource";
+    private Cache<String, Object> cache;
 
-	private Cache<String, Object> cache;
+    public JBossCacheCache(Cache<String, Object> cache) {
+        super();
+        this.cache = cache;
+    }
 
-	private static final String RESOURCE = "resource";
-	
-	public JBossCacheCache(Cache<String, Object> cache) {
-		super();
-		
-		this.cache = cache;
-	}
+    private Fqn<Object> createFqn(Object key) {
+        return Fqn.fromElements(key);
+    }
 
-	private Fqn<Object> createFqn(Object key) {
-		return Fqn.fromElements(key);
-	}
-	
-	public Object get(Object key) {
-		return cache.get(createFqn(key), RESOURCE);
-	}
+    public Object get(Object key) {
+        return cache.get(createFqn(key), RESOURCE);
+    }
 
-	public void put(Object key, Object value, Date expired) {
-		Map<String,Object> map = new HashMap<String, Object>(3);
-		
-		map.put(RESOURCE, value);
-		if (expired != null) {
-			map.put(ExpirationAlgorithmConfig.EXPIRATION_KEY, expired.getTime());
-		}
-		
-		cache.put(createFqn(key), map);
-		Transaction transaction = cache.getInvocationContext().getTransaction();
-		
-		try {
-			//TODO: to review
-			if (transaction != null && transaction.getStatus() == Status.STATUS_ACTIVE) {
-				transaction.commit();
-			}
-		} catch (SystemException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (SecurityException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (IllegalStateException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (RollbackException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (HeuristicMixedException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (HeuristicRollbackException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-	}
+    public void put(Object key, Object value, Date expired) {
+        Map<String, Object> map = new HashMap<String, Object>(3);
 
-	public void start() {
-		cache.start();
-	}
+        map.put(RESOURCE, value);
 
-	public void stop() {
-		cache.stop();
-	}
+        if (expired != null) {
+            map.put(ExpirationAlgorithmConfig.EXPIRATION_KEY, expired.getTime());
+        }
+
+        cache.put(createFqn(key), map);
+
+        Transaction transaction = cache.getInvocationContext().getTransaction();
+
+        try {
+
+            // TODO: to review
+            if ((transaction != null) && (transaction.getStatus() == Status.STATUS_ACTIVE)) {
+                transaction.commit();
+            }
+        } catch (SystemException e) {
+
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (SecurityException e) {
+
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (IllegalStateException e) {
+
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (RollbackException e) {
+
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (HeuristicMixedException e) {
+
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (HeuristicRollbackException e) {
+
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    public void start() {
+        cache.start();
+    }
+
+    public void stop() {
+        cache.stop();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCacheFactory.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCacheFactory.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCacheFactory.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,16 +1,11 @@
+
 /**
- * 
+ *
  */
 package org.ajax4jsf.cache;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.Map;
+import org.ajax4jsf.resource.util.URLToStreamHelper;
 
-import javax.faces.FacesException;
-
-import org.ajax4jsf.resource.util.URLToStreamHelper;
 import org.jboss.cache.Cache;
 import org.jboss.cache.DefaultCacheFactory;
 import org.jboss.cache.Fqn;
@@ -19,62 +14,71 @@
 import org.jboss.cache.config.EvictionRegionConfig;
 import org.jboss.cache.eviction.ExpirationAlgorithmConfig;
 
+import java.io.IOException;
+import java.io.InputStream;
+
+import java.net.URL;
+
+import java.util.Map;
+
+import javax.faces.FacesException;
+
 /**
  * @author Nick Belaevski
  * @since 4.0
  */
- 
+
 //TODO - to doc - no max size eviction support
 public class JBossCacheCacheFactory implements CacheFactory {
+    private org.jboss.cache.CacheFactory<String, Object> cacheFactory;
 
-	private org.jboss.cache.CacheFactory<String, Object> cacheFactory;
-	
-	public JBossCacheCacheFactory() {
-		super();
-	
-		cacheFactory = new DefaultCacheFactory<String, Object>();
-	}
+    public JBossCacheCacheFactory() {
+        super();
+        cacheFactory = new DefaultCacheFactory<String, Object>();
+    }
 
-	public org.ajax4jsf.cache.Cache createCache(Map<?, ?> env) {
-		ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
-		Cache<String, Object> cache = null;
-		URL cacheConfigurationURL = null;
-		if (contextClassLoader != null) {
-			cacheConfigurationURL = contextClassLoader.getResource("/jboss-cache.xml");
-		}
-		
-		if (cacheConfigurationURL != null) {
-			InputStream stream = null;
-			try {
-				stream = URLToStreamHelper.urlToStream(cacheConfigurationURL);
-				cache = cacheFactory.createCache(stream);
-			} catch (IOException e) {
-				throw new FacesException(e.getLocalizedMessage(), e);
-			} finally {
-				if (stream != null) {
-					try {
-						stream.close();
-					} catch (IOException e) {
-						// TODO Auto-generated catch block
-						e.printStackTrace();
-					}
-				}
-			}
-		} else {
-			Configuration configuration = new Configuration();
+    public org.ajax4jsf.cache.Cache createCache(Map<?, ?> env) {
+        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+        Cache<String, Object> cache = null;
+        URL cacheConfigurationURL = null;
 
-			EvictionRegionConfig evictionRegionConfig = new EvictionRegionConfig(Fqn.root());
-			ExpirationAlgorithmConfig expirationAlgorithm = new ExpirationAlgorithmConfig();
-			evictionRegionConfig.setEvictionAlgorithmConfig(expirationAlgorithm);
-			
-			EvictionConfig evictionConfig = new EvictionConfig(evictionRegionConfig);
-			evictionConfig.setWakeupInterval(1000);
+        if (contextClassLoader != null) {
+            cacheConfigurationURL = contextClassLoader.getResource("/jboss-cache.xml");
+        }
 
-			configuration.setEvictionConfig(evictionConfig);
-			cache = cacheFactory.createCache(configuration);
-		}
-		
-		return new JBossCacheCache(cache);
-	}
-	
+        if (cacheConfigurationURL != null) {
+            InputStream stream = null;
+
+            try {
+                stream = URLToStreamHelper.urlToStream(cacheConfigurationURL);
+                cache = cacheFactory.createCache(stream);
+            } catch (IOException e) {
+                throw new FacesException(e.getLocalizedMessage(), e);
+            } finally {
+                if (stream != null) {
+                    try {
+                        stream.close();
+                    } catch (IOException e) {
+
+                        // TODO Auto-generated catch block
+                        e.printStackTrace();
+                    }
+                }
+            }
+        } else {
+            Configuration configuration = new Configuration();
+            EvictionRegionConfig evictionRegionConfig = new EvictionRegionConfig(Fqn.root());
+            ExpirationAlgorithmConfig expirationAlgorithm = new ExpirationAlgorithmConfig();
+
+            evictionRegionConfig.setEvictionAlgorithmConfig(expirationAlgorithm);
+
+            EvictionConfig evictionConfig = new EvictionConfig(evictionRegionConfig);
+
+            evictionConfig.setWakeupInterval(1000);
+            configuration.setEvictionConfig(evictionConfig);
+            cache = cacheFactory.createCache(configuration);
+        }
+
+        return new JBossCacheCache(cache);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCache.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCache.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCache.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,56 +19,60 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.cache;
 
-import java.util.Date;
-
 import com.opensymphony.oscache.base.EntryRefreshPolicy;
 import com.opensymphony.oscache.base.NeedsRefreshException;
 import com.opensymphony.oscache.web.filter.ExpiresRefreshPolicy;
 
+import java.util.Date;
 
 /**
  * @author Nick - mailto:nbelaevski at exadel.com
  * created 01.05.2007
- * 
+ *
  */
 public class OSCacheCache implements Cache {
+    private com.opensymphony.oscache.base.Cache cache;
 
-	private com.opensymphony.oscache.base.Cache cache;
+    public OSCacheCache(com.opensymphony.oscache.base.Cache cache) {
+        super();
+        this.cache = cache;
+    }
 
-	public OSCacheCache(com.opensymphony.oscache.base.Cache cache) {
-		super();
-		this.cache = cache;
-	}
+    public Object get(Object key) {
+        String stringKey = (String) key;
 
-	public Object get(Object key) {
-		String stringKey = (String) key;
+        try {
+            return cache.getFromCache(stringKey);
+        } catch (NeedsRefreshException e) {
+            cache.removeEntry(stringKey);
 
-		try {
-			return cache.getFromCache(stringKey);
-		} catch (NeedsRefreshException e) {
-			cache.removeEntry(stringKey);
-			return null;
-		}
-	}
+            return null;
+        }
+    }
 
-	public void put(Object key, Object value, Date expired) {
-		EntryRefreshPolicy refreshPolicy = null;
-		if (expired != null) {
-			int ttl = (int) (expired.getTime() - System.currentTimeMillis()) / 1000;
-			refreshPolicy = new ExpiresRefreshPolicy(ttl);
-		}
-		
-		cache.putInCache((String) key, value, refreshPolicy);
-	}
+    public void put(Object key, Object value, Date expired) {
+        EntryRefreshPolicy refreshPolicy = null;
 
-	public void start() {
-		// TODO Auto-generated method stub
-	}
+        if (expired != null) {
+            int ttl = (int) (expired.getTime() - System.currentTimeMillis()) / 1000;
 
-	public void stop() {
-		// TODO Auto-generated method stub
-		
-	}
+            refreshPolicy = new ExpiresRefreshPolicy(ttl);
+        }
+
+        cache.putInCache((String) key, value, refreshPolicy);
+    }
+
+    public void start() {
+
+        // TODO Auto-generated method stub
+    }
+
+    public void stop() {
+
+        // TODO Auto-generated method stub
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,40 +19,47 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.cache;
 
+import com.opensymphony.oscache.general.GeneralCacheAdministrator;
+
+import org.ajax4jsf.resource.util.URLToStreamHelper;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
 import java.io.InputStream;
+
 import java.net.URL;
+
 import java.util.Map;
 import java.util.Properties;
 
-import org.ajax4jsf.resource.util.URLToStreamHelper;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
-import com.opensymphony.oscache.general.GeneralCacheAdministrator;
-
 /**
  * @author Nick - mailto:nbelaevski at exadel.com
  *         created 01.05.2007
  */
 public class OSCacheCacheFactory implements CacheFactory {
-
     private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
 
     private static Properties loadProperties() throws IOException {
         Properties properties = new Properties();
+        URL resource = OSCacheCache.class.getResource("oscache.properties");
 
-        URL resource = OSCacheCache.class.getResource("oscache.properties");
         if (resource != null) {
             InputStream stream = URLToStreamHelper.urlToStream(resource);
+
             try {
                 properties.load(stream);
             } finally {
                 try {
                     stream.close();
                 } catch (IOException e) {
+
                     // TODO: handle exception
                 }
             }
@@ -63,9 +70,11 @@
 
     public Cache createCache(Map<?, ?> env) {
         Properties cacheProperties = new Properties();
+
         try {
             cacheProperties.putAll(loadProperties());
         } catch (IOException e) {
+
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
@@ -73,15 +82,16 @@
         try {
             cacheProperties.putAll(loadProperties());
         } catch (IOException e) {
+
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
 
         cacheProperties.putAll(env);
+        LOG.info("Creating OSCache cache instance using parameters: " + cacheProperties);
 
-        LOG.info("Creating OSCache cache instance using parameters: " + cacheProperties);
         GeneralCacheAdministrator cacheAdministrator = new GeneralCacheAdministrator(cacheProperties);
+
         return new OSCacheCache(cacheAdministrator.getCache());
     }
-
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMap.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMap.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMap.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.cache;
 
 import java.util.AbstractMap;
@@ -64,7 +66,6 @@
     }
 
     private class MyAbstractSet extends AbstractSet<Map.Entry<String, String>> {
-
         @Override
         public Iterator<Map.Entry<String, String>> iterator() {
             return new MyIterator();
@@ -73,9 +74,8 @@
         @Override
         public int size() {
             int result = 0;
+            @SuppressWarnings("unchecked") Enumeration<String> initNames = servletContext.getInitParameterNames();
 
-            @SuppressWarnings("unchecked")
-            Enumeration<String> initNames = servletContext.getInitParameterNames();
             while (initNames.hasMoreElements()) {
                 initNames.nextElement();
                 result++;
@@ -90,8 +90,8 @@
         }
     }
 
+
     private class MyIterator implements Iterator<Map.Entry<String, String>> {
-
         @SuppressWarnings("unchecked")
         private Enumeration<String> initNames = servletContext.getInitParameterNames();
 

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMapEntry.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMapEntry.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMapEntry.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.cache;
 
 import java.util.Map;
@@ -28,7 +30,6 @@
  * Date: Oct 13, 2009
  */
 class ServletContextInitMapEntry<K, V> implements Map.Entry<K, V> {
-
     private K key;
     private V value;
 
@@ -49,5 +50,4 @@
     public V setValue(V value) {
         throw new UnsupportedOperationException("This map is read-only");
     }
-
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
 
+
+
 package org.ajax4jsf.cache.lru;
 
 import java.util.Date;
@@ -28,19 +30,15 @@
  * Date: Oct 13, 2009
  */
 public final class CacheEntry implements Comparable<CacheEntry> {
-
+    private Date expired;
     private Object key;
-
     private Object value;
 
-    private Date expired;
-
     public CacheEntry(Object key, Object value, Date expired) {
         super();
-
         this.key = key;
         this.value = value;
-        this.expired = expired == null ? null : (Date) expired.clone();
+        this.expired = (expired == null) ? null : (Date) expired.clone();
     }
 
     public Object getKey() {
@@ -52,17 +50,19 @@
     }
 
     public boolean isExpired() {
-        return expired != null && System.currentTimeMillis() >= expired.getTime();
+        return (expired != null) && (System.currentTimeMillis() >= expired.getTime());
     }
 
     public Date getExpired() {
-        return expired == null ? null : (Date) expired.clone();
+        return (expired == null) ? null : (Date) expired.clone();
     }
 
-    //due to PriorityQueue bug in JDK 1.5 comparator should return 0 ONLY if entries are equal
+    // due to PriorityQueue bug in JDK 1.5 comparator should return 0 ONLY if entries are equal
     public int compareTo(CacheEntry o) {
-        //reverse sort order
+
+        // reverse sort order
         int result = expired.compareTo(o.expired);
+
         if (result == 0) {
             result = key.toString().compareTo(o.key.toString());
         }
@@ -74,32 +74,42 @@
     public int hashCode() {
         final int prime = 31;
         int result = 1;
+
         result = prime * result + ((key == null) ? 0 : key.hashCode());
+
         return result;
     }
 
-    //see compareTo()
+    // see compareTo()
     @Override
     public boolean equals(Object obj) {
         if (this == obj) {
             return true;
         }
+
         if (obj == null) {
             return false;
         }
-        if (getClass() != obj.getClass())
+
+        if (getClass() != obj.getClass()) {
             return false;
+        }
+
         CacheEntry other = (CacheEntry) obj;
+
         if (key == null) {
-            if (other.key != null)
+            if (other.key != null) {
                 return false;
-        } else if (!key.equals(other.key))
+            }
+        } else if (!key.equals(other.key)) {
             return false;
+        }
+
         return true;
     }
 
     @Override
     public String toString() {
-        return expired == null ? key.toString() : key + ": " + expired;
+        return (expired == null) ? key.toString() : key + ": " + expired;
     }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheMap.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheMap.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheMap.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
 
+
+
 package org.ajax4jsf.cache.lru;
 
 import org.ajax4jsf.util.LRUMap;
@@ -30,8 +32,8 @@
  * Date: Oct 13, 2009
  */
 public final class CacheMap extends LRUMap<Object, CacheEntry> {
-
     private static final long serialVersionUID = -5422668357346537621L;
+    private PriorityQueue<CacheEntry> expirationQueue = new PriorityQueue<CacheEntry>();
 
     public CacheMap() {
         super();
@@ -41,8 +43,6 @@
         super(capacity);
     }
 
-    private PriorityQueue<CacheEntry> expirationQueue = new PriorityQueue<CacheEntry>();
-
     public PriorityQueue<CacheEntry> getExpirationQueue() {
         return expirationQueue;
     }
@@ -50,8 +50,10 @@
     @Override
     public CacheEntry put(Object key, CacheEntry value) {
         CacheEntry entry = super.put(key, value);
+
         if (entry != null) {
-            //prolong
+
+            // prolong
             expirationQueue.remove(entry);
         }
 
@@ -65,6 +67,7 @@
     @Override
     public CacheEntry remove(Object key) {
         CacheEntry entry = super.remove(key);
+
         if (entry != null) {
             expirationQueue.remove(entry);
         }
@@ -81,13 +84,10 @@
     public void purge() {
         CacheEntry queueEntry = expirationQueue.peek();
 
-        while (queueEntry != null && queueEntry.isExpired()) {
+        while ((queueEntry != null) && queueEntry.isExpired()) {
             super.remove(queueEntry.getKey());
             expirationQueue.remove();
-
             queueEntry = expirationQueue.peek();
         }
     }
 }
-
-

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCache.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCache.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCache.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,50 +19,52 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
 
+
+
 package org.ajax4jsf.cache.lru;
 
+import org.ajax4jsf.cache.Cache;
+
 import java.util.Date;
 
-import org.ajax4jsf.cache.Cache;
-
 /**
  * @author Nick - mailto:nbelaevski at exadel.com
  * @since 3.1
  */
 public class LRUMapCache implements Cache {
+    private CacheMap map;
 
-	private CacheMap map;
-	
-	public LRUMapCache() {
-		this.map = new CacheMap();
-	}
-	
-	public LRUMapCache(int capacity) {
-		this.map = new CacheMap(capacity);
-	}
-	
-	public synchronized Object get(Object key) {
-		this.map.purge();
+    public LRUMapCache() {
+        this.map = new CacheMap();
+    }
 
-		CacheEntry entry = this.map.get(key);
-		if (entry != null) {
-			return entry.getValue();
-		}
-		
-		return null;
-	}
+    public LRUMapCache(int capacity) {
+        this.map = new CacheMap(capacity);
+    }
 
-	public synchronized void put(Object key, Object value, Date expired) {
-		this.map.purge();
+    public synchronized Object get(Object key) {
+        this.map.purge();
 
-		CacheEntry cacheEntry = new CacheEntry(key, value, expired);
-		this.map.put(key, cacheEntry);
-	}
+        CacheEntry entry = this.map.get(key);
 
-	public void start() {
-	}
+        if (entry != null) {
+            return entry.getValue();
+        }
 
-	public void stop() {
-		this.map.clear();
-	}
+        return null;
+    }
+
+    public synchronized void put(Object key, Object value, Date expired) {
+        this.map.purge();
+
+        CacheEntry cacheEntry = new CacheEntry(key, value, expired);
+
+        this.map.put(key, cacheEntry);
+    }
+
+    public void start() {}
+
+    public void stop() {
+        this.map.clear();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,37 +19,41 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.cache.lru;
 
-import java.util.Map;
+import org.ajax4jsf.cache.Cache;
+import org.ajax4jsf.cache.CacheFactory;
 
 import org.richfaces.log.RichfacesLogger;
+
 import org.slf4j.Logger;
-import org.ajax4jsf.cache.lru.LRUMapCache;
-import org.ajax4jsf.cache.CacheFactory;
-import org.ajax4jsf.cache.Cache;
 
+import java.util.Map;
 
 /**
  * @author Nick - mailto:nbelaevski at exadel.com
  *         created 01.05.2007
  */
 public class LRUMapCacheFactory implements CacheFactory {
-
+    public static final String CACHE_SIZE_PARAMETER = "org.ajax4jsf.cache.LRU_MAP_CACHE_SIZE";
     private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
 
-    public static final String CACHE_SIZE_PARAMETER = "org.ajax4jsf.cache.LRU_MAP_CACHE_SIZE";
-
     public Cache createCache(Map<?, ?> env) {
         LOG.info("Creating LRUMap cache instance using parameters: " + env);
 
         String size = (String) env.get(CACHE_SIZE_PARAMETER);
-        if (size == null || size.length() == 0) {
+
+        if ((size == null) || (size.length() == 0)) {
             LOG.info("Creating LRUMap cache instance of default capacity");
+
             return new LRUMapCache();
         } else {
             int parsedSize = Integer.parseInt(size);
+
             LOG.info("Creating LRUMap cache instance of " + parsedSize + " items capacity");
+
             return new LRUMapCache(parsedSize);
         }
     }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Cache implementations
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxActionComponent.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxActionComponent.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxActionComponent.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.component;
 
+import org.ajax4jsf.context.AjaxContext;
+import org.ajax4jsf.event.AjaxEvent;
+import org.ajax4jsf.event.AjaxListener;
+import org.ajax4jsf.event.AjaxSource;
+import org.ajax4jsf.renderkit.RendererUtils;
+
 import javax.faces.component.UICommand;
 import javax.faces.component.UIComponent;
 import javax.faces.context.FacesContext;
@@ -29,130 +37,129 @@
 import javax.faces.event.FacesEvent;
 import javax.faces.event.PhaseId;
 
-import org.ajax4jsf.context.AjaxContext;
-import org.ajax4jsf.event.AjaxEvent;
-import org.ajax4jsf.event.AjaxListener;
-import org.ajax4jsf.event.AjaxSource;
-import org.ajax4jsf.renderkit.RendererUtils;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.3 $ $Date: 2007/02/06 16:23:21 $
- * 
+ *
  */
-public abstract class AjaxActionComponent extends UICommand implements
-		AjaxComponent, AjaxSource {
+public abstract class AjaxActionComponent extends UICommand implements AjaxComponent, AjaxSource {
+    public static final String FOCUS_DATA_ID = "_A4J.AJAX.focus";
 
-	public static final String FOCUS_DATA_ID = "_A4J.AJAX.focus";
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.UIComponentBase#broadcast(javax.faces.event.FacesEvent)
+     */
+    public void broadcast(FacesEvent event) throws AbortProcessingException {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.UIComponentBase#broadcast(javax.faces.event.FacesEvent)
-	 */
-	public void broadcast(FacesEvent event) throws AbortProcessingException {
-		// perform default
-		super.broadcast(event);
-		if (event instanceof AjaxEvent) {
-			FacesContext context = getFacesContext();
-			// complete re-Render fields. AjaxEvent deliver before render
-			// response.
-			setupReRender(context);
-			// Put data for send in response
-			Object data = getData();
-			AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-			if (null != data) {
-				ajaxContext.setResponseData(data);
-			}
-			String focus = getFocus();
-			if (null != focus) {
-				// search for component in tree.
-				// XXX - use more pourful search, as in h:outputLabel
-				// component.
-				UIComponent focusComponent = RendererUtils.getInstance().
-					findComponentFor(this, focus);
-				if (null != focusComponent) {
-					focus = focusComponent.getClientId(context);
-				}
-				ajaxContext.getResponseDataMap().put(FOCUS_DATA_ID, focus);
-			}
-			ajaxContext.setOncomplete(getOncomplete());
-		}
-	}
+        // perform default
+        super.broadcast(event);
 
-	/**
-	 * Template method with old signature, for backward compability.
-	 */
-	protected void setupReRender() {
-	}
+        if (event instanceof AjaxEvent) {
+            FacesContext context = getFacesContext();
 
-	/**
-	 * Template methods for fill set of resions to render in subclasses.
-	 * 
-	 * @param facesContext
-	 *            TODO
-	 */
-	protected void setupReRender(FacesContext facesContext) {
-		AjaxContext.getCurrentInstance(facesContext).addRegionsFromComponent(
-				this);
-		setupReRender();
-	}
+            // complete re-Render fields. AjaxEvent deliver before render
+            // response.
+            setupReRender(context);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent)
-	 */
-	public void queueEvent(FacesEvent event) {
-		if (event instanceof ActionEvent) {
-			if (event.getComponent() == this) {
-				if (isImmediate()) {
-					event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
-				} else if (isBypassUpdates()) {
-					event.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
-				} else {
-					event.setPhaseId(PhaseId.INVOKE_APPLICATION);
-				}
-			}
-			// UICommand set Phase ID for all ActionEvents - bypass it.
-			getParent().queueEvent(event);
-		} else {
-			super.queueEvent(event);
-		}
-	}
+            // Put data for send in response
+            Object data = getData();
+            AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxSource#addAjaxListener(org.ajax4jsf.framework.ajax.AjaxListener)
-	 */
-	public void addAjaxListener(AjaxListener listener) {
-		addFacesListener(listener);
-	}
+            if (null != data) {
+                ajaxContext.setResponseData(data);
+            }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxSource#getAjaxListeners()
-	 */
-	public AjaxListener[] getAjaxListeners() {
-		AjaxListener al[] = (AjaxListener[]) getFacesListeners(AjaxListener.class);
-		return (al);
+            String focus = getFocus();
 
-	}
+            if (null != focus) {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxSource#removeAjaxListener(org.ajax4jsf.framework.ajax.AjaxListener)
-	 */
-	public void removeAjaxListener(AjaxListener listener) {
-		removeFacesListener(listener);
+                // search for component in tree.
+                // XXX - use more pourful search, as in h:outputLabel
+                // component.
+                UIComponent focusComponent = RendererUtils.getInstance().findComponentFor(this, focus);
 
-	}
+                if (null != focusComponent) {
+                    focus = focusComponent.getClientId(context);
+                }
 
-	protected UIComponent getSingleComponent() {
-		return this;
-	}
+                ajaxContext.getResponseDataMap().put(FOCUS_DATA_ID, focus);
+            }
 
+            ajaxContext.setOncomplete(getOncomplete());
+        }
+    }
+
+    /**
+     * Template method with old signature, for backward compability.
+     */
+    protected void setupReRender() {}
+
+    /**
+     * Template methods for fill set of resions to render in subclasses.
+     *
+     * @param facesContext
+     *            TODO
+     */
+    protected void setupReRender(FacesContext facesContext) {
+        AjaxContext.getCurrentInstance(facesContext).addRegionsFromComponent(this);
+        setupReRender();
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent)
+     */
+    public void queueEvent(FacesEvent event) {
+        if (event instanceof ActionEvent) {
+            if (event.getComponent() == this) {
+                if (isImmediate()) {
+                    event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
+                } else if (isBypassUpdates()) {
+                    event.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
+                } else {
+                    event.setPhaseId(PhaseId.INVOKE_APPLICATION);
+                }
+            }
+
+            // UICommand set Phase ID for all ActionEvents - bypass it.
+            getParent().queueEvent(event);
+        } else {
+            super.queueEvent(event);
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxSource#addAjaxListener(org.ajax4jsf.framework.ajax.AjaxListener)
+     */
+    public void addAjaxListener(AjaxListener listener) {
+        addFacesListener(listener);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxSource#getAjaxListeners()
+     */
+    public AjaxListener[] getAjaxListeners() {
+        AjaxListener[] al = (AjaxListener[]) getFacesListeners(AjaxListener.class);
+
+        return al;
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxSource#removeAjaxListener(org.ajax4jsf.framework.ajax.AjaxListener)
+     */
+    public void removeAjaxListener(AjaxListener listener) {
+        removeFacesListener(listener);
+    }
+
+    protected UIComponent getSingleComponent() {
+        return this;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxInputComponent.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxInputComponent.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxInputComponent.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.component;
 
+import org.ajax4jsf.context.AjaxContext;
+import org.ajax4jsf.event.AjaxEvent;
+
 import javax.faces.component.EditableValueHolder;
 import javax.faces.component.UIInput;
 import javax.faces.context.FacesContext;
@@ -29,52 +34,54 @@
 import javax.faces.event.FacesEvent;
 import javax.faces.event.PhaseId;
 
-import org.ajax4jsf.context.AjaxContext;
-import org.ajax4jsf.event.AjaxEvent;
-
-
 /**
  * Base class for all AJAX-enabled Input components
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.2 $ $Date: 2007/02/06 16:23:21 $
  *
  */
-public abstract class AjaxInputComponent extends UIInput implements AjaxComponent,EditableValueHolder {
+public abstract class AjaxInputComponent extends UIInput implements AjaxComponent, EditableValueHolder {
 
-	/* (non-Javadoc)
-	 * @see javax.faces.component.UIComponentBase#broadcast(javax.faces.event.FacesEvent)
-	 */
-	public void broadcast(FacesEvent event) throws AbortProcessingException {
-		// perform default
-		super.broadcast(event);
-		if (event instanceof AjaxEvent) {
-			// complete re-Render fields. AjaxEvent deliver before render response.
-			setupReRender();
-		}
-	}
-	/**
-	 * Template methods for fill set of resions to render in subclasses.
-	 */
-	protected void setupReRender() {
-		FacesContext context = getFacesContext();
-		AjaxContext.getCurrentInstance(context).addRegionsFromComponent(this);
-		
-	}
-	/* (non-Javadoc)
-	 * @see javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent)
-	 */
-	public void queueEvent(FacesEvent event) {
-		if (event instanceof ActionEvent && event.getComponent()==this) {
-			if (isImmediate()) {
-				event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
-			}  else if (isBypassUpdates()) {
-				event.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
-			}else {
-				event.setPhaseId(PhaseId.INVOKE_APPLICATION);
-			}
-		}
-		super.queueEvent(event);
-	}
-    
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.component.UIComponentBase#broadcast(javax.faces.event.FacesEvent)
+     */
+    public void broadcast(FacesEvent event) throws AbortProcessingException {
 
+        // perform default
+        super.broadcast(event);
+
+        if (event instanceof AjaxEvent) {
+
+            // complete re-Render fields. AjaxEvent deliver before render response.
+            setupReRender();
+        }
+    }
+
+    /**
+     * Template methods for fill set of resions to render in subclasses.
+     */
+    protected void setupReRender() {
+        FacesContext context = getFacesContext();
+
+        AjaxContext.getCurrentInstance(context).addRegionsFromComponent(this);
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent)
+     */
+    public void queueEvent(FacesEvent event) {
+        if ((event instanceof ActionEvent) && (event.getComponent() == this)) {
+            if (isImmediate()) {
+                event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
+            } else if (isBypassUpdates()) {
+                event.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
+            } else {
+                event.setPhaseId(PhaseId.INVOKE_APPLICATION);
+            }
+        }
+
+        super.queueEvent(event);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxLoadBundleComponent.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxLoadBundleComponent.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxLoadBundleComponent.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.component;
 
 /**
@@ -26,6 +28,4 @@
  *
  * Marker interface for UILoadBundle component
  */
-public interface AjaxLoadBundleComponent {
-
-}
+public interface AjaxLoadBundleComponent {}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxRegionBrige.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxRegionBrige.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxRegionBrige.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,12 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.component;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.event.AjaxEvent;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import javax.el.ELContext;
 import javax.el.MethodExpression;
 import javax.el.ValueExpression;
-import javax.faces.application.Application;
+
 import javax.faces.component.StateHolder;
 import javax.faces.component.UIComponent;
 import javax.faces.component.UIComponentBase;
@@ -32,37 +41,29 @@
 import javax.faces.event.AbortProcessingException;
 import javax.faces.event.FacesEvent;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.event.AjaxEvent;
-import org.ajax4jsf.event.AjaxListener;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
-
 /**
  * @author shura
- * 
+ *
  * Brige design pattern for any UIComponent append support ajax partial rendering. For AJAX request, apply
  * ActionListeniers, construct list of components for render - by direct setting
- * from Listenier or Components bean methods. 
+ * from Listenier or Components bean methods.
  * For use in concrete component, in constructor must be instantiated to class field as :
  * private AjaxRegionBrige brige;
  * ....
- * Constructor(){ 
+ * Constructor(){
  * brige = new AjaxRegionBrige(this);
  * }.
- * And delegate all brige public methods. 
+ * And delegate all brige public methods.
  * @See <code>AJAXConatiner</code> interface , or from configuration - by
  *      <ajax:forupdate>jsp tag's of this or nested components, or from all
  *      <code>UIForm</code> components instances with <code>isSubmitted</code>
  *      set to <code>true</code>
- *  
+ *
  */
-public class AjaxRegionBrige  implements AjaxContainerBase, StateHolder{
+public class AjaxRegionBrige implements AjaxContainerBase, StateHolder {
 
-
     // Private Fields
-    private static final Logger log = RichfacesLogger.COMPONENTS.getLogger();
+    private static final Logger LOG = RichfacesLogger.COMPONENTS.getLogger();
 
     /**
      * Listener for call on Ajax Requests
@@ -70,33 +71,28 @@
     private MethodExpression ajaxListener = null;
 
     /**
-     * Flag for immediate call listeners 
+     * Flag for immediate call listeners
      */
     private boolean immediate = false;
     private boolean immediateSet = false;
-
     private boolean selfRendered = false;
     private boolean selfRenderedSet = false;
-
     private boolean transientFlag = false;
-    
-    private UIComponent component ;
-    
     private boolean submitted = false;
-    
+    private UIComponent component;
 
     // Interface implementation
 
     /**
-	 * @param component
-	 */
-	public AjaxRegionBrige(UIComponent component) {
-		this.component = component;
-	}
+     * @param component
+     */
+    public AjaxRegionBrige(UIComponent component) {
+        this.component = component;
+    }
 
-	/*
+    /*
      * (non-Javadoc)
-     * 
+     *
      * @see org.ajax4jsf.components.custom.ajax.AjaxContainer#getAjaxListener()
      */
     public MethodExpression getAjaxListener() {
@@ -105,181 +101,189 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see ogr.apache.myfaces.custom.ajax.AjaxContainer#setAjaxListener(javax.faces.el.MethodBinding)
      */
     public void setAjaxListener(MethodExpression ajaxListener) {
-        // 
-        if (log.isDebugEnabled())
-        {
-            log.debug(Messages.getMessage(Messages.SET_AJAX_LISTENER, ajaxListener.getExpressionString()));
+
+        //
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.SET_AJAX_LISTENER, ajaxListener.getExpressionString()));
         }
+
         this.ajaxListener = ajaxListener;
     }
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see ogr.apache.myfaces.custom.ajax.AjaxContainer#isImmediate()
      */
     public boolean isImmediate() {
         if (this.immediateSet) {
-            return (this.immediate);
+            return this.immediate;
         }
+
         ValueExpression vb = component.getValueExpression("immediate");
+
         if (vb != null) {
-            return (Boolean.TRUE.equals(vb.getValue(FacesContext.getCurrentInstance().getELContext())));
+            return Boolean.TRUE.equals(vb.getValue(FacesContext.getCurrentInstance().getELContext()));
         } else {
-            return (this.immediate);
+            return this.immediate;
         }
     }
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see ogr.apache.myfaces.custom.ajax.AjaxContainer#setImmediate(boolean)
      */
     public void setImmediate(boolean immediate) {
         if (immediate != this.immediate) {
             this.immediate = immediate;
         }
+
         this.immediateSet = true;
-
     }
 
-    /* (non-Javadoc)
-	 * @see org.ajax4jsf.framework.ajax.AjaxContainer#isSelfRendered()
-	 */
-	public boolean isSelfRendered() {
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.framework.ajax.AjaxContainer#isSelfRendered()
+     */
+    public boolean isSelfRendered() {
         if (this.selfRenderedSet) {
-            return (this.selfRendered);
+            return this.selfRendered;
         }
+
         ValueExpression vb = component.getValueExpression("selfRendered");
+
         if (vb != null) {
-            return (Boolean.TRUE.equals(vb.getValue(FacesContext.getCurrentInstance().getELContext())));
+            return Boolean.TRUE.equals(vb.getValue(FacesContext.getCurrentInstance().getELContext()));
         } else {
-            return (this.selfRendered);
+            return this.selfRendered;
         }
-	}
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.framework.ajax.AjaxContainer#setSelfRendered(boolean)
-	 */
-	public void setSelfRendered(boolean selfRendered) {
-		this.selfRendered = selfRendered;
-		this.selfRenderedSet = true;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.framework.ajax.AjaxContainer#setSelfRendered(boolean)
+     */
+    public void setSelfRendered(boolean selfRendered) {
+        this.selfRendered = selfRendered;
+        this.selfRenderedSet = true;
+    }
 
-	/**
+    /**
      * @return Returns the submitted.
      */
-    public boolean isSubmitted()
-    {
+    public boolean isSubmitted() {
         return this.submitted;
     }
 
     /**
-	     * @param submitted The submitted to set.
-	     */
-	    public void setSubmitted(boolean submitted)
-	    {
-	        // Important - decoder must set submitted AFTER setAjaxRequest !!!
-	        if (log.isDebugEnabled() && submitted  && (!isSubmitted())) {
-	            log.debug(Messages.getMessage(Messages.SUBMITTED_AJAX_REQUEST));
-	        }
-	        this.submitted = submitted;
-	    }
+     *     @param submitted The submitted to set.
+     */
+    public void setSubmitted(boolean submitted) {
 
-	/**
-	 * <p>
-	 * In addition to to the default {@link UIComponent#broadcast}processing,
-	 * pass the {@link AjaxEvent}being broadcast to the method referenced by
-	 * <code>AjaxListener</code> (if any), and to the default
-	 * {@link AjaxListener}registered on the {@link Application}.
-	 * </p>
-	 * 
-	 * @param event
-	 *            {@link FacesEvent}to be broadcast
-	 * 
-	 * @exception AbortProcessingException
-	 *                Signal the JavaServer Faces implementation that no further
-	 *                processing on the current event should be performed
-	 * @exception IllegalArgumentException
-	 *                if the implementation class of this {@link FacesEvent}is
-	 *                not supported by this component
-	 * @exception NullPointerException
-	 *                if <code>event</code> is <code>null</code>
-	 */
-	public void broadcast(FacesEvent event) throws AbortProcessingException {
+        // Important - decoder must set submitted AFTER setAjaxRequest !!!
+        if (LOG.isDebugEnabled() && submitted && !isSubmitted()) {
+            LOG.debug(Messages.getMessage(Messages.SUBMITTED_AJAX_REQUEST));
+        }
 
-		// Perform standard superclass processing
-		// component.broadcast(event);
+        this.submitted = submitted;
+    }
 
-		if (event instanceof AjaxEvent) {
-			if (log.isDebugEnabled()) {
-				log.debug(Messages
-						.getMessage(Messages.SEND_EVENT_TO_AJAX_LISTENER,
-								component.getId()));
-			}
+    /**
+     * <p>
+     * In addition to to the default {@link UIComponent#broadcast}processing,
+     * pass the {@link AjaxEvent}being broadcast to the method referenced by
+     * <code>AjaxListener</code> (if any), and to the default
+     * {@link org.ajax4jsf.event.AjaxListener}registered on the {@link javax.faces.application.Application}.
+     * </p>
+     *
+     * @param event
+     *            {@link FacesEvent}to be broadcast
+     *
+     * @exception AbortProcessingException
+     *                Signal the JavaServer Faces implementation that no further
+     *                processing on the current event should be performed
+     * @exception IllegalArgumentException
+     *                if the implementation class of this {@link FacesEvent}is
+     *                not supported by this component
+     * @exception NullPointerException
+     *                if <code>event</code> is <code>null</code>
+     */
+    public void broadcast(FacesEvent event) throws AbortProcessingException {
 
-			// Notify the specified action listener method (if any)
-			MethodExpression mb = getAjaxListener();
-			if (mb != null) {
-				FacesContext context = FacesContext.getCurrentInstance();
-				ELContext elContext = context.getELContext();
-				mb.invoke(elContext, new Object[] { event });
-			}
-		}
-	}
+        // Perform standard superclass processing
+        // component.broadcast(event);
+        if (event instanceof AjaxEvent) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.SEND_EVENT_TO_AJAX_LISTENER, component.getId()));
+            }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext,
-	 *      java.lang.Object)
-	 */
-	public void restoreState(FacesContext context, Object state) {
-	    if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.RESTORE_AJAX_COMPONENT_STATE, component.getId()));
-		}
-	    Object values[] = (Object[]) state;
-//	    super.restoreState(context, values[0]);
-	    this.immediate = ((Boolean) values[0]).booleanValue();
-	    this.immediateSet = ((Boolean) values[1]).booleanValue();
-	    this.ajaxListener = (MethodExpression) UIComponentBase.restoreAttachedState(context, values[2]);
-	    this.selfRendered = ((Boolean) values[3]).booleanValue();
-	    this.selfRenderedSet = ((Boolean) values[4]).booleanValue();
-	}
+            // Notify the specified action listener method (if any)
+            MethodExpression mb = getAjaxListener();
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext)
-	 */
-	public Object saveState(FacesContext context) {
-	    // 
-	    if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.SAVE_AJAX_COMPONENT_STATE, component.getId()));
-		}
-	    Object[] values = new Object[5];
-//	    values[0] = super.saveState(context);
-	    values[0] = Boolean.valueOf(immediate);
-	    values[1] = Boolean.valueOf(immediateSet);
-	    values[2] = UIComponentBase.saveAttachedState(context, ajaxListener);
-	    values[3] = Boolean.valueOf(selfRendered);
-	    values[4] = Boolean.valueOf(selfRenderedSet);
-	    return values;
-	}
+            if (mb != null) {
+                FacesContext context = FacesContext.getCurrentInstance();
+                ELContext elContext = context.getELContext();
 
+                mb.invoke(elContext, new Object[] {event});
+            }
+        }
+    }
 
-   public boolean isTransient() {
-		return transientFlag;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext,
+     *      java.lang.Object)
+     */
+    public void restoreState(FacesContext context, Object state) {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.RESTORE_AJAX_COMPONENT_STATE, component.getId()));
+        }
 
-	public void setTransient(boolean transientFlag) {
-		this.transientFlag = transientFlag;
-	}
+        Object[] values = (Object[]) state;
 
+//      super.restoreState(context, values[0]);
+        this.immediate = ((Boolean) values[0]).booleanValue();
+        this.immediateSet = ((Boolean) values[1]).booleanValue();
+        this.ajaxListener = (MethodExpression) UIComponentBase.restoreAttachedState(context, values[2]);
+        this.selfRendered = ((Boolean) values[3]).booleanValue();
+        this.selfRenderedSet = ((Boolean) values[4]).booleanValue();
+    }
 
-	}
-    
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext)
+     */
+    public Object saveState(FacesContext context) {
+
+        //
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.SAVE_AJAX_COMPONENT_STATE, component.getId()));
+        }
+
+        Object[] values = new Object[5];
+
+//      values[0] = super.saveState(context);
+        values[0] = Boolean.valueOf(immediate);
+        values[1] = Boolean.valueOf(immediateSet);
+        values[2] = UIComponentBase.saveAttachedState(context, ajaxListener);
+        values[3] = Boolean.valueOf(selfRendered);
+        values[4] = Boolean.valueOf(selfRenderedSet);
+
+        return values;
+    }
+
+    public boolean isTransient() {
+        return transientFlag;
+    }
+
+    public void setTransient(boolean transientFlag) {
+        this.transientFlag = transientFlag;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxViewRoot.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxViewRoot.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/AjaxViewRoot.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,9 +19,24 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.component;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.context.AjaxContext;
+import org.ajax4jsf.context.InvokerCallback;
+import org.ajax4jsf.context.ViewIdHolder;
+import org.ajax4jsf.event.AjaxListener;
+import org.ajax4jsf.event.EventsQueue;
+import org.ajax4jsf.renderkit.AjaxContainerRenderer;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
+
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
@@ -29,6 +44,7 @@
 import java.util.Set;
 
 import javax.el.MethodExpression;
+
 import javax.faces.FacesException;
 import javax.faces.FactoryFinder;
 import javax.faces.component.ContextCallback;
@@ -45,643 +61,662 @@
 import javax.faces.render.Renderer;
 import javax.faces.webapp.FacesServlet;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.context.AjaxContext;
-import org.ajax4jsf.context.InvokerCallback;
-import org.ajax4jsf.context.ViewIdHolder;
-import org.ajax4jsf.event.AjaxListener;
-import org.ajax4jsf.event.EventsQueue;
-import org.ajax4jsf.renderkit.AjaxContainerRenderer;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * Custom ViewRoot for support render parts of tree for Ajax requests. Main
  * difference from default ViewRoot - store events queue and unique id counter
  * in request-scope variables. In common realisation, store request-scope
  * variables in component produce errors in case of concurrent requests to same
  * view.
- * 
+ *
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.4 $ $Date: 2007/02/28 17:01:01 $
- * 
+ *
  */
 public class AjaxViewRoot extends UIViewRoot implements AjaxContainer {
+    public static final String ROOT_ID = "_viewRoot";
+    private static final Logger LOG = RichfacesLogger.COMPONENTS.getLogger();
 
-	public static final String ROOT_ID = "_viewRoot";
-	
-	private Lifecycle lifecycle;
+    /**
+     * Use own {@link PhaseListener}'s list, to use with AJAX processing.
+     * phases.
+     */
+    private List<PhaseListener> phaseListeners = null;
+    private EventsQueue ajaxEvents = new EventsQueue();
+    private InvokerCallback validatorsInvoker = new InvokerCallback() {
+        public void invokeContextCallback(FacesContext context, UIComponent component) {
+            component.processValidators(context);
+        }
+        public void invokeRoot(FacesContext context) {}
+    };
+    private InvokerCallback updatesInvoker = new InvokerCallback() {
+        public void invokeContextCallback(FacesContext context, UIComponent component) {
+            component.processUpdates(context);
+        }
+        public void invokeRoot(FacesContext context) {}
+    };
+    private InvokerCallback decodeInvoker = new InvokerCallback() {
+        public void invokeContextCallback(FacesContext context, UIComponent component) {
+            component.processDecodes(context);
+        }
+        public void invokeRoot(FacesContext context) {
+            decode(context);
+        }
+    };
 
-	private AjaxRegionBrige _brige;
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.UIViewRoot#encodeBegin(javax.faces.context.FacesContext)
+     */
 
-	private static final Logger _log = RichfacesLogger.COMPONENTS.getLogger();
+    // public void encodeBegin(FacesContext context) throws IOException {
+    // UIComponent submittedComponent = getSubmittedRegion(context);
+    // if(null == submittedComponent){
+    // super.encodeBegin(context);
+    // } else {
+    // submittedComponent.encodeBegin(context);
+    // }
+    // }
+    private ContextCallback ajaxInvoker = new ContextCallback() {
+        public void invokeContextCallback(FacesContext context, UIComponent component) {
+            try {
+                if (component instanceof AjaxContainer) {
+                    AjaxContainer ajax = (AjaxContainer) component;
 
-	/**
-	 * 
-	 */
-	public AjaxViewRoot() {
-		super();
-		super.setId(ROOT_ID);
-		_brige = new AjaxRegionBrige(this);
-	}
+                    ajax.encodeAjax(context);
+                } else {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.UIComponentBase#getId()
-	 */
-	// public String getId() {
-	// return ROOT_ID;
-	// }
-	public String getRendererType() {
-		return (COMPONENT_FAMILY);
-	}
+                    // Container not found, use Root for encode.
+                    encodeAjax(context);
+                }
+            } catch (IOException e) {
+                throw new FacesException(e);
+            }
+        }
+    };
+    private AjaxRegionBrige brige;
+    private EventsQueue[] events;
+    private Lifecycle lifecycle;
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#broadcast(javax.faces.event.FacesEvent)
-	 */
-	public void broadcast(FacesEvent event) throws AbortProcessingException {
-		super.broadcast(event);
-		getBrige().broadcast(event);
-	}
+    /**
+     *
+     */
+    public AjaxViewRoot() {
+        super();
+        super.setId(ROOT_ID);
+        brige = new AjaxRegionBrige(this);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#getAjaxListener()
-	 */
-	public MethodExpression getAjaxListener() {
-		return getBrige().getAjaxListener();
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.UIComponentBase#getId()
+     */
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#isImmediate()
-	 */
-	public boolean isImmediate() {
-		return getBrige().isImmediate();
-	}
+    // public String getId() {
+    // return ROOT_ID;
+    // }
+    public String getRendererType() {
+        return COMPONENT_FAMILY;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#isSubmitted()
-	 */
-	public boolean isSubmitted() {
-		return getBrige().isSubmitted();
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#broadcast(javax.faces.event.FacesEvent)
+     */
+    public void broadcast(FacesEvent event) throws AbortProcessingException {
+        super.broadcast(event);
+        getBrige().broadcast(event);
+    }
 
-	/**
-	 * Use own {@link PhaseListener}'s list, to use with AJAX processing.
-	 * phases.
-	 */
-	private List<PhaseListener> phaseListeners = null;
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#getAjaxListener()
+     */
+    public MethodExpression getAjaxListener() {
+        return getBrige().getAjaxListener();
+    }
 
-	public void removePhaseListener(PhaseListener toRemove) {
-		if (null != phaseListeners) {
-			phaseListeners.remove(toRemove);
-		}
-		super.removePhaseListener(toRemove);
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#isImmediate()
+     */
+    public boolean isImmediate() {
+        return getBrige().isImmediate();
+    }
 
-	public void addPhaseListener(PhaseListener newPhaseListener) {
-		if (null == phaseListeners) {
-			phaseListeners = new ArrayList<PhaseListener>();
-		}
-		phaseListeners.add(newPhaseListener);
-		super.addPhaseListener(newPhaseListener);
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#isSubmitted()
+     */
+    public boolean isSubmitted() {
+        return getBrige().isSubmitted();
+    }
 
-	/**
-	 * Send notification to a view-scope phase listeners.
-	 * 
-	 * @param context
-	 * @param phase
-	 * @param before
-	 */
-	protected void processPhaseListeners(FacesContext context, PhaseId phase,
-			boolean before) {
-		MethodExpression listenerExpression = before ? getBeforePhaseListener()
-				: getAfterPhaseListener();
-		PhaseEvent event = null;
-		if (null != listenerExpression) {
-			event = createPhaseEvent(context, phase);
-			listenerExpression.invoke(context.getELContext(),
-					new Object[] { event });
-		}
-		if (null != this.phaseListeners) {
-			for (PhaseListener listener : phaseListeners) {
-				PhaseId phaseId = listener.getPhaseId();
-				if (phaseId == phase || phaseId == PhaseId.ANY_PHASE) {
-					if (null == event) {
-						event = createPhaseEvent(context, phase);
-					}
-					if (before) {
-						listener.beforePhase(event);
-					} else {
-						listener.afterPhase(event);
-					}
-				}
-			}
-		}
-	}
+    public void removePhaseListener(PhaseListener toRemove) {
+        if (null != phaseListeners) {
+            phaseListeners.remove(toRemove);
+        }
 
-	protected PhaseEvent createPhaseEvent(FacesContext context, PhaseId phaseId)
-			throws FacesException {
-		if (lifecycle == null) {
-			LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
-					.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
-			String lifecycleId = context.getExternalContext().getInitParameter(
-					FacesServlet.LIFECYCLE_ID_ATTR);
-			if (lifecycleId == null) {
-				lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE;
-			}
-			lifecycle = lifecycleFactory.getLifecycle(lifecycleId);
-		}
-		return (new PhaseEvent(context, phaseId, lifecycle));
-	}
+        super.removePhaseListener(toRemove);
+    }
 
-	protected void processPhase(FacesContext context, PhaseId phase,
-			InvokerCallback callback) {
-		// Process phase listeners before phase.
-		processPhaseListeners(context, phase, true);
-		// Process phase. Run callback method by invokeOnComponent for a
-		// submitted region.
-		if (!(null == callback || context.getRenderResponse() || context
-				.getResponseComplete())) {
-			AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-			String submittedRegionClientId = ajaxContext
-					.getSubmittedRegionClientId();
-			if (ajaxContext.isAjaxRequest() && submittedRegionClientId != null && 
-							!submittedRegionClientId.equals(ROOT_ID) 
-							&& !submittedRegionClientId.equals(getClientId(context))) {
-				invokeOnComponent(context, submittedRegionClientId, new InvokerCallbackWrapper(callback));
-			} else {
-				// For a root region, call invokeRoot method, then process all
-				// facets and children by invoke method.
-				try {
-					callback.invokeRoot(context);
-				} catch (RuntimeException e) {
-					context.renderResponse();
-					throw e;
-				}
-				String ajaxSingleClientId = ajaxContext.getAjaxSingleClientId();
-				if (null == ajaxSingleClientId) {
-					for (Iterator<UIComponent> iter = getFacetsAndChildren(); iter
-							.hasNext();) {
-						callback.invokeContextCallback(context, iter.next());
-					}
-				} else {
-				    	InvokerCallback invokerCallback = new InvokerCallbackWrapper(callback);
-					invokeOnComponent(context, ajaxSingleClientId, invokerCallback);
-					Set<String> areasToProcess = ajaxContext.getAjaxAreasToProcess();
-					if(null != areasToProcess){
-						for (String areaId : areasToProcess) {
-							invokeOnComponent(context, areaId, invokerCallback);
-						}
-					}
-				}
-			}
-		}
-		// Broadcast phase events.
-		broadcastEvents(context, phase);
-		// Process afterPhase listeners.
-		processPhaseListeners(context, phase, false);
-	}
+    public void addPhaseListener(PhaseListener newPhaseListener) {
+        if (null == phaseListeners) {
+            phaseListeners = new ArrayList<PhaseListener>();
+        }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.UIComponent#queueEvent(javax.faces.event.FacesEvent)
-	 */
-	public void queueEvent(FacesEvent event) {
-		if (event == null)
-			throw new NullPointerException(Messages
-					.getMessage(Messages.NULL_EVENT_SUBMITTED_ERROR));
-		if (event.getPhaseId().compareTo(PhaseId.RENDER_RESPONSE) == 0) {
-			// HACK - Special case - Ajax Events to RenderResponse phase
-			// queue.
-			getAjaxEventsQueue().offer(event);
-		} else {
-			getEventsQueue(event.getPhaseId()).offer(event);
-		}
-	}
+        phaseListeners.add(newPhaseListener);
+        super.addPhaseListener(newPhaseListener);
+    }
 
-	/**
-	 * Broadcast events for specified Phase
-	 * 
-	 * @param context
-	 * @param phaseId -
-	 *            phase, for which events must be processed.
-	 */
-	public void broadcastEvents(FacesContext context, PhaseId phaseId) {
-		EventsQueue[] events = getEvents();
-		EventsQueue anyPhaseEvents = events[PhaseId.ANY_PHASE.getOrdinal()];
-		EventsQueue phaseEvents = events[phaseId.getOrdinal()];
-		if (phaseEvents.isEmpty() && anyPhaseEvents.isEmpty())
-			return;
-		// FacesEvent event = null;
-		boolean haveAnyPhaseEvents = !anyPhaseEvents.isEmpty();
-		boolean havePhaseEvents = !phaseEvents.isEmpty();
-		do {
-			// ANY_PHASE first
-			processEvents(context, anyPhaseEvents, haveAnyPhaseEvents);
+    /**
+     * Send notification to a view-scope phase listeners.
+     *
+     * @param context
+     * @param phase
+     * @param before
+     */
+    protected void processPhaseListeners(FacesContext context, PhaseId phase, boolean before) {
+        MethodExpression listenerExpression = before ? getBeforePhaseListener() : getAfterPhaseListener();
+        PhaseEvent event = null;
 
-			processEvents(context, phaseEvents, havePhaseEvents);
-			// Events can queued in other events processing
-			haveAnyPhaseEvents = !anyPhaseEvents.isEmpty();
-			havePhaseEvents = !phaseEvents.isEmpty();
-		} while (haveAnyPhaseEvents || havePhaseEvents);
-		if (context.getRenderResponse() || context.getResponseComplete()) {
-			clearEvents();
-		}
+        if (null != listenerExpression) {
+            event = createPhaseEvent(context, phase);
+            listenerExpression.invoke(context.getELContext(), new Object[] {event});
+        }
 
-	}
+        if (null != this.phaseListeners) {
+            for (PhaseListener listener : phaseListeners) {
+                PhaseId phaseId = listener.getPhaseId();
 
-	/**
-	 * @param context
-	 *            TODO
-	 * @param phaseEventsQueue
-	 * @param havePhaseEvents
-	 */
-	public void processEvents(FacesContext context,
-			EventsQueue phaseEventsQueue, boolean havePhaseEvents) {
-		FacesEvent event;
-		while (havePhaseEvents) {
-			try {
-				event = (FacesEvent) phaseEventsQueue.remove();
-				UIComponent source = event.getComponent();
-				try {
-					source.broadcast(event);
-				} catch (AbortProcessingException e) {
-					if (_log.isErrorEnabled()) {
-						UIComponent component = event.getComponent();
-						String id = null != component ? component
-								.getClientId(context) : "";
-						_log.error(
-								"Error processing faces event for the component "
-										+ id, e);
-					}
-				}
-			} catch (NoSuchElementException e) {
-				havePhaseEvents = false;
-			}
-		}
-	}
+                if ((phaseId == phase) || (phaseId == PhaseId.ANY_PHASE)) {
+                    if (null == event) {
+                        event = createPhaseEvent(context, phase);
+                    }
 
-	public void broadcastAjaxEvents(FacesContext context) {
-		EventsQueue queue = getAjaxEventsQueue();
-		processEvents(context, queue, !queue.isEmpty());
-	}
+                    if (before) {
+                        listener.beforePhase(event);
+                    } else {
+                        listener.afterPhase(event);
+                    }
+                }
+            }
+        }
+    }
 
-	private EventsQueue[] events;
+    protected PhaseEvent createPhaseEvent(FacesContext context, PhaseId phaseId) throws FacesException {
+        if (lifecycle == null) {
+            LifecycleFactory lifecycleFactory =
+                (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
+            String lifecycleId = context.getExternalContext().getInitParameter(FacesServlet.LIFECYCLE_ID_ATTR);
 
-	private EventsQueue ajaxEvents = new EventsQueue();
+            if (lifecycleId == null) {
+                lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE;
+            }
 
-	/**
-	 * Use FIFO buffers for hold Faces Events. Hold this buffers in Request
-	 * scope parameters for support any concurrent requests for same component
-	 * tree ( since RI hold component tree in session ).
-	 * 
-	 * @param phase
-	 * 
-	 * @return
-	 */
-	protected EventsQueue getEventsQueue(PhaseId phase) {
-		return getEvents()[phase.getOrdinal()];
-	}
+            lifecycle = lifecycleFactory.getLifecycle(lifecycleId);
+        }
 
-	/**
-	 * @return
-	 */
-	protected EventsQueue[] getEvents() {
-		if (events == null) {
-			clearEvents();
-		}
-		return events;
-	}
+        return new PhaseEvent(context, phaseId, lifecycle);
+    }
 
-	/**
-	 * Special Fifo Buffer for ajax events to Render Responce phase.
-	 * 
-	 * @return
-	 */
-	protected EventsQueue getAjaxEventsQueue() {
+    protected void processPhase(FacesContext context, PhaseId phase, InvokerCallback callback) {
 
-		return ajaxEvents;
-	}
+        // Process phase listeners before phase.
+        processPhaseListeners(context, phase, true);
 
-	public void clearEvents() {
-		int len;
-		events = new EventsQueue[len = PhaseId.VALUES.size()];
-		for (int i = 0; i < len; i++) {
-			events[i] = new EventsQueue();
-		}
-	}
+        // Process phase. Run callback method by invokeOnComponent for a
+        // submitted region.
+        if (!((null == callback) || context.getRenderResponse() || context.getResponseComplete())) {
+            AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
+            String submittedRegionClientId = ajaxContext.getSubmittedRegionClientId();
 
-	private InvokerCallback _decodeInvoker = new InvokerCallback() {
+            if (ajaxContext.isAjaxRequest() && (submittedRegionClientId != null)
+                    && !submittedRegionClientId.equals(ROOT_ID)
+                    && !submittedRegionClientId.equals(getClientId(context))) {
+                invokeOnComponent(context, submittedRegionClientId, new InvokerCallbackWrapper(callback));
+            } else {
 
-		public void invokeContextCallback(FacesContext context,
-				UIComponent component) {
-			component.processDecodes(context);
-		}
+                // For a root region, call invokeRoot method, then process all
+                // facets and children by invoke method.
+                try {
+                    callback.invokeRoot(context);
+                } catch (RuntimeException e) {
+                    context.renderResponse();
 
-		public void invokeRoot(FacesContext context) {
-			decode(context);
-		}
+                    throw e;
+                }
 
-	};
+                String ajaxSingleClientId = ajaxContext.getAjaxSingleClientId();
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#processDecodes(javax.faces.context.FacesContext)
-	 */
-	public void processDecodes(FacesContext context) {
-		if (context == null)
-			throw new NullPointerException("context");
-		processPhase(context, PhaseId.APPLY_REQUEST_VALUES, _decodeInvoker);
-	}
+                if (null == ajaxSingleClientId) {
+                    for (Iterator<UIComponent> iter = getFacetsAndChildren(); iter.hasNext(); ) {
+                        callback.invokeContextCallback(context, iter.next());
+                    }
+                } else {
+                    InvokerCallback invokerCallback = new InvokerCallbackWrapper(callback);
 
-	private InvokerCallback _updatesInvoker = new InvokerCallback() {
+                    invokeOnComponent(context, ajaxSingleClientId, invokerCallback);
 
-		public void invokeContextCallback(FacesContext context,
-				UIComponent component) {
-			component.processUpdates(context);
-		}
+                    Set<String> areasToProcess = ajaxContext.getAjaxAreasToProcess();
 
-		public void invokeRoot(FacesContext context) {
-		}
+                    if (null != areasToProcess) {
+                        for (String areaId : areasToProcess) {
+                            invokeOnComponent(context, areaId, invokerCallback);
+                        }
+                    }
+                }
+            }
+        }
 
-	};
+        // Broadcast phase events.
+        broadcastEvents(context, phase);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#processUpdates(javax.faces.context.FacesContext)
-	 */
-	public void processUpdates(FacesContext context) {
-		if (context == null)
-			throw new NullPointerException("context");
-		processPhase(context, PhaseId.UPDATE_MODEL_VALUES, _updatesInvoker);
-	}
+        // Process afterPhase listeners.
+        processPhaseListeners(context, phase, false);
+    }
 
-	private InvokerCallback _validatorsInvoker = new InvokerCallback() {
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.UIComponent#queueEvent(javax.faces.event.FacesEvent)
+     */
+    public void queueEvent(FacesEvent event) {
+        if (event == null) {
+            throw new NullPointerException(Messages.getMessage(Messages.NULL_EVENT_SUBMITTED_ERROR));
+        }
 
-		public void invokeContextCallback(FacesContext context,
-				UIComponent component) {
-			component.processValidators(context);
-		}
+        if (event.getPhaseId().compareTo(PhaseId.RENDER_RESPONSE) == 0) {
 
-		public void invokeRoot(FacesContext context) {
-		}
+            // HACK - Special case - Ajax Events to RenderResponse phase
+            // queue.
+            getAjaxEventsQueue().offer(event);
+        } else {
+            getEventsQueue(event.getPhaseId()).offer(event);
+        }
+    }
 
-	};
+    /**
+     * Broadcast events for specified Phase
+     *
+     * @param context
+     * @param phaseId -
+     *            phase, for which events must be processed.
+     */
+    public void broadcastEvents(FacesContext context, PhaseId phaseId) {
+        EventsQueue[] eWebXmlvents = getEvents();
+        EventsQueue anyPhaseEvents = events[PhaseId.ANY_PHASE.getOrdinal()];
+        EventsQueue phaseEvents = events[phaseId.getOrdinal()];
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#processValidators(javax.faces.context.FacesContext)
-	 */
-	public void processValidators(FacesContext context) {
-		if (context == null)
-			throw new NullPointerException("context");
-		processPhase(context, PhaseId.PROCESS_VALIDATIONS, _validatorsInvoker);
-	}
+        if (phaseEvents.isEmpty() && anyPhaseEvents.isEmpty()) {
+            return;
+        }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.UIViewRoot#processApplication(javax.faces.context.FacesContext)
-	 */
-	public void processApplication(FacesContext context) {
-		if (context == null)
-			throw new NullPointerException("context");
-		processPhase(context, PhaseId.INVOKE_APPLICATION, null);
-	}
+        // FacesEvent event = null;
+        boolean haveAnyPhaseEvents = !anyPhaseEvents.isEmpty();
+        boolean havePhaseEvents = !phaseEvents.isEmpty();
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.UIViewRoot#encodeBegin(javax.faces.context.FacesContext)
-	 */
-	// public void encodeBegin(FacesContext context) throws IOException {
-	// UIComponent submittedComponent = getSubmittedRegion(context);
-	// if(null == submittedComponent){
-	// super.encodeBegin(context);
-	// } else {
-	// submittedComponent.encodeBegin(context);
-	// }
-	// }
-	private ContextCallback _ajaxInvoker = new ContextCallback() {
+        do {
 
-		public void invokeContextCallback(FacesContext context,
-				UIComponent component) {
-			try {
-				if (component instanceof AjaxContainer) {
-					AjaxContainer ajax = (AjaxContainer) component;
-					ajax.encodeAjax(context);
-				} else {
-					// Container not found, use Root for encode.
-					encodeAjax(context);
-				}
-			} catch (IOException e) {
-				throw new FacesException(e);
-			}
-		}
-	};
+            // ANY_PHASE first
+            processEvents(context, anyPhaseEvents, haveAnyPhaseEvents);
+            processEvents(context, phaseEvents, havePhaseEvents);
 
-	@Override
-	public void encodeBegin(FacesContext context) throws IOException {
-		processPhaseListeners(context, PhaseId.RENDER_RESPONSE, true);
-		// Copy/paste from UIComponentBase, so in no way for java to call super.super method.
+            // Events can queued in other events processing
+            haveAnyPhaseEvents = !anyPhaseEvents.isEmpty();
+            havePhaseEvents = !phaseEvents.isEmpty();
+        } while (haveAnyPhaseEvents || havePhaseEvents);
+
+        if (context.getRenderResponse() || context.getResponseComplete()) {
+            clearEvents();
+        }
+    }
+
+    /**
+     * @param context
+     *            TODO
+     * @param phaseEventsQueue
+     * @param havePhaseEvents
+     */
+    public void processEvents(FacesContext context, EventsQueue phaseEventsQueue, boolean havePhaseEvents) {
+        FacesEvent event;
+
+        while (havePhaseEvents) {
+            try {
+                event = (FacesEvent) phaseEventsQueue.remove();
+
+                UIComponent source = event.getComponent();
+
+                try {
+                    source.broadcast(event);
+                } catch (AbortProcessingException e) {
+                    if (LOG.isErrorEnabled()) {
+                        UIComponent component = event.getComponent();
+                        String id = (null != component) ? component.getClientId(context) : "";
+
+                        LOG.error("Error processing faces event for the component " + id, e);
+                    }
+                }
+            } catch (NoSuchElementException e) {
+                havePhaseEvents = false;
+            }
+        }
+    }
+
+    public void broadcastAjaxEvents(FacesContext context) {
+        EventsQueue queue = getAjaxEventsQueue();
+
+        processEvents(context, queue, !queue.isEmpty());
+    }
+
+    /**
+     * Use FIFO buffers for hold Faces Events. Hold this buffers in Request
+     * scope parameters for support any concurrent requests for same component
+     * tree ( since RI hold component tree in session ).
+     *
+     * @param phase
+     *
+     * @return
+     */
+    protected EventsQueue getEventsQueue(PhaseId phase) {
+        return getEvents()[phase.getOrdinal()];
+    }
+
+    /**
+     * @return
+     */
+    protected EventsQueue[] getEvents() {
+        if (events == null) {
+            clearEvents();
+        }
+
+        return events;
+    }
+
+    /**
+     * Special Fifo Buffer for ajax events to Render Responce phase.
+     *
+     * @return
+     */
+    protected EventsQueue getAjaxEventsQueue() {
+        return ajaxEvents;
+    }
+
+    public void clearEvents() {
+        int len = PhaseId.VALUES.size();
+
+        events = new EventsQueue[len];
+
+        for (int i = 0; i < len; i++) {
+            events[i] = new EventsQueue();
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#processDecodes(javax.faces.context.FacesContext)
+     */
+    public void processDecodes(FacesContext context) {
+        if (context == null) {
+            throw new NullPointerException("context");
+        }
+
+        processPhase(context, PhaseId.APPLY_REQUEST_VALUES, decodeInvoker);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#processUpdates(javax.faces.context.FacesContext)
+     */
+    public void processUpdates(FacesContext context) {
+        if (context == null) {
+            throw new NullPointerException("context");
+        }
+
+        processPhase(context, PhaseId.UPDATE_MODEL_VALUES, updatesInvoker);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#processValidators(javax.faces.context.FacesContext)
+     */
+    public void processValidators(FacesContext context) {
+        if (context == null) {
+            throw new NullPointerException("context");
+        }
+
+        processPhase(context, PhaseId.PROCESS_VALIDATIONS, validatorsInvoker);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.UIViewRoot#processApplication(javax.faces.context.FacesContext)
+     */
+    public void processApplication(FacesContext context) {
+        if (context == null) {
+            throw new NullPointerException("context");
+        }
+
+        processPhase(context, PhaseId.INVOKE_APPLICATION, null);
+    }
+
+    @Override
+    public void encodeBegin(FacesContext context) throws IOException {
+        processPhaseListeners(context, PhaseId.RENDER_RESPONSE, true);
+
+        // Copy/paste from UIComponentBase, so in no way for java to call super.super method.
         String rendererType = getRendererType();
+
         if (rendererType != null) {
             Renderer renderer = this.getRenderer(context);
+
             if (renderer != null) {
                 renderer.encodeBegin(context, this);
             } else {
+
                 // TODO: log
             }
         }
+    }
 
-	}
+    @Override
+    public void encodeEnd(FacesContext context) throws IOException {
 
-	@Override
-	public void encodeEnd(FacesContext context) throws IOException {
-		// Copy/paste from UIComponentBase, so in no way for java to call super.super method.
+        // Copy/paste from UIComponentBase, so in no way for java to call super.super method.
         String rendererType = getRendererType();
+
         if (rendererType != null) {
             Renderer renderer = this.getRenderer(context);
+
             if (renderer != null) {
                 renderer.encodeEnd(context, this);
             } else {
+
                 // TODO: log
             }
         }
-		processPhaseListeners(context, PhaseId.RENDER_RESPONSE, false);
-//		super.encodeEnd(context);
-	}
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.UIComponentBase#encodeChildren(javax.faces.context.FacesContext)
-	 */
-	public void encodeChildren(FacesContext context) throws IOException {
-		AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-		if (ajaxContext.isAjaxRequest()) {
-			String submittedRegionClientId = ajaxContext
-					.getSubmittedRegionClientId();
-			boolean invoked = false; 
-			if (submittedRegionClientId != null && !submittedRegionClientId.equals(ROOT_ID) && !submittedRegionClientId.equals(getClientId(context))) {
-				invoked = invokeOnComponent(context, submittedRegionClientId, _ajaxInvoker);
-			} 
-			// if container not found, use Root for encode.
-			// https://jira.jboss.org/jira/browse/RF-3975			
-			if (!invoked) {
-			    encodeAjax(context);
-			}
-		} else {
-			super.encodeChildren(context);
-		}
-	}
 
-	@SuppressWarnings("unchecked")
-	public void restoreState(FacesContext context, Object state) {
-		Object[] mystate = (Object[]) state;
-		super.restoreState(context, mystate[0]);
-		getBrige().restoreState(context, mystate[1]);
-		Object listeners = restoreAttachedState(context, mystate[2]);
-		if (null != listeners) {
-			phaseListeners = (List<PhaseListener>) listeners;
-		}
-	}
+        processPhaseListeners(context, PhaseId.RENDER_RESPONSE, false);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#saveState(javax.faces.context.FacesContext)
-	 */
-	public Object saveState(FacesContext context) {
-		Object[] state = new Object[3];
-		state[0] = super.saveState(context);
-		state[1] = getBrige().saveState(context);
-		state[2] = saveAttachedState(context, phaseListeners);
-		return state;
-	}
+//      super.encodeEnd(context);
+    }
 
-	public String getViewId() {
-		ViewIdHolder viewIdHolder = AjaxContext.getCurrentInstance()
-				.getViewIdHolder();
-		String viewId;
-		if (null != viewIdHolder) {
-			viewId = viewIdHolder.getViewId();
-		} else {
-			viewId = super.getViewId();
-		}
-		return viewId;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.UIComponentBase#encodeChildren(javax.faces.context.FacesContext)
+     */
+    public void encodeChildren(FacesContext context) throws IOException {
+        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#setAjaxListener(javax.faces.el.MethodBinding)
-	 */
-	public void setAjaxListener(MethodExpression ajaxListener) {
-		getBrige().setAjaxListener(ajaxListener);
-	}
+        if (ajaxContext.isAjaxRequest()) {
+            String submittedRegionClientId = ajaxContext.getSubmittedRegionClientId();
+            boolean invoked = false;
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#setImmediate(boolean)
-	 */
-	public void setImmediate(boolean immediate) {
-		getBrige().setImmediate(immediate);
-	}
+            if ((submittedRegionClientId != null) && !submittedRegionClientId.equals(ROOT_ID)
+                    && !submittedRegionClientId.equals(getClientId(context))) {
+                invoked = invokeOnComponent(context, submittedRegionClientId, ajaxInvoker);
+            }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#setSubmitted(boolean)
-	 */
-	public void setSubmitted(boolean submitted) {
-		getBrige().setSubmitted(submitted);
-	}
+            // if container not found, use Root for encode.
+            // https://jira.jboss.org/jira/browse/RF-3975
+            if (!invoked) {
+                encodeAjax(context);
+            }
+        } else {
+            super.encodeChildren(context);
+        }
+    }
 
-	public void addAjaxListener(AjaxListener listener) {
-		addFacesListener(listener);
-	}
+    @SuppressWarnings("unchecked")
+    public void restoreState(FacesContext context, Object state) {
+        Object[] mystate = (Object[]) state;
 
-	public AjaxListener[] getAjaxListeners() {
-		return (AjaxListener[]) getFacesListeners(AjaxListener.class);
-	}
+        super.restoreState(context, mystate[0]);
+        getBrige().restoreState(context, mystate[1]);
 
-	public void removeAjaxListener(AjaxListener listener) {
-		removeFacesListener(listener);
+        Object listeners = restoreAttachedState(context, mystate[2]);
 
-	}
+        if (null != listeners) {
+            phaseListeners = (List<PhaseListener>) listeners;
+        }
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#isSelfRendered()
-	 */
-	public boolean isSelfRendered() {
-		return false;// _brige.isSelfRendered();
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#saveState(javax.faces.context.FacesContext)
+     */
+    public Object saveState(FacesContext context) {
+        Object[] state = new Object[3];
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#setSelfRendered(boolean)
-	 */
-	public void setSelfRendered(boolean selfRendered) {
-		// _brige.setSelfRendered(selfRendered);
-	}
+        state[0] = super.saveState(context);
+        state[1] = getBrige().saveState(context);
+        state[2] = saveAttachedState(context, phaseListeners);
 
+        return state;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.UIComponentBase#getRendersChildren()
-	 */
-	public boolean getRendersChildren() {
-		FacesContext context = FacesContext.getCurrentInstance();
-		// For non Ajax request, view root not render children
-		if (!AjaxContext.getCurrentInstance(context).isAjaxRequest()) {
-			return false;
-		}
-		// Ajax Request. Control all output.
-		return true;
-	}
+    public String getViewId() {
+        ViewIdHolder viewIdHolder = AjaxContext.getCurrentInstance().getViewIdHolder();
+        String viewId;
 
-	public boolean isRenderRegionOnly() {
-		// for viewroot it not applicable.
-		return false;
-	}
+        if (null != viewIdHolder) {
+            viewId = viewIdHolder.getViewId();
+        } else {
+            viewId = super.getViewId();
+        }
 
-	public void setRenderRegionOnly(boolean reRenderPage) {
-		// Ignore for a ViewRoot.
-	}
+        return viewId;
+    }
 
-	public void encodeAjax(FacesContext context) throws IOException {
-		String rendererType = getRendererType();
-		if (rendererType != null) {
-			((AjaxContainerRenderer) getRenderer(context)).encodeAjax(context,
-					this);
-		}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#setAjaxListener(javax.faces.el.MethodBinding)
+     */
+    public void setAjaxListener(MethodExpression ajaxListener) {
+        getBrige().setAjaxListener(ajaxListener);
+    }
 
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#setImmediate(boolean)
+     */
+    public void setImmediate(boolean immediate) {
+        getBrige().setImmediate(immediate);
+    }
 
-	/**
-	 * @return the brige
-	 */
-	protected AjaxRegionBrige getBrige() {
-		return _brige;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#setSubmitted(boolean)
+     */
+    public void setSubmitted(boolean submitted) {
+        getBrige().setSubmitted(submitted);
+    }
 
+    public void addAjaxListener(AjaxListener listener) {
+        addFacesListener(listener);
+    }
+
+    public AjaxListener[] getAjaxListeners() {
+        return (AjaxListener[]) getFacesListeners(AjaxListener.class);
+    }
+
+    public void removeAjaxListener(AjaxListener listener) {
+        removeFacesListener(listener);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#isSelfRendered()
+     */
+    public boolean isSelfRendered() {
+        return false; // _brige.isSelfRendered();
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.ajax.AjaxViewBrige#setSelfRendered(boolean)
+     */
+    public void setSelfRendered(boolean selfRendered) {
+
+        // _brige.setSelfRendered(selfRendered);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.UIComponentBase#getRendersChildren()
+     */
+    public boolean getRendersChildren() {
+        FacesContext context = FacesContext.getCurrentInstance();
+
+        // For non Ajax request, view root not render children
+        if (!AjaxContext.getCurrentInstance(context).isAjaxRequest()) {
+            return false;
+        }
+
+        // Ajax Request. Control all output.
+        return true;
+    }
+
+    public boolean isRenderRegionOnly() {
+
+        // for viewroot it not applicable.
+        return false;
+    }
+
+    public void setRenderRegionOnly(boolean reRenderPage) {
+
+        // Ignore for a ViewRoot.
+    }
+
+    public void encodeAjax(FacesContext context) throws IOException {
+        String rendererType = getRendererType();
+
+        if (rendererType != null) {
+            ((AjaxContainerRenderer) getRenderer(context)).encodeAjax(context, this);
+        }
+    }
+
+    /**
+     * @return the brige
+     */
+    protected AjaxRegionBrige getBrige() {
+        return brige;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/ContextCallbackWrapper.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/ContextCallbackWrapper.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/ContextCallbackWrapper.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,42 +18,43 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.component;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import javax.faces.component.ContextCallback;
 import javax.faces.component.UIComponent;
 import javax.faces.context.FacesContext;
 
 /**
  * @author Anton Belevich
- * 
+ *
  */
 public class ContextCallbackWrapper implements ContextCallback {
+    ContextCallback callback;
 
-	ContextCallback callback;
+    public ContextCallbackWrapper(ContextCallback callback) {
+        this.callback = callback;
+    }
 
-	public ContextCallbackWrapper(ContextCallback callback) {
-		this.callback = callback;
-	}
+    public void invokeContextCallback(FacesContext context, UIComponent target) {
+        if (isParentRendered(target)) {
+            callback.invokeContextCallback(context, target);
+        }
+    }
 
-	public void invokeContextCallback(FacesContext context, UIComponent target) {
-		if (isParentRendered(target)) {
-			callback.invokeContextCallback(context, target);
-		}
-	}
+    public boolean isParentRendered(UIComponent target) {
+        UIComponent component = target;
 
-	public boolean isParentRendered(UIComponent target) {
-		UIComponent component = target;
+        while (component != null) {
+            if (!component.isRendered()) {
+                return false;
+            }
 
-		while (component != null) {
-			if (!component.isRendered()) {
-				return false;
-			}
-			component = component.getParent();
-		}
-		return true;
-	}
+            component = component.getParent();
+        }
+
+        return true;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/EventValueBinding.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/EventValueBinding.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/EventValueBinding.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.component;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
+
 import javax.faces.component.StateHolder;
 import javax.faces.component.UIComponent;
 import javax.faces.context.FacesContext;
@@ -28,179 +33,167 @@
 import javax.faces.el.PropertyNotFoundException;
 import javax.faces.el.ValueBinding;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.renderkit.AjaxRendererUtils;
-
 /**
  * Inner class for build event string for parent component.
- * 
+ *
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:38 $ Disadvantages -
  *          not rebuild event string setted as EL expression. TODO - save
  *          expressions for build event string at render phase.
  */
 public class EventValueBinding extends ValueBinding implements StateHolder {
-
-    /**
-         * 
-         */
     private static final long serialVersionUID = -6583167387542332290L;
 
-    private String _componentId;
-
     /**
-         * current update component. transient since saved state as component.
-         */
-    transient private AjaxSupport _component = null;
+     *     current update component. transient since saved state as component.
+     */
+    private transient AjaxSupport component = null;
+    private String componentId;
 
     /**
-         * Default constructor for restoreState.
-         */
-    public EventValueBinding() {
+     *     Default constructor for restoreState.
+     */
+    public EventValueBinding() {}
 
-    }
-
     /**
-         * Constructor for build from AjaxComponent.
-         * 
-         * @param update
-         */
+     *     Constructor for build from AjaxComponent.
+     *
+     *     @param update
+     */
     public EventValueBinding(AjaxSupport update) {
-	_component = update;
-	// _componentId = string;
+        component = update;
+
+        // _componentId = string;
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.el.ValueBinding#getType(javax.faces.context.FacesContext)
-         */
-    public Class getType(FacesContext facesContext) throws EvaluationException,
-	    PropertyNotFoundException {
-
-	return String.class;
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.el.ValueBinding#getType(javax.faces.context.FacesContext)
+     */
+    @Override
+    public Class getType(FacesContext facesContext) throws EvaluationException, PropertyNotFoundException {
+        return String.class;
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.el.ValueBinding#getValue(javax.faces.context.FacesContext)
-         */
-    public Object getValue(FacesContext facesContext)
-	    throws EvaluationException, PropertyNotFoundException {
-	if (((UIComponent) getComponent(facesContext)).isRendered()) {
-	    return getComponent(facesContext).getEventString();
-
-	} else {
-	    return null;
-	}
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.el.ValueBinding#getValue(javax.faces.context.FacesContext)
+     */
+    @Override
+    public Object getValue(FacesContext facesContext) throws EvaluationException, PropertyNotFoundException {
+        if (((UIComponent) getComponent(facesContext)).isRendered()) {
+            return getComponent(facesContext).getEventString();
+        } else {
+            return null;
+        }
     }
 
-    private AjaxSupport getComponent(FacesContext facesContext)
-	    throws EvaluationException {
+    private AjaxSupport getComponent(FacesContext facesContext) throws EvaluationException {
+        if (component == null) {
+            UIComponent uiComponent = facesContext.getViewRoot().findComponent(componentId);
 
-	if (_component == null) {
-	    UIComponent uiComponent = facesContext.getViewRoot().findComponent(
-		    _componentId);
-	    if (null != uiComponent && uiComponent instanceof AjaxSupport) {
-		_component = (AjaxSupport) uiComponent;
-	    } else {
-		throw new EvaluationException(Messages.getMessage(
-			Messages.COMPONENT_NOT_FOUND, _componentId));
-	    }
+            if ((null != uiComponent) && (uiComponent instanceof AjaxSupport)) {
+                component = (AjaxSupport) uiComponent;
+            } else {
+                throw new EvaluationException(Messages.getMessage(Messages.COMPONENT_NOT_FOUND, componentId));
+            }
+        }
 
-	}
-
-	return _component;
+        return component;
     }
 
     /**
-         * @param component
-         *                the component to set
-         */
+     *     @param component
+     *                    the component to set
+     */
     public void setComponent(AjaxSupport component) {
-	_component = component;
+        this.component = component;
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.el.ValueBinding#isReadOnly(javax.faces.context.FacesContext)
-         */
-    public boolean isReadOnly(FacesContext facesContext)
-	    throws EvaluationException, PropertyNotFoundException {
-	// TODO Auto-generated method stub
-	return true;
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.el.ValueBinding#isReadOnly(javax.faces.context.FacesContext)
+     */
+    @Override
+    public boolean isReadOnly(FacesContext facesContext) throws EvaluationException, PropertyNotFoundException {
+
+        // TODO Auto-generated method stub
+        return true;
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.el.ValueBinding#setValue(javax.faces.context.FacesContext,
-         *      java.lang.Object)
-         */
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.el.ValueBinding#setValue(javax.faces.context.FacesContext,
+     *          java.lang.Object)
+     */
+    @Override
     public void setValue(FacesContext facesContext, Object value)
-	    throws EvaluationException, PropertyNotFoundException {
-	throw new EvaluationException(Messages
-		.getMessage(Messages.EVENT_IS_READ_ONLY));
-
+        throws EvaluationException, PropertyNotFoundException {
+        
+        throw new EvaluationException(Messages.getMessage(Messages.EVENT_IS_READ_ONLY));
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext)
-         */
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext)
+     */
     public Object saveState(FacesContext context) {
-	if (null == _component) {
-	    return _componentId;
-	} else {
-	    return AjaxRendererUtils
-		    .getAbsoluteId((UIComponent) getComponent(context));
-	}
+        if (null == component) {
+            return componentId;
+        } else {
+            return AjaxRendererUtils.getAbsoluteId((UIComponent) getComponent(context));
+        }
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext,
-         *      java.lang.Object)
-         */
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext,
+     *          java.lang.Object)
+     */
     public void restoreState(FacesContext context, Object state) {
-	// TODO Auto-generated method stub
-	_componentId = (String) state;
+
+        // TODO Auto-generated method stub
+        componentId = (String) state;
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.component.StateHolder#isTransient()
-         */
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.component.StateHolder#isTransient()
+     */
     public boolean isTransient() {
-	// TODO Auto-generated method stub
-	return false;
+
+        // TODO Auto-generated method stub
+        return false;
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.component.StateHolder#setTransient(boolean)
-         */
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.component.StateHolder#setTransient(boolean)
+     */
     public void setTransient(boolean newTransientValue) {
-	// TODO Auto-generated method stub
 
+        // TODO Auto-generated method stub
     }
 
     /*
-         * (non-Javadoc)
-         * 
-         * @see javax.faces.el.ValueBinding#getExpressionString()
-         */
+     *     (non-Javadoc)
+     *
+     *     @see javax.faces.el.ValueBinding#getExpressionString()
+     */
+    @Override
     public String getExpressionString() {
-	// FacesContext context = FacesContext.getCurrentInstance();
-	// UIComponent component = (UIComponent) getComponent(context);
-	// return "#{ajaxSupport["+component.getClientId(context)+"]}";
-	return null;
-    }
 
-}
\ No newline at end of file
+        // FacesContext context = FacesContext.getCurrentInstance();
+        // UIComponent component = (UIComponent) getComponent(context);
+        // return "#{ajaxSupport["+component.getClientId(context)+"]}";
+        return null;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/EventValueExpression.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/EventValueExpression.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/EventValueExpression.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,199 +18,194 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.component;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
+
 import javax.el.ELContext;
 import javax.el.ELException;
 import javax.el.ValueExpression;
+
 import javax.faces.component.StateHolder;
 import javax.faces.component.UIComponent;
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.renderkit.AjaxRendererUtils;
-
 /**
  * @author Maksim Kaszynski
- * 
+ *
  */
-public class EventValueExpression extends ValueExpression implements
-		StateHolder {
+public class EventValueExpression extends ValueExpression implements StateHolder {
+    private static final long serialVersionUID = -6583167387542332290L;
 
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -6583167387542332290L;
+    /**
+     * current update component. transient since saved state as component.
+     */
+    private transient AjaxSupport component = null;
+    private String componentId;
 
-	private String componentId;
+    public EventValueExpression() {
 
-	/**
-	 * current update component. transient since saved state as component.
-	 */
-	transient private AjaxSupport component = null;
+        // TODO Auto-generated constructor stub
+    }
 
-	
-	public EventValueExpression() {
-		// TODO Auto-generated constructor stub
-	}
+    public EventValueExpression(AjaxSupport component) {
+        super();
+        this.component = component;
+    }
 
-	public EventValueExpression(AjaxSupport component) {
-		super();
-		this.component = component;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.Expression#equals(java.lang.Object)
+     */
+    @Override
+    public boolean equals(Object obj) {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.Expression#equals(java.lang.Object)
-	 */
-	@Override
-	public boolean equals(Object obj) {
-		// TODO Auto-generated method stub
-		return false;
-	}
+        // TODO Auto-generated method stub
+        return false;
+    }
 
-	private AjaxSupport getComponent(FacesContext facesContext)
-			throws ELException {
+    private AjaxSupport getComponent(FacesContext facesContext) throws ELException {
+        if (component == null) {
+            UIComponent uiComponent = facesContext.getViewRoot().findComponent(componentId);
 
-		if (component == null) {
-			UIComponent uiComponent = facesContext.getViewRoot().findComponent(
-					componentId);
-			if (null != uiComponent && uiComponent instanceof AjaxSupport) {
-				component = (AjaxSupport) uiComponent;
-			} else {
-				throw new ELException(Messages.getMessage(
-						Messages.COMPONENT_NOT_FOUND, componentId));
-			}
+            if ((null != uiComponent) && (uiComponent instanceof AjaxSupport)) {
+                component = (AjaxSupport) uiComponent;
+            } else {
+                throw new ELException(Messages.getMessage(Messages.COMPONENT_NOT_FOUND, componentId));
+            }
+        }
 
-		}
+        return component;
+    }
 
-		return component;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.ValueExpression#getExpectedType()
+     */
+    @Override
+    public Class<?> getExpectedType() {
+        return String.class;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.ValueExpression#getExpectedType()
-	 */
-	@Override
-	public Class<?> getExpectedType() {
-		return String.class;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.Expression#getExpressionString()
+     */
+    @Override
+    public String getExpressionString() {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.Expression#getExpressionString()
-	 */
-	@Override
-	public String getExpressionString() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+        // TODO Auto-generated method stub
+        return null;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.ValueExpression#getType(javax.el.ELContext)
-	 */
-	@Override
-	public Class<?> getType(ELContext context) {
-		return String.class;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.ValueExpression#getType(javax.el.ELContext)
+     */
+    @Override
+    public Class<?> getType(ELContext context) {
+        return String.class;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.ValueExpression#getValue(javax.el.ELContext)
-	 */
-	@Override
-	public Object getValue(ELContext context) {
-		FacesContext facesContext = FacesContext.getCurrentInstance();
-		AjaxSupport component = getComponent(facesContext);
-		if (((UIComponent) component).isRendered()) {
-			return component.getEventString();
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.ValueExpression#getValue(javax.el.ELContext)
+     */
+    @Override
+    public Object getValue(ELContext context) {
+        FacesContext facesContext = FacesContext.getCurrentInstance();
+        AjaxSupport component = getComponent(facesContext);
 
-		} else {
-			return null;
-		}
-	}
+        if (((UIComponent) component).isRendered()) {
+            return component.getEventString();
+        } else {
+            return null;
+        }
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.Expression#hashCode()
-	 */
-	@Override
-	public int hashCode() {
-		// TODO Auto-generated method stub
-		return 0;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.Expression#hashCode()
+     */
+    @Override
+    public int hashCode() {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.Expression#isLiteralText()
-	 */
-	@Override
-	public boolean isLiteralText() {
-		// TODO Auto-generated method stub
-		return false;
-	}
+        // TODO Auto-generated method stub
+        return 0;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.ValueExpression#isReadOnly(javax.el.ELContext)
-	 */
-	@Override
-	public boolean isReadOnly(ELContext context) {
-		return true;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.Expression#isLiteralText()
+     */
+    @Override
+    public boolean isLiteralText() {
 
-	public boolean isTransient() {
-		return false;
-	}
+        // TODO Auto-generated method stub
+        return false;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext,
-	 *      java.lang.Object)
-	 */
-	public void restoreState(FacesContext context, Object state) {
-		componentId = (String) state;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.ValueExpression#isReadOnly(javax.el.ELContext)
+     */
+    @Override
+    public boolean isReadOnly(ELContext context) {
+        return true;
+    }
 
-	public Object saveState(FacesContext context) {
-		if (null == component) {
-			return componentId;
-		} else {
-			return AjaxRendererUtils
-					.getAbsoluteId((UIComponent) getComponent(context));
-		}
-	}
+    public boolean isTransient() {
+        return false;
+    }
 
-	/**
-	 * @param component
-	 *            the component to set
-	 */
-	public void setComponent(AjaxSupport component) {
-		this.component = component;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext,
+     *      java.lang.Object)
+     */
+    public void restoreState(FacesContext context, Object state) {
+        componentId = (String) state;
+    }
 
-	public void setTransient(boolean newTransientValue) {
-	}
+    public Object saveState(FacesContext context) {
+        if (null == component) {
+            return componentId;
+        } else {
+            return AjaxRendererUtils.getAbsoluteId((UIComponent) getComponent(context));
+        }
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.el.ValueExpression#setValue(javax.el.ELContext,
-	 *      java.lang.Object)
-	 */
-	@Override
-	public void setValue(ELContext context, Object value) {
-		throw new ELException(Messages.getMessage(Messages.EVENT_IS_READ_ONLY));
-	}
+    /**
+     * @param component
+     *            the component to set
+     */
+    public void setComponent(AjaxSupport component) {
+        this.component = component;
+    }
 
+    public void setTransient(boolean newTransientValue) {}
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.el.ValueExpression#setValue(javax.el.ELContext,
+     *      java.lang.Object)
+     */
+    @Override
+    public void setValue(ELContext context, Object value) {
+        throw new ELException(Messages.getMessage(Messages.EVENT_IS_READ_ONLY));
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/InvokerCallbackWrapper.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/InvokerCallbackWrapper.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/InvokerCallbackWrapper.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,27 +18,28 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.component;
 
+import org.ajax4jsf.context.InvokerCallback;
+
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.context.InvokerCallback;
-
 /**
  * @author Anton Belevich
  *
  */
 public class InvokerCallbackWrapper extends ContextCallbackWrapper implements InvokerCallback {
-
     public InvokerCallbackWrapper(InvokerCallback invokerCallback) {
-	super(invokerCallback);
+        super(invokerCallback);
     }
-    
-    /* 
+
+    /*
      * @see org.ajax4jsf.context.InvokerCallback#invokeRoot(javax.faces.context.FacesContext)
      */
     public void invokeRoot(FacesContext context) {
-	((InvokerCallback)this.callback).invokeRoot(context);
+        ((InvokerCallback) this.callback).invokeRoot(context);
     }
-
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/QueueRegistry.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/QueueRegistry.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/QueueRegistry.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -20,6 +20,7 @@
  */
 
 
+
 package org.ajax4jsf.component;
 
 import java.util.LinkedHashMap;
@@ -32,57 +33,51 @@
  * @author Nick Belaevski
  * @since 3.3.0
  */
-public class QueueRegistry {
+public final class QueueRegistry {
+    private static final String REGISTRY_ATTRIBUTE_NAME = QueueRegistry.class.getName();
+    private boolean shouldCreateDefaultGlobalQueue = false;
+    private Map<String, Object> queuesData = new LinkedHashMap<String, Object>();
 
-	private static final String REGISTRY_ATTRIBUTE_NAME = QueueRegistry.class.getName();
-	
-	private boolean shouldCreateDefaultGlobalQueue = false;
-	
-	private Map<String, Object> queuesData = new LinkedHashMap<String, Object>();
+    private QueueRegistry() {}
 
-	private QueueRegistry() {
-	}
-	
-	public static QueueRegistry getInstance(FacesContext context) {
-		ExternalContext externalContext = context.getExternalContext();
-		Map<String, Object> requestMap = externalContext.getRequestMap();
-		
-		QueueRegistry registry = (QueueRegistry) 
-			requestMap.get(REGISTRY_ATTRIBUTE_NAME);
-		
-		if (registry == null) {
-			registry = new QueueRegistry();
-			requestMap.put(REGISTRY_ATTRIBUTE_NAME, registry);
-		}
-		
-		return registry;
-	}
-	
-	public void registerQueue(FacesContext context, String clientName, Object data) {
-		if (!containsQueue(clientName)) {
-			queuesData.put(clientName, data);
-		} else {
-			context.getExternalContext().log("Queue with name '" + clientName + "' has already been registered");
-		}
-	}
-	
-	public boolean containsQueue(String name) {
-		return queuesData.containsKey(name);
-	}
-	
-	public Map<String, Object> getRegisteredQueues(FacesContext context) {
-		return queuesData;
-	}
+    public static QueueRegistry getInstance(FacesContext context) {
+        ExternalContext externalContext = context.getExternalContext();
+        Map<String, Object> requestMap = externalContext.getRequestMap();
+        QueueRegistry registry = (QueueRegistry) requestMap.get(REGISTRY_ATTRIBUTE_NAME);
 
-	public void setShouldCreateDefaultGlobalQueue() {
-		this.shouldCreateDefaultGlobalQueue = true;
-	}
-	
-	public boolean isShouldCreateDefaultGlobalQueue() {
-		return shouldCreateDefaultGlobalQueue;
-	}
-	
-	public boolean hasQueuesToEncode() {
-		return shouldCreateDefaultGlobalQueue || !queuesData.isEmpty();
-	}
+        if (registry == null) {
+            registry = new QueueRegistry();
+            requestMap.put(REGISTRY_ATTRIBUTE_NAME, registry);
+        }
+
+        return registry;
+    }
+
+    public void registerQueue(FacesContext context, String clientName, Object data) {
+        if (!containsQueue(clientName)) {
+            queuesData.put(clientName, data);
+        } else {
+            context.getExternalContext().log("Queue with name '" + clientName + "' has already been registered");
+        }
+    }
+
+    public boolean containsQueue(String name) {
+        return queuesData.containsKey(name);
+    }
+
+    public Map<String, Object> getRegisteredQueues(FacesContext context) {
+        return queuesData;
+    }
+
+    public void setShouldCreateDefaultGlobalQueue() {
+        this.shouldCreateDefaultGlobalQueue = true;
+    }
+
+    public boolean isShouldCreateDefaultGlobalQueue() {
+        return shouldCreateDefaultGlobalQueue;
+    }
+
+    public boolean hasQueuesToEncode() {
+        return shouldCreateDefaultGlobalQueue || !queuesData.isEmpty();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/component/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Base APIs and support classes of AJAX-enabled components
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FacesConfig.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FacesConfig.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FacesConfig.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,12 +18,21 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+
 import java.io.IOException;
 import java.io.InputStream;
+
 import java.net.URL;
 import java.net.URLConnection;
+
 import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.List;
@@ -32,163 +41,155 @@
 
 import javax.faces.FacesException;
 import javax.faces.webapp.FacesServlet;
+
 import javax.servlet.ServletContext;
+
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
 import javax.xml.parsers.SAXParserFactory;
 
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.XMLReader;
-
 /**
  * @author asmirnov
- * 
+ *
  */
 public class FacesConfig {
+    private static final String FACES_CONFIG_CLASS_PATH = "META-INF/faces-config.xml";
+    private static final String FACES_CONFIG_WEB_PATH = "/WEB-INF/faces-config.xml";
+    private static final Logger LOG = Logger.getLogger(FacesConfig.class.getName());
+    private List<String> excludedAttributes = new ArrayList<String>();
+    private SAXParserFactory factory;
 
-	private static final Logger log = Logger.getLogger(FacesConfig.class
-			.getName());
+    public FacesConfig() {
+        factory = SAXParserFactory.newInstance();
+        factory.setValidating(false);
+        factory.setNamespaceAware(true);
+    }
 
-	private static final String FACES_CONFIG_CLASS_PATH = "META-INF/faces-config.xml";
+    public void parse(ServletContext context) {
+        try {
+            parseClasspath(context);
+            parseOptional(context);
+            parseDefault(context);
+        } catch (ParsingException e) {
+            throw new FacesException("Error parsing faces-config", e);
+        }
+    }
 
-	private static final String FACES_CONFIG_WEB_PATH = "/WEB-INF/faces-config.xml";
+    protected void parseDefault(ServletContext context) throws ParsingException {
 
-	private List<String> excludedAttributes = new ArrayList<String>();
+        // Parse default faces config.
+        InputStream inputStream = context.getResourceAsStream(FACES_CONFIG_WEB_PATH);
 
-	private SAXParserFactory factory;
+        if (null != inputStream) {
+            try {
+                parse(inputStream);
+            } finally {
+                try {
+                    inputStream.close();
+                } catch (IOException e) {
+                    LOG.log(Level.WARNING, "Can't close input stream for web resource " + FACES_CONFIG_WEB_PATH, e);
+                }
+            }
+        }
+    }
 
-	public FacesConfig() {
-		factory = SAXParserFactory.newInstance();
-		factory.setValidating(false);
-		factory.setNamespaceAware(true);
-	}
+    protected void parseOptional(ServletContext context) throws ParsingException {
 
-	public void parse(ServletContext context) {
-		try {
-			parseClasspath(context);
-			parseOptional(context);
-			parseDefault(context);
-		} catch (ParsingException e) {
-			throw new FacesException("Error parsing faces-config",e);
-		}
-	}
+        // Parse additional faces-config files, if present.
+        String facesConfigs = context.getInitParameter(FacesServlet.CONFIG_FILES_ATTR);
 
-	protected void parseDefault(ServletContext context) throws ParsingException {
-		// Parse default faces config.
-		InputStream inputStream = context
-				.getResourceAsStream(FACES_CONFIG_WEB_PATH);
-		if (null != inputStream) {
-			try {
-				parse(inputStream);
-			} finally {
-				try {
-					inputStream.close();
-				} catch (IOException e) {
-					log.log(Level.WARNING,
-							"Can't close input stream for web resource "
-									+ FACES_CONFIG_WEB_PATH, e);
-				}
-			}
-		}
-	}
+        if (null != facesConfigs) {
+            String[] configNamesArray = facesConfigs.trim().split("(\\s)*,(\\s)*");
 
-	protected void parseOptional(ServletContext context)
-			throws ParsingException {
-		// Parse additional faces-config files, if present.
-		String facesConfigs = context
-				.getInitParameter(FacesServlet.CONFIG_FILES_ATTR);
-		if (null != facesConfigs) {
-			String[] configNamesArray = facesConfigs.trim().split(
-					"(\\s)*,(\\s)*");
-			for (int i = 0; i < configNamesArray.length; i++) {
-				String facesConfigPath = configNamesArray[i];
-				InputStream inputStream = context
-						.getResourceAsStream(facesConfigPath);
-				if (null != inputStream) {
-					try {
-						parse(inputStream);
-					} finally {
-						try {
-							inputStream.close();
-						} catch (IOException e) {
-							log.log(Level.WARNING,
-									"Can't close input stream for web resource "
-											+ facesConfigPath, e);
-						}
-					}
-				}
-			}
-		}
-	}
+            for (int i = 0; i < configNamesArray.length; i++) {
+                String facesConfigPath = configNamesArray[i];
+                InputStream inputStream = context.getResourceAsStream(facesConfigPath);
 
-	protected void parseClasspath(ServletContext context)
-			throws ParsingException {
-		ClassLoader classLoader = Thread.currentThread()
-				.getContextClassLoader();
-		if (null == classLoader) {
-			classLoader = context.getClass().getClassLoader();
-		}
-		try {
-			// Parse all faces-config.xml files in the classpath.
-			Enumeration<URL> resources = classLoader
-					.getResources(FACES_CONFIG_CLASS_PATH);
-			while (resources.hasMoreElements()) {
-				URL resourceURL = (URL) resources.nextElement();
-				try {
-					URLConnection connection = resourceURL.openConnection();
-					// To avoid file locking in the Windows environmemt.
-					connection.setUseCaches(false);
-					InputStream inputStream = connection.getInputStream();
-					try {
-						parse(inputStream);
-					} finally {
-						inputStream.close();
-					}
-				} catch (IOException e) {
-					log.log(Level.WARNING, "Can't parse "
-							+ resourceURL.toExternalForm(), e);
-				}
-			}
-		} catch (IOException e) {
-			log.log(Level.WARNING,
-					"Can't get META-INF/faces-config.xml resources", e);
-		}
-	}
+                if (null != inputStream) {
+                    try {
+                        parse(inputStream);
+                    } finally {
+                        try {
+                            inputStream.close();
+                        } catch (IOException e) {
+                            LOG.log(Level.WARNING, "Can't close input stream for web resource " + facesConfigPath, e);
+                        }
+                    }
+                }
+            }
+        }
+    }
 
-	protected void parse(InputStream facesConfig) throws ParsingException {
-		try {
-			SAXParser parser = getParser();
-			
-			//WL 10.3 parser returns new instance of XMLReader everytime
-			XMLReader reader = parser.getXMLReader();
-			FacesConfigHandler facesConfigHandler = new FacesConfigHandler(reader, excludedAttributes);
+    protected void parseClasspath(ServletContext context) throws ParsingException {
+        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
 
-			reader.setContentHandler(facesConfigHandler);
+        if (null == classLoader) {
+            classLoader = context.getClass().getClassLoader();
+        }
+
+        try {
+
+            // Parse all faces-config.xml files in the classpath.
+            Enumeration<URL> resources = classLoader.getResources(FACES_CONFIG_CLASS_PATH);
+
+            while (resources.hasMoreElements()) {
+                URL resourceURL = (URL) resources.nextElement();
+
+                try {
+                    URLConnection connection = resourceURL.openConnection();
+
+                    // To avoid file locking in the Windows environmemt.
+                    connection.setUseCaches(false);
+
+                    InputStream inputStream = connection.getInputStream();
+
+                    try {
+                        parse(inputStream);
+                    } finally {
+                        inputStream.close();
+                    }
+                } catch (IOException e) {
+                    LOG.log(Level.WARNING, "Can't parse " + resourceURL.toExternalForm(), e);
+                }
+            }
+        } catch (IOException e) {
+            LOG.log(Level.WARNING, "Can't get META-INF/faces-config.xml resources", e);
+        }
+    }
+
+    protected void parse(InputStream facesConfig) throws ParsingException {
+        try {
+            SAXParser parser = getParser();
+
+            // WL 10.3 parser returns new instance of XMLReader everytime
+            XMLReader reader = parser.getXMLReader();
+            FacesConfigHandler facesConfigHandler = new FacesConfigHandler(reader, excludedAttributes);
+
+            reader.setContentHandler(facesConfigHandler);
             reader.setEntityResolver(facesConfigHandler);
             reader.setErrorHandler(facesConfigHandler);
             reader.setDTDHandler(facesConfigHandler);
-			
-			reader.parse(new InputSource(facesConfig));
-		} catch (SAXException e) {
-			log.log(Level.WARNING, "Exception at faces-config.xml parsing", e);
-		} catch (IOException e) {
-			log.log(Level.WARNING, "Exception at faces-config.xml parsing", e);
-		}
-	}
+            reader.parse(new InputSource(facesConfig));
+        } catch (SAXException e) {
+            LOG.log(Level.WARNING, "Exception at faces-config.xml parsing", e);
+        } catch (IOException e) {
+            LOG.log(Level.WARNING, "Exception at faces-config.xml parsing", e);
+        }
+    }
 
-	protected SAXParser getParser() throws ParsingException {
-		try {
-			SAXParser parser = factory.newSAXParser();
-			return parser;
-		} catch (ParserConfigurationException e) {
-			throw new ParsingException("SAX Parser configuration error", e);
-		} catch (SAXException e) {
-			throw new ParsingException("SAX Parser instantiation error", e);
-		}
-	}
+    protected SAXParser getParser() throws ParsingException {
+        try {
+            SAXParser parser = factory.newSAXParser();
 
-	public List<String> getExcludedAttributes() {
-		return excludedAttributes;
-	}
+            return parser;
+        } catch (ParserConfigurationException e) {
+            throw new ParsingException("SAX Parser configuration error", e);
+        } catch (SAXException e) {
+            throw new ParsingException("SAX Parser instantiation error", e);
+        }
+    }
+
+    public List<String> getExcludedAttributes() {
+        return excludedAttributes;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FacesConfigHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FacesConfigHandler.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FacesConfigHandler.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,11 +18,11 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
-package org.ajax4jsf.config;
 
-import java.io.StringReader;
-import java.util.List;
 
+
+package org.ajax4jsf.config;
+
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.InputSource;
@@ -30,133 +30,127 @@
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.DefaultHandler;
 
+import java.io.StringReader;
+
+import java.util.List;
+
 /**
  * @author asmirnov
  *
  */
 public class FacesConfigHandler extends DefaultHandler {
-
-
-	private static final String JEE_NS = "http://java.sun.com/xml/ns/javaee";
-	private static final String BRIDGE_NS = "http://www.apache.org/myfaces/xml/ns/bridge/bridge-extension";
-	private static final String APPLICATION_ELEMENT          = "application";
-    private static final String APP_EXTENSION_ELEMENT     = "application-extension";
-    private static final String EXCLUDED_ATTRIBUTES_ELEMENT    = "excluded-attributes";
-    private static final String EXCLUDED_ATTRIBUTE_ELEMENT  = "excluded-attribute";
-
+    private static final String APPLICATION_ELEMENT = "application";
+    private static final String APP_EXTENSION_ELEMENT = "application-extension";
+    private static final String BRIDGE_NS = "http://www.apache.org/myfaces/xml/ns/bridge/bridge-extension";
+    private static final String EXCLUDED_ATTRIBUTES_ELEMENT = "excluded-attributes";
+    private static final String EXCLUDED_ATTRIBUTE_ELEMENT = "excluded-attribute";
+    private static final String JEE_NS = "http://java.sun.com/xml/ns/javaee";
     private List<String> excludedAttributes;
-	private XMLReader reader;
+    private XMLReader reader;
 
-	public FacesConfigHandler(XMLReader reader, List<String> excludedAttributes) {
-		this.reader = reader;
-		this.excludedAttributes = excludedAttributes;
-	}
+    public FacesConfigHandler(XMLReader reader, List<String> excludedAttributes) {
+        this.reader = reader;
+        this.excludedAttributes = excludedAttributes;
+    }
 
-	@Override
-	public void startElement(String uri, String localName, String name,
-			Attributes attributes) throws SAXException {
-		if (APPLICATION_ELEMENT.equals(localName) && JEE_NS.equals(uri)) {
-			reader.setContentHandler(new ApplicationHandler());
-		}
-	}
-	
     @Override
-    public InputSource resolveEntity(String publicId, String systemId) throws SAXException
-    {
-      // Do nothing, to avoid network requests to external DTD/Schema
-      return new InputSource(new StringReader(""));
+    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
+        if (APPLICATION_ELEMENT.equals(localName) && JEE_NS.equals(uri)) {
+            reader.setContentHandler(new ApplicationHandler());
+        }
     }
 
-    private abstract class FacesConfigElementHandler extends StateHandler {
-    	
-    	
-    	public FacesConfigElementHandler(ContentHandler parentHandler) {
-			super(parentHandler);
-		}
+    @Override
+    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
 
-		@Override
-    	protected XMLReader getReader() {
-    		return reader;
-    	}
+        // Do nothing, to avoid network requests to external DTD/Schema
+        return new InputSource(new StringReader(""));
     }
 
     /**
-	 * @author asmirnov
-	 *
-	 */
-	private class ApplicationHandler extends FacesConfigElementHandler {
-		public ApplicationHandler() {
-			super(FacesConfigHandler.this);
-		}
-		
-		@Override
-		protected ContentHandler getNextHandler(String uri, String localName,
-				Attributes attributes) {
-			if(APP_EXTENSION_ELEMENT.equals(localName) && JEE_NS.equals(uri)){
-				return new ApplicationExtensionHandler(this);
-			} else {
-				return null;
-			}
-		}
-	
-	}
+     * @author asmirnov
+     *
+     */
+    private class ApplicationExtensionHandler extends FacesConfigElementHandler {
+        public ApplicationExtensionHandler(ContentHandler parent) {
+            super(parent);
+        }
 
+        @Override
+        protected ContentHandler getNextHandler(String uri, String localName, Attributes attributes) {
+            if (EXCLUDED_ATTRIBUTES_ELEMENT.equals(localName) && BRIDGE_NS.equals(uri)) {
+                return new ExcludedAttributesHandler(this);
+            } else {
+                return null;
+            }
+        }
+    }
+
+
     /**
-	 * @author asmirnov
-	 *
-	 */
-	private class ApplicationExtensionHandler extends FacesConfigElementHandler {
-		public ApplicationExtensionHandler(ContentHandler parent) {
-			super(parent);
-		}
-		
-		@Override
-		protected ContentHandler getNextHandler(String uri, String localName,
-				Attributes attributes) {
-			if(EXCLUDED_ATTRIBUTES_ELEMENT.equals(localName) && BRIDGE_NS.equals(uri)){
-				return new ExcludedAttributesHandler(this);
-			} else {
-				return null;
-			}
-		}
-	
-	}
-	
+     * @author asmirnov
+     *
+     */
+    private class ApplicationHandler extends FacesConfigElementHandler {
+        public ApplicationHandler() {
+            super(FacesConfigHandler.this);
+        }
+
+        @Override
+        protected ContentHandler getNextHandler(String uri, String localName, Attributes attributes) {
+            if (APP_EXTENSION_ELEMENT.equals(localName) && JEE_NS.equals(uri)) {
+                return new ApplicationExtensionHandler(this);
+            } else {
+                return null;
+            }
+        }
+    }
+
+
     /**
-	 * @author asmirnov
-	 *
-	 */
-	private class ExcludedAttributesHandler extends FacesConfigElementHandler {
+     * @author asmirnov
+     *
+     */
+    private class ExcludedAttributeHandler extends StringContentHandler {
+        public ExcludedAttributeHandler(ContentHandler parent) {
+            super(reader, parent, new StringBuilder());
+        }
 
-		public ExcludedAttributesHandler(ContentHandler parent) {
-			super(parent);
-		}
-		
-		@Override
-		protected ContentHandler getNextHandler(String uri, String localName,
-				Attributes attributes) {
-			if(EXCLUDED_ATTRIBUTE_ELEMENT.equals(localName) && BRIDGE_NS.equals(uri)){
-				return new ExcludedAttributeHandler(this);
-			} else {
-				return null;
-			}
-		}
-	
-	}
-	/**
-	 * @author asmirnov
-	 *
-	 */
-	private class ExcludedAttributeHandler extends StringContentHandler {
+        @Override
+        protected void endLastElement() {
+            excludedAttributes.add(getResult().toString());
+        }
+    }
 
-		public ExcludedAttributeHandler(ContentHandler parent) {
-			super(reader, parent, new StringBuilder());
-		}
 
-		@Override
-		protected void endLastElement() {
-			excludedAttributes.add(getResult().toString());
-		}
-	}
+    /**
+     * @author asmirnov
+     *
+     */
+    private class ExcludedAttributesHandler extends FacesConfigElementHandler {
+        public ExcludedAttributesHandler(ContentHandler parent) {
+            super(parent);
+        }
 
+        @Override
+        protected ContentHandler getNextHandler(String uri, String localName, Attributes attributes) {
+            if (EXCLUDED_ATTRIBUTE_ELEMENT.equals(localName) && BRIDGE_NS.equals(uri)) {
+                return new ExcludedAttributeHandler(this);
+            } else {
+                return null;
+            }
+        }
+    }
+
+
+    private abstract class FacesConfigElementHandler extends StateHandler {
+        public FacesConfigElementHandler(ContentHandler parentHandler) {
+            super(parentHandler);
+        }
+
+        @Override
+        protected XMLReader getReader() {
+            return reader;
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FilterBean.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FilterBean.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FilterBean.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,54 +18,75 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
+class FilterBean {
+    private final String className;
+    private final String name;
 
-class FilterBean {
-	private final String name;
-	private final String className;
-	/**
-	 * @param name
-	 * @param className
-	 */
-	public FilterBean(String name, String className) {
-		super();
-		this.name = name;
-		this.className = className;
-	}
-	public String getName() {
-		return name;
-	}
-	public String getClassName() {
-		return className;
-	}
-	/* (non-Javadoc)
-	 * @see java.lang.Object#hashCode()
-	 */
-	@Override
-	public int hashCode() {
-		final int prime = 31;
-		int result = 1;
-		result = prime * result + ((name == null) ? 0 : name.hashCode());
-		return result;
-	}
-	/* (non-Javadoc)
-	 * @see java.lang.Object#equals(java.lang.Object)
-	 */
-	@Override
-	public boolean equals(Object obj) {
-		if (this == obj)
-			return true;
-		if (obj == null)
-			return false;
-		if (getClass() != obj.getClass())
-			return false;
-		FilterBean other = (FilterBean) obj;
-		if (name == null) {
-			if (other.name != null)
-				return false;
-		} else if (!name.equals(other.name))
-			return false;
-		return true;
-	}
-}
\ No newline at end of file
+    /**
+     * @param name
+     * @param className
+     */
+    public FilterBean(String name, String className) {
+        super();
+        this.name = name;
+        this.className = className;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public String getClassName() {
+        return className;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#hashCode()
+     */
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+
+        result = prime * result + ((name == null) ? 0 : name.hashCode());
+
+        return result;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#equals(java.lang.Object)
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+
+        if (obj == null) {
+            return false;
+        }
+
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+
+        FilterBean other = (FilterBean) obj;
+
+        if (name == null) {
+            if (other.name != null) {
+                return false;
+            }
+        } else if (!name.equals(other.name)) {
+            return false;
+        }
+
+        return true;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FilterMapping.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FilterMapping.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FilterMapping.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,6 +18,9 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
 /**
@@ -25,61 +28,70 @@
  *
  */
 class FilterMapping {
-	
-	private final String filterName;
-	private final String servletName;
-	private final String urlPattern;
+    private final String filterName;
+    private final String servletName;
+    private final String urlPattern;
 
+    public FilterMapping(String filterName, String servletName, String urlPattern) {
+        this.filterName = filterName;
+        this.servletName = servletName;
+        this.urlPattern = urlPattern;
+    }
 
-	public FilterMapping(String filterName, String servletName,
-			String urlPattern) {
-		this.filterName = filterName;
-		this.servletName = servletName;
-		this.urlPattern = urlPattern;
-	}
+    public String getFilterName() {
+        return filterName;
+    }
 
-	public String getFilterName() {
-		return filterName;
-	}
+    public String getServletName() {
+        return servletName;
+    }
 
-	public String getServletName() {
-		return servletName;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#hashCode()
+     */
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
 
-	/* (non-Javadoc)
-	 * @see java.lang.Object#hashCode()
-	 */
-	@Override
-	public int hashCode() {
-		final int prime = 31;
-		int result = 1;
-		result = prime * result
-				+ ((filterName == null) ? 0 : filterName.hashCode());
-		return result;
-	}
+        result = prime * result + ((filterName == null) ? 0 : filterName.hashCode());
 
-	/* (non-Javadoc)
-	 * @see java.lang.Object#equals(java.lang.Object)
-	 */
-	@Override
-	public boolean equals(Object obj) {
-		if (this == obj)
-			return true;
-		if (obj == null)
-			return false;
-		if (getClass() != obj.getClass())
-			return false;
-		FilterMapping other = (FilterMapping) obj;
-		if (filterName == null) {
-			if (other.filterName != null)
-				return false;
-		} else if (!filterName.equals(other.filterName))
-			return false;
-		return true;
-	}
+        return result;
+    }
 
-	public String getUrlPattern() {
-		return urlPattern;
-	}
-	
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#equals(java.lang.Object)
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+
+        if (obj == null) {
+            return false;
+        }
+
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+
+        FilterMapping other = (FilterMapping) obj;
+
+        if (filterName == null) {
+            if (other.filterName != null) {
+                return false;
+            }
+        } else if (!filterName.equals(other.filterName)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    public String getUrlPattern() {
+        return urlPattern;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FrameworkConfiguration.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FrameworkConfiguration.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FrameworkConfiguration.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,207 +1,153 @@
 package org.ajax4jsf.config;
 
+import org.ajax4jsf.util.ELUtils;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.util.EnumMap;
 import java.util.Map;
 import java.util.regex.Pattern;
 
 import javax.el.ExpressionFactory;
 import javax.el.ValueExpression;
+
 import javax.faces.context.ExternalContext;
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.util.ELUtils;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
-
-
 /**
  * @author Anton Belevich
  * @since 4.0
  * framework configuration class
  */
-
 public final class FrameworkConfiguration {
-	
-	private static final Logger LOGGER = RichfacesLogger.CONFIG.getLogger();
-	
-	private Map<InitParam, String> initParams = new EnumMap<InitParam, String>(InitParam.class);
-	
-	private static final Pattern ALLOWABLE_BOOLEANS = Pattern.compile("^true|false$",Pattern.CASE_INSENSITIVE);
-	 
-	private static final Pattern ALLOWABLE_NUMBER = Pattern.compile("^\\d+$");
+    private static final Logger LOGGER = RichfacesLogger.CONFIG.getLogger();
+    private static final Pattern ALLOWABLE_NUMBER = Pattern.compile("^\\d+$");
+    private static final Pattern ALLOWABLE_BOOLEANS = Pattern.compile("^true|false$", Pattern.CASE_INSENSITIVE);
+    private Map<InitParam, String> initParams = new EnumMap<InitParam, String>(InitParam.class);
 
-
     private FrameworkConfiguration(ExternalContext externalContext) {
-		processInitParams(externalContext);
-	}
-	
+        processInitParams(externalContext);
+    }
+
+    public enum InitParam {
+        SKIN("org.richfaces.SKIN", "DEFAULT"), LoadScriptStrategy("org.richfaces.LoadScriptStrategy", "DEFAULT"),
+        LoadStyleStrategy("org.richfaces.LoadStyleStrategy", "DEFAULT"), LOGFILE("org.ajax4jsf.LOGFILE", "none"),
+        VIEW_HANDLERS("org.ajax4jsf.VIEW_HANDLERS", "none"),
+        CONTROL_COMPONENTS("org.ajax4jsf.CONTROL_COMPONENTS", "none"),
+        ENCRYPT_PASSWORD("org.ajax4jsf.ENCRYPT_PASSWORD", "random"),
+        GLOBAL_RESOURCE_URI_PREFIX("org.ajax4jsf.GLOBAL_RESOURCE_URI_PREFIX", "a4j/g"),
+        SESSION_RESOURCE_URI_PREFIX("org.ajax4jsf.SESSION_RESOURCE_URI_PREFIX", "a4j/s"),
+        ENCRYPT_RESOURCE_DATA("org.ajax4jsf.ENCRYPT_RESOURCE_DATA", "false"),
+        COMPRESS_SCRIPT("org.ajax4jsf.COMPRESS_SCRIPT", "true"),
+        SERIALIZE_SERVER_STATE("org.ajax4jsf.SERIALIZE_SERVER_STATE", "false"),
+        DEFAULT_EXPIRE("org.ajax4jsf.DEFAULT_EXPIRE", "86400");
+
+        private String defaultValue;
+        private String qualifiedName;
+
+        InitParam(String qualifiedName, String defaultValue) {
+            this.qualifiedName = qualifiedName;
+            this.defaultValue = defaultValue;
+        }
+
+        public String getDefaultValue() {
+            return defaultValue;
+        }
+
+        public String getQualifiedName() {
+            return qualifiedName;
+        }
+    }
+
     public static FrameworkConfiguration getInstance() {
-    	FacesContext facesContext = FacesContext.getCurrentInstance();
-        return getInstance(facesContext.getExternalContext());
+        FacesContext facesContext = FacesContext.getCurrentInstance();
 
+        return getInstance(facesContext.getExternalContext());
     }
-	
+
     public static FrameworkConfiguration getInstance(ExternalContext externalContext) {
-    	return new FrameworkConfiguration(externalContext);
+        return new FrameworkConfiguration(externalContext);
     }
-    
+
     private boolean isBooleanValue(String value) {
-       	return ALLOWABLE_BOOLEANS.matcher(value).matches();
+        return ALLOWABLE_BOOLEANS.matcher(value).matches();
     }
-    
+
     private boolean isNumberValue(String value) {
-    	return ALLOWABLE_NUMBER.matcher(value).matches();
+        return ALLOWABLE_NUMBER.matcher(value).matches();
     }
-    
+
     public int getOptionNumber(InitParam param) {
-    	
-    	String value = getOption(param);
-    	
-    	if(ELUtils.isValueReference(value)) {
-    		return ((Integer)resolveELParam(FacesContext.getCurrentInstance(), value, java.lang.Integer.class)).intValue();
-    	}
-    	
-    	if(isNumberValue(value)) {
-    		return  Integer.parseInt(value);
-    	} 
-    	LOGGER.error("option value: " + param.getQualifiedName() + " is not an integer number set default value: " + param.getDefaultValue());
-    	return Integer.parseInt(param.getDefaultValue());
+        String value = getOption(param);
+
+        if (ELUtils.isValueReference(value)) {
+            return ((Integer) resolveELParam(FacesContext.getCurrentInstance(), value,
+                                             java.lang.Integer.class)).intValue();
+        }
+
+        if (isNumberValue(value)) {
+            return Integer.parseInt(value);
+        }
+
+        LOGGER.error("option value: " + param.getQualifiedName() + " is not an integer number set default value: "
+                     + param.getDefaultValue());
+
+        return Integer.parseInt(param.getDefaultValue());
     }
-    
+
     public boolean isOptionEnabled(InitParam param) {
-    	String value = getOption(param);
-    	
-		if(ELUtils.isValueReference(value)) {
-			return ((Boolean)resolveELParam(FacesContext.getCurrentInstance(), value, java.lang.Boolean.class)).booleanValue();
-		}
-		
-		if(isBooleanValue(value)) {
-			return Boolean.parseBoolean(value);
-		}
-		
-		LOGGER.error("option value: " + param.getQualifiedName() + " is not a boolean value set default value: " + param.getDefaultValue());
-   		return Boolean.parseBoolean(param.getDefaultValue());    	
+        String value = getOption(param);
+
+        if (ELUtils.isValueReference(value)) {
+            return ((Boolean) resolveELParam(FacesContext.getCurrentInstance(), value,
+                                             java.lang.Boolean.class)).booleanValue();
+        }
+
+        if (isBooleanValue(value)) {
+            return Boolean.parseBoolean(value);
+        }
+
+        LOGGER.error("option value: " + param.getQualifiedName() + " is not a boolean value set default value: "
+                     + param.getDefaultValue());
+
+        return Boolean.parseBoolean(param.getDefaultValue());
     }
-    
+
     public String getOptionValue(InitParam param) {
-    	String value = getOption(param);
-    	if(ELUtils.isValueReference(value)) {
-    		return (String)resolveELParam(FacesContext.getCurrentInstance(), value, java.lang.String.class);
-    	}
-     	return value;
+        String value = getOption(param);
+
+        if (ELUtils.isValueReference(value)) {
+            return (String) resolveELParam(FacesContext.getCurrentInstance(), value, java.lang.String.class);
+        }
+
+        return value;
     }
-    
+
     public String getOption(InitParam param) {
-    	return initParams.get(param);
+        return initParams.get(param);
     }
-    
-	private void processInitParams(ExternalContext externalContext){
-		for(InitParam param: InitParam.values()) {
-			String paramName = param.qualifiedName;
-			String paramValue = externalContext.getInitParameter(paramName);
-			String value = param.getDefaultValue();
-		
-			if (paramValue != null && !"".equals(paramValue.trim())) {
-				value = paramValue;
-			} 
-			
-			initParams.put(param, value);
-		}
-	}
-	
-	public Object resolveELParam(FacesContext context, String value, Class <?> expectedClass) {
-	
-		ExpressionFactory factory = context.getApplication().getExpressionFactory();
-		ValueExpression valueExpression = factory.createValueExpression(context.getELContext(), value, expectedClass);
-		Object returnValue = valueExpression.getValue(context.getELContext());
-		
-		return returnValue;  
-	}
-	
-	public enum InitParam {
-		
-		SKIN (
-			"org.richfaces.SKIN",
-			"DEFAULT"
-		), 
-		
-		LoadScriptStrategy (
-			"org.richfaces.LoadScriptStrategy", 
-			"DEFAULT"
-		), 
-		
-		LoadStyleStrategy (
-			"org.richfaces.LoadStyleStrategy", 
-			"DEFAULT"
-		), 
-		
-		LOGFILE (
-				"org.ajax4jsf.LOGFILE",
-				"none"
-		), 
-		
-		VIEW_HANDLERS(
-				"org.ajax4jsf.VIEW_HANDLERS",
-				"none"
-		), 
-		
-		CONTROL_COMPONENTS(
-				"org.ajax4jsf.CONTROL_COMPONENTS",
-				"none"
-		), 
-		
-		ENCRYPT_PASSWORD (
-				"org.ajax4jsf.ENCRYPT_PASSWORD",
-				"random"
-		), 
-		
-		GLOBAL_RESOURCE_URI_PREFIX(
-				"org.ajax4jsf.GLOBAL_RESOURCE_URI_PREFIX",
-				"a4j/g"
-		),
-		
-		SESSION_RESOURCE_URI_PREFIX(
-				"org.ajax4jsf.SESSION_RESOURCE_URI_PREFIX",
-				"a4j/s"
-		),
-		
-		ENCRYPT_RESOURCE_DATA(
-				"org.ajax4jsf.ENCRYPT_RESOURCE_DATA",
-				"false"
-		),
-		
-		COMPRESS_SCRIPT(
-				"org.ajax4jsf.COMPRESS_SCRIPT",
-				"true"
-		), 
-		
-		SERIALIZE_SERVER_STATE(
-				"org.ajax4jsf.SERIALIZE_SERVER_STATE",
-				"false"
-		),
-		
 
-		DEFAULT_EXPIRE (
-				"org.ajax4jsf.DEFAULT_EXPIRE", 
-				"86400"
-		);
-		
-		private String qualifiedName;
-		private String defaultValue;
-		
-		InitParam(String qualifiedName,String defaultValue) {
-			this.qualifiedName = qualifiedName;
-			this.defaultValue = defaultValue;
+    private void processInitParams(ExternalContext externalContext) {
+        for (InitParam param : InitParam.values()) {
+            String paramName = param.qualifiedName;
+            String paramValue = externalContext.getInitParameter(paramName);
+            String value = param.getDefaultValue();
+
+            if ((paramValue != null) && !"".equals(paramValue.trim())) {
+                value = paramValue;
+            }
+
+            initParams.put(param, value);
         }
-		
-		public String getDefaultValue() {
-            return defaultValue;
-        }
-       
-        public String getQualifiedName() {
-            return qualifiedName;
-        }
     }
-	
+
+    public Object resolveELParam(FacesContext context, String value, Class<?> expectedClass) {
+        ExpressionFactory factory = context.getApplication().getExpressionFactory();
+        ValueExpression valueExpression = factory.createValueExpression(context.getELContext(), value, expectedClass);
+        Object returnValue = valueExpression.getValue(context.getELContext());
+
+        return returnValue;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ParsingException.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ParsingException.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ParsingException.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,6 +18,9 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
 /**
@@ -26,41 +29,44 @@
  */
 public class ParsingException extends Exception {
 
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -6052151937934930943L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = -6052151937934930943L;
 
-	/**
-	 * 
-	 */
-	public ParsingException() {
-		// TODO Auto-generated constructor stub
-	}
+    /**
+     *
+     */
+    public ParsingException() {
 
-	/**
-	 * @param message
-	 */
-	public ParsingException(String message) {
-		super(message);
-		// TODO Auto-generated constructor stub
-	}
+        // TODO Auto-generated constructor stub
+    }
 
-	/**
-	 * @param cause
-	 */
-	public ParsingException(Throwable cause) {
-		super(cause);
-		// TODO Auto-generated constructor stub
-	}
+    /**
+     * @param message
+     */
+    public ParsingException(String message) {
+        super(message);
 
-	/**
-	 * @param message
-	 * @param cause
-	 */
-	public ParsingException(String message, Throwable cause) {
-		super(message, cause);
-		// TODO Auto-generated constructor stub
-	}
+        // TODO Auto-generated constructor stub
+    }
 
+    /**
+     * @param cause
+     */
+    public ParsingException(Throwable cause) {
+        super(cause);
+
+        // TODO Auto-generated constructor stub
+    }
+
+    /**
+     * @param message
+     * @param cause
+     */
+    public ParsingException(String message, Throwable cause) {
+        super(message, cause);
+
+        // TODO Auto-generated constructor stub
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ServletBean.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ServletBean.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ServletBean.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,54 +18,75 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
+class ServletBean {
+    private final String className;
+    private final String name;
 
-class ServletBean {
-	private final String name;
-	private final String className;
-	/**
-	 * @param name
-	 * @param className
-	 */
-	public ServletBean(String name, String className) {
-		super();
-		this.name = name;
-		this.className = className;
-	}
-	public String getName() {
-		return name;
-	}
-	public String getClassName() {
-		return className;
-	}
-	/* (non-Javadoc)
-	 * @see java.lang.Object#hashCode()
-	 */
-	@Override
-	public int hashCode() {
-		final int prime = 31;
-		int result = 1;
-		result = prime * result + ((name == null) ? 0 : name.hashCode());
-		return result;
-	}
-	/* (non-Javadoc)
-	 * @see java.lang.Object#equals(java.lang.Object)
-	 */
-	@Override
-	public boolean equals(Object obj) {
-		if (this == obj)
-			return true;
-		if (obj == null)
-			return false;
-		if (getClass() != obj.getClass())
-			return false;
-		ServletBean other = (ServletBean) obj;
-		if (name == null) {
-			if (other.name != null)
-				return false;
-		} else if (!name.equals(other.name))
-			return false;
-		return true;
-	}
-}
\ No newline at end of file
+    /**
+     * @param name
+     * @param className
+     */
+    public ServletBean(String name, String className) {
+        super();
+        this.name = name;
+        this.className = className;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public String getClassName() {
+        return className;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#hashCode()
+     */
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+
+        result = prime * result + ((name == null) ? 0 : name.hashCode());
+
+        return result;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#equals(java.lang.Object)
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+
+        if (obj == null) {
+            return false;
+        }
+
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+
+        ServletBean other = (ServletBean) obj;
+
+        if (name == null) {
+            if (other.name != null) {
+                return false;
+            }
+        } else if (!name.equals(other.name)) {
+            return false;
+        }
+
+        return true;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ServletMapping.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ServletMapping.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/ServletMapping.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,59 +18,75 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
 class ServletMapping {
-	private final String servletName;
-	private final String urlPattern;
+    private final String servletName;
+    private final String urlPattern;
 
-	/**
-	 * @param servletName
-	 * @param urlPattern
-	 */
-	public ServletMapping(String servletName, String urlPattern) {
-		super();
-		this.servletName = servletName;
-		this.urlPattern = urlPattern;
-	}
+    /**
+     * @param servletName
+     * @param urlPattern
+     */
+    public ServletMapping(String servletName, String urlPattern) {
+        super();
+        this.servletName = servletName;
+        this.urlPattern = urlPattern;
+    }
 
-	public String getServletName() {
-		return servletName;
-	}
+    public String getServletName() {
+        return servletName;
+    }
 
-	public String getUrlPattern() {
-		return urlPattern;
-	}
+    public String getUrlPattern() {
+        return urlPattern;
+    }
 
-	/* (non-Javadoc)
-	 * @see java.lang.Object#hashCode()
-	 */
-	@Override
-	public int hashCode() {
-		final int prime = 31;
-		int result = 1;
-		result = prime * result
-				+ ((servletName == null) ? 0 : servletName.hashCode());
-		return result;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#hashCode()
+     */
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
 
-	/* (non-Javadoc)
-	 * @see java.lang.Object#equals(java.lang.Object)
-	 */
-	@Override
-	public boolean equals(Object obj) {
-		if (this == obj)
-			return true;
-		if (obj == null)
-			return false;
-		if (getClass() != obj.getClass())
-			return false;
-		ServletMapping other = (ServletMapping) obj;
-		if (servletName == null) {
-			if (other.servletName != null)
-				return false;
-		} else if (!servletName.equals(other.servletName))
-			return false;
-		return true;
-	}
-}
\ No newline at end of file
+        result = prime * result + ((servletName == null) ? 0 : servletName.hashCode());
+
+        return result;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#equals(java.lang.Object)
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+
+        if (obj == null) {
+            return false;
+        }
+
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+
+        ServletMapping other = (ServletMapping) obj;
+
+        if (servletName == null) {
+            if (other.servletName != null) {
+                return false;
+            }
+        } else if (!servletName.equals(other.servletName)) {
+            return false;
+        }
+
+        return true;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/StateHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/StateHandler.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/StateHandler.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,10 +18,11 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
-import java.io.StringReader;
-
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.InputSource;
@@ -29,61 +30,62 @@
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.DefaultHandler;
 
+import java.io.StringReader;
+
 /**
  * @author asmirnov
- * 
+ *
  */
 public abstract class StateHandler extends DefaultHandler {
+    private int depth = 0;
+    private final ContentHandler parentHandler;
 
-	private final ContentHandler parentHandler;
+    public StateHandler(ContentHandler parentHandler) {
+        super();
+        this.parentHandler = parentHandler;
+    }
 
+    @Override
+    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
+        ContentHandler nextHandler = getNextHandler(uri, localName, attributes);
 
-	private int depth = 0;
+        if (null == nextHandler) {
+            depth++;
+        } else {
 
-	public StateHandler(ContentHandler parentHandler) {
-		super();
-		this.parentHandler = parentHandler;
-	}
+            // TODO nick - setup all four handlers here?
+            getReader().setContentHandler(nextHandler);
+        }
+    }
 
-	@Override
-	public void startElement(String uri, String localName, String name,
-			Attributes attributes) throws SAXException {
-		ContentHandler nextHandler = getNextHandler(uri, localName, attributes);
-		if (null == nextHandler) {
-			depth++;
-		} else {
-			//TODO nick - setup all four handlers here?
-			getReader().setContentHandler(nextHandler);
-		}
-	}
+    protected ContentHandler getNextHandler(String uri, String localName, Attributes attributes) {
+        return null;
+    }
 
-	protected ContentHandler getNextHandler(String uri, String localName,
-			Attributes attributes) {
-		return null;
-	}
-	
-	@Override
-	public void endElement(String uri, String localName, String name)
-			throws SAXException {
-		if(depth-- == 0){
-			if(null != parentHandler){
-				//TODO nick - see to-do in startElement method
-				getReader().setContentHandler(parentHandler);
-			}
-			endLastElement();
-		}
-	}
+    @Override
+    public void endElement(String uri, String localName, String name) throws SAXException {
+        if (depth-- == 0) {
+            if (null != parentHandler) {
 
-	protected void endLastElement() {
-		// Do nothing		
-	}
-	
+                // TODO nick - see to-do in startElement method
+                getReader().setContentHandler(parentHandler);
+            }
+
+            endLastElement();
+        }
+    }
+
+    protected void endLastElement() {
+
+        // Do nothing
+    }
+
     @Override
-    public InputSource resolveEntity(String publicId, String systemId) throws SAXException
-    {
-      // Do nothing, to avoid network requests to external DTD/Schema
-      return new InputSource(new StringReader(""));
+    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
+
+        // Do nothing, to avoid network requests to external DTD/Schema
+        return new InputSource(new StringReader(""));
     }
 
-	protected abstract XMLReader getReader(); 
+    protected abstract XMLReader getReader();
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/StringContentHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/StringContentHandler.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/StringContentHandler.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,6 +18,9 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
 import org.xml.sax.ContentHandler;
@@ -26,33 +29,29 @@
 
 /**
  * @author asmirnov
- * 
+ *
  */
 class StringContentHandler extends StateHandler {
+    private final XMLReader reader;
+    private StringBuilder result;
 
-	private StringBuilder result;
-	
-	private final XMLReader reader;
+    public StringContentHandler(XMLReader reader, ContentHandler parentHandler, StringBuilder result) {
+        super(parentHandler);
+        this.reader = reader;
+        this.result = result;
+    }
 
-	public StringContentHandler(XMLReader reader, ContentHandler parentHandler,
-			StringBuilder result) {
-		super(parentHandler);
-		this.reader = reader;
-		this.result = result;
-	}
+    @Override
+    public void characters(char[] ch, int start, int length) throws SAXException {
+        result.append(ch, start, length);
+    }
 
-	@Override
-	public void characters(char[] ch, int start, int length)
-			throws SAXException {
-		result.append(ch, start, length);
-	}
+    protected StringBuilder getResult() {
+        return result;
+    }
 
-	protected StringBuilder getResult() {
-		return result;
-	}
-	
-	@Override
-	protected XMLReader getReader() {
-		return reader;
-	}
+    @Override
+    protected XMLReader getReader() {
+        return reader;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/WebXMLParser.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/WebXMLParser.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/WebXMLParser.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,213 +18,220 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.config;
 
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+
 import java.io.IOException;
 import java.io.InputStream;
+
 import java.util.ArrayList;
 import java.util.List;
 
 import javax.servlet.ServletContext;
 import javax.servlet.ServletException;
+
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
 import javax.xml.parsers.SAXParserFactory;
 
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.XMLReader;
-
 /**
  * @author asmirnov
- * 
+ *
  */
 @Deprecated
 public class WebXMLParser {
+    static final String FACES_SERVLET_CLASS = "javax.faces.webapp.FacesServlet";
+    public static final String WEB_XML = "/WEB-INF/web.xml";
+    private String facesFilterPrefix = null;
 
-	public static final String WEB_XML = "/WEB-INF/web.xml";
+    /**
+     * Suffix for Resource-Ajax filter , in common must be same as for
+     * {@link javax.faces.webapp.FacesServlet}
+     */
+    private String facesFilterSuffix = null;
+    private String facesServletPrefix = null;
+    private String facesServletSuffix = null;
+    private List<String> facesServletMappings;
+    private List<String> filterMappings;
 
-	private String _facesFilterPrefix = null;
-	/**
-	 * Suffix for Resource-Ajax filter , in common must be same as for
-	 * {@link javax.faces.webapp.FacesServlet}
-	 */
-	private String _facesFilterSuffix = null;
-	private String _facesServletPrefix = null;
-	private String _facesServletSuffix = null;
+    public void init(InputStream webXml, String filterName) throws ParsingException {
+        try {
 
-	private List<String> facesServletMappings;
-	private List<String> filterMappings;
-	static final String FACES_SERVLET_CLASS = "javax.faces.webapp.FacesServlet";
+            // Prepare SAX parser for a web-xml.
+            SAXParserFactory factory = SAXParserFactory.newInstance();
 
-	public void init(InputStream webXml, String filterName)
-			throws ParsingException {
-		try {
-			// Prepare SAX parser for a web-xml.
-			SAXParserFactory factory = SAXParserFactory.newInstance();
-			factory.setValidating(false);
-			factory.setNamespaceAware(true);
-			SAXParser parser = factory.newSAXParser();
-			//WL 10.3 parser returns new instance of XMLReader everytime
-			XMLReader reader = parser.getXMLReader();
-			
-			// Parse web.xml with state-avare content handler.
-			WebappHandler webappHandler = new WebappHandler(reader);
-            
-			reader.setContentHandler(webappHandler);
+            factory.setValidating(false);
+            factory.setNamespaceAware(true);
+
+            SAXParser parser = factory.newSAXParser();
+
+            // WL 10.3 parser returns new instance of XMLReader everytime
+            XMLReader reader = parser.getXMLReader();
+
+            // Parse web.xml with state-avare content handler.
+            WebappHandler webappHandler = new WebappHandler(reader);
+
+            reader.setContentHandler(webappHandler);
             reader.setEntityResolver(webappHandler);
             reader.setErrorHandler(webappHandler);
             reader.setDTDHandler(webappHandler);
-
             reader.parse(new InputSource(webXml));
 
-			// Calculate Faces Servlet and filter mappings.
-			for (ServletBean servlet : webappHandler.getServlets()) {
-				if (FACES_SERVLET_CLASS.equals(servlet.getClassName())) {
-					facesServletMappings = new ArrayList<String>();
-					for (ServletMapping mapping : webappHandler
-							.getServletMappings()) {
-						if (servlet.getName().equals(mapping.getServletName())) {
-							facesServletMappings.add(mapping.getUrlPattern());
-							String asPrefix = getAsPrefix(mapping
-									.getUrlPattern());
-							if (null != asPrefix) {
-								_facesServletPrefix = asPrefix;
+            // Calculate Faces Servlet and filter mappings.
+            for (ServletBean servlet : webappHandler.getServlets()) {
+                if (FACES_SERVLET_CLASS.equals(servlet.getClassName())) {
+                    facesServletMappings = new ArrayList<String>();
 
-							}
-							String asSuffix = getAsSuffix(mapping
-									.getUrlPattern());
-							if (null != asSuffix) {
-								_facesServletSuffix = asSuffix;
+                    for (ServletMapping mapping : webappHandler.getServletMappings()) {
+                        if (servlet.getName().equals(mapping.getServletName())) {
+                            facesServletMappings.add(mapping.getUrlPattern());
 
-							}
-						}
-					}
-				}
-			}
-			// Find named filter configuration.
-			// Got filter, check it's mapping.
-			filterMappings = new ArrayList<String>();
-			for (FilterMapping mapping : webappHandler.getFilterMappings()) {
-				if (mapping.getFilterName().equals(filterName)) {
-					if (null != mapping.getUrlPattern()
-							&& !"".equals(mapping.getUrlPattern())) {
-						filterMappings.add(mapping.getUrlPattern());
-						String asPrefix = getAsPrefix(mapping.getUrlPattern());
-						if (null != asPrefix) {
-							_facesFilterPrefix = asPrefix;
+                            String asPrefix = getAsPrefix(mapping.getUrlPattern());
 
-						}
-						String asSuffix = getAsSuffix(mapping.getUrlPattern());
-						if (null != asSuffix) {
-							_facesFilterSuffix = asSuffix;
+                            if (null != asPrefix) {
+                                facesServletPrefix = asPrefix;
+                            }
 
-						}
-					} else if (null != mapping.getServletName()
-							&& !"".equals(mapping.getServletName())) {
-						for (ServletMapping servletMapping : webappHandler
-								.getServletMappings()) {
-							if (mapping.getServletName().equals(
-									servletMapping.getServletName())) {
-								filterMappings.add(servletMapping
-										.getUrlPattern());
-								String asPrefix = getAsPrefix(servletMapping
-										.getUrlPattern());
-								if (null != asPrefix) {
-									_facesFilterPrefix = asPrefix;
+                            String asSuffix = getAsSuffix(mapping.getUrlPattern());
 
-								}
-								String asSuffix = getAsSuffix(servletMapping
-										.getUrlPattern());
-								if (null != asSuffix) {
-									_facesFilterSuffix = asSuffix;
+                            if (null != asSuffix) {
+                                facesServletSuffix = asSuffix;
+                            }
+                        }
+                    }
+                }
+            }
 
-								}
-							}
-						}
-					}
-				}
-			}
-			if (0 == filterMappings.size()) {
-				throw new ParsingException(
-						"No filter mapping set for a filter " + filterName);
-			}
+            // Find named filter configuration.
+            // Got filter, check it's mapping.
+            filterMappings = new ArrayList<String>();
 
-		} catch (IOException e) {
-			throw new ParsingException("Error read web application config", e);
-		} catch (ParserConfigurationException e) {
-			throw new ParsingException("SAX Parser configuration error", e);
-		} catch (SAXException e) {
-			throw new ParsingException(
-					"Error parsing XML for the web application config", e);
-		}
-	}
+            for (FilterMapping mapping : webappHandler.getFilterMappings()) {
+                if (mapping.getFilterName().equals(filterName)) {
+                    if ((null != mapping.getUrlPattern()) && !"".equals(mapping.getUrlPattern())) {
+                        filterMappings.add(mapping.getUrlPattern());
 
-	private String getAsSuffix(String urlPattern) {
-		String suffix = null;
-		if (urlPattern.startsWith("*")) {
-			suffix = urlPattern.substring(1);
-		}
-		return suffix;
-	}
+                        String asPrefix = getAsPrefix(mapping.getUrlPattern());
 
-	private String getAsPrefix(String urlPattern) {
-		String preffix = null;
-		if (urlPattern.endsWith("*")) {
-			int cut = urlPattern.endsWith("/*") ? 2 : 1;
-			preffix = urlPattern.substring(0, urlPattern.length() - cut);
-		}
-		return preffix;
-	}
+                        if (null != asPrefix) {
+                            facesFilterPrefix = asPrefix;
+                        }
 
-	public List<String> getFacesServletMappings() {
-		return facesServletMappings;
-	}
+                        String asSuffix = getAsSuffix(mapping.getUrlPattern());
 
-	/**
-	 * @return the facesFilterPrefix
-	 */
-	public String getFacesFilterPrefix() {
-		return _facesFilterPrefix;
-	}
+                        if (null != asSuffix) {
+                            facesFilterSuffix = asSuffix;
+                        }
+                    } else if ((null != mapping.getServletName()) && !"".equals(mapping.getServletName())) {
+                        for (ServletMapping servletMapping : webappHandler.getServletMappings()) {
+                            if (mapping.getServletName().equals(servletMapping.getServletName())) {
+                                filterMappings.add(servletMapping.getUrlPattern());
 
-	/**
-	 * @return the facesFilterSuffix
-	 */
-	public String getFacesFilterSuffix() {
-		return _facesFilterSuffix;
-	}
+                                String asPrefix = getAsPrefix(servletMapping.getUrlPattern());
 
-	/**
-	 * @return the facesServletPrefix
-	 */
-	public String getFacesServletPrefix() {
-		return _facesServletPrefix;
-	}
+                                if (null != asPrefix) {
+                                    facesFilterPrefix = asPrefix;
+                                }
 
-	/**
-	 * @return the facesServletSuffix
-	 */
-	public String getFacesServletSuffix() {
-		return _facesServletSuffix;
-	}
+                                String asSuffix = getAsSuffix(servletMapping.getUrlPattern());
 
-	public void init(ServletContext portletContext, String filterName)
-			throws ServletException {
-		InputStream inputStream = portletContext.getResourceAsStream(WEB_XML);
-		if (null != inputStream) {
-			try {
-				init(inputStream, filterName);
-			} catch (ParsingException e1) {
-				throw new ServletException(
-						"Error parse web application config", e1);
-			}
-			try {
-				inputStream.close();
-			} catch (IOException e) {
-				// Do nothing, ignore
-			}
+                                if (null != asSuffix) {
+                                    facesFilterSuffix = asSuffix;
+                                }
+                            }
+                        }
+                    }
+                }
+            }
 
-		}
-	}
+            if (0 == filterMappings.size()) {
+                throw new ParsingException("No filter mapping set for a filter " + filterName);
+            }
+        } catch (IOException e) {
+            throw new ParsingException("Error read web application config", e);
+        } catch (ParserConfigurationException e) {
+            throw new ParsingException("SAX Parser configuration error", e);
+        } catch (SAXException e) {
+            throw new ParsingException("Error parsing XML for the web application config", e);
+        }
+    }
+
+    private String getAsSuffix(String urlPattern) {
+        String suffix = null;
+
+        if (urlPattern.startsWith("*")) {
+            suffix = urlPattern.substring(1);
+        }
+
+        return suffix;
+    }
+
+    private String getAsPrefix(String urlPattern) {
+        String preffix = null;
+
+        if (urlPattern.endsWith("*")) {
+            int cut = urlPattern.endsWith("/*") ? 2 : 1;
+
+            preffix = urlPattern.substring(0, urlPattern.length() - cut);
+        }
+
+        return preffix;
+    }
+
+    public List<String> getFacesServletMappings() {
+        return facesServletMappings;
+    }
+
+    /**
+     * @return the facesFilterPrefix
+     */
+    public String getFacesFilterPrefix() {
+        return facesFilterPrefix;
+    }
+
+    /**
+     * @return the facesFilterSuffix
+     */
+    public String getFacesFilterSuffix() {
+        return facesFilterSuffix;
+    }
+
+    /**
+     * @return the facesServletPrefix
+     */
+    public String getFacesServletPrefix() {
+        return facesServletPrefix;
+    }
+
+    /**
+     * @return the facesServletSuffix
+     */
+    public String getFacesServletSuffix() {
+        return facesServletSuffix;
+    }
+
+    public void init(ServletContext portletContext, String filterName) throws ServletException {
+        InputStream inputStream = portletContext.getResourceAsStream(WEB_XML);
+
+        if (null != inputStream) {
+            try {
+                init(inputStream, filterName);
+            } catch (ParsingException e1) {
+                throw new ServletException("Error parse web application config", e1);
+            }
+
+            try {
+                inputStream.close();
+            } catch (IOException e) {
+
+                // Do nothing, ignore
+            }
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/WebappHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/WebappHandler.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/WebappHandler.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,12 +18,11 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
-package org.ajax4jsf.config;
 
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.List;
 
+
+package org.ajax4jsf.config;
+
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.InputSource;
@@ -31,232 +30,206 @@
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.DefaultHandler;
 
+import java.io.StringReader;
+
+import java.util.ArrayList;
+import java.util.List;
+
 /**
  * @author asmirnov
- * 
+ *
  */
 public class WebappHandler extends DefaultHandler {
+    static final String FILTER_CLASS_ELEMENT = "filter-class";
+    static final String FILTER_ELEMENT = "filter";
+    static final String FILTER_MAPPING_ELEMENT = "filter-mapping";
+    static final String FILTER_NAME_ELEMENT = "filter-name";
+    static final String SERVLET_CLASS_ELEMENT = "servlet-class";
+    static final String SERVLET_ELEMENT = "servlet";
+    static final String SERVLET_MAPPING_ELEMENT = "servlet-mapping";
+    static final String SERVLET_NAME_ELEMENT = "servlet-name";
+    static final String URL_PATTERN_ELEMENT = "url-pattern";
+    private List<ServletBean> servlets = new ArrayList<ServletBean>();
+    private List<ServletMapping> servletMappings = new ArrayList<ServletMapping>();
+    private List<FilterBean> filters = new ArrayList<FilterBean>();
+    private List<FilterMapping> filterMappings = new ArrayList<FilterMapping>();
+    private ServletBean facesServlet;
+    private XMLReader xmlReader;
 
-	static final String SERVLET_MAPPING_ELEMENT = "servlet-mapping";
+    public WebappHandler(XMLReader reader) {
+        this.xmlReader = reader;
+    }
 
-	static final String SERVLET_ELEMENT = "servlet";
+    public List<FilterBean> getFilters() {
+        return filters;
+    }
 
-	static final String SERVLET_NAME_ELEMENT = "servlet-name";
+    public List<FilterMapping> getFilterMappings() {
+        return filterMappings;
+    }
 
-	static final String SERVLET_CLASS_ELEMENT = "servlet-class";
+    public List<ServletBean> getServlets() {
+        return servlets;
+    }
 
-	static final String FILTER_MAPPING_ELEMENT = "filter-mapping";
+    public List<ServletMapping> getServletMappings() {
+        return servletMappings;
+    }
 
-	static final String FILTER_ELEMENT = "filter";
+    @Override
+    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
+        if (SERVLET_ELEMENT.equals(localName)) {
+            xmlReader.setContentHandler(new ServletHandler());
+        } else if (SERVLET_MAPPING_ELEMENT.equals(localName)) {
+            xmlReader.setContentHandler(new ServletMappingHandler());
+        } else if (FILTER_ELEMENT.equals(localName)) {
+            xmlReader.setContentHandler(new FilterHandler());
+        } else if (FILTER_MAPPING_ELEMENT.equals(localName)) {
+            xmlReader.setContentHandler(new FilterMappingHandler());
+        }
+    }
 
-	static final String FILTER_NAME_ELEMENT = "filter-name";
+    @Override
+    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
 
-	static final String FILTER_CLASS_ELEMENT = "filter-class";
+        // Do nothing, to avoid network requests for external DTD/Schema
+        return new InputSource(new StringReader(""));
+    }
 
-	private List<ServletBean> servlets = new ArrayList<ServletBean>();
-	
-	private List<FilterBean> filters = new ArrayList<FilterBean>();
+    /**
+     * @author asmirnov
+     *
+     */
+    public class FilterHandler extends WebappElementHandler {
+        private StringBuilder filterName = new StringBuilder();
+        private StringBuilder filterClass = new StringBuilder();
 
-	private List<ServletMapping> servletMappings = new ArrayList<ServletMapping>();
-	
-	private List<FilterMapping> filterMappings = new ArrayList<FilterMapping>();
+        public FilterHandler() {
+            super(WebappHandler.this);
+        }
 
-	private ServletBean facesServlet;
+        @Override
+        protected ContentHandler getNextHandler(String uri, String localName, Attributes attributes) {
 
-	private XMLReader xmlReader;
+            // TODO Auto-generated method stub
+            ContentHandler handler = null;
 
-	static final String URL_PATTERN_ELEMENT = "url-pattern";
+            if (FILTER_CLASS_ELEMENT.equals(localName)) {
+                handler = new StringContentHandler(getReader(), this, filterClass);
+            } else if (FILTER_NAME_ELEMENT.equals(localName)) {
+                handler = new StringContentHandler(getReader(), this, filterName);
+            }
 
+            return handler;
+        }
 
-	public WebappHandler(XMLReader reader) {
-		this.xmlReader = reader;
-	}
+        @Override
+        protected void endLastElement() {
+            filters.add(new FilterBean(filterName.toString().trim(), filterClass.toString().trim()));
+        }
+    }
 
-	public List<FilterBean> getFilters() {
-		return filters;
-	}
 
-	public List<FilterMapping> getFilterMappings() {
-		return filterMappings;
-	}
+    /**
+     * @author asmirnov
+     *
+     */
+    public class FilterMappingHandler extends WebappElementHandler {
+        private StringBuilder servletName = new StringBuilder();
+        private StringBuilder urlPattern = new StringBuilder();
+        private StringBuilder filterName = new StringBuilder();
 
-	public List<ServletBean> getServlets() {
-		return servlets;
-	}
+        public FilterMappingHandler() {
+            super(WebappHandler.this);
+        }
 
-	public List<ServletMapping> getServletMappings() {
-		return servletMappings;
-	}
+        @Override
+        protected ContentHandler getNextHandler(String uri, String localName, Attributes attributes) {
+            ContentHandler nextHandler = null;
 
-	@Override
-	public void startElement(String uri, String localName, String name,
-			Attributes attributes) throws SAXException {
-		if (SERVLET_ELEMENT.equals(localName)) {
-			xmlReader.setContentHandler(new ServletHandler());
-		} else if (SERVLET_MAPPING_ELEMENT.equals(localName)) {
-			xmlReader.setContentHandler(new ServletMappingHandler());
-		} else if (FILTER_ELEMENT.equals(localName)) {
-			xmlReader.setContentHandler(new FilterHandler());
-		} else if (FILTER_MAPPING_ELEMENT.equals(localName)) {
-			xmlReader.setContentHandler(new FilterMappingHandler());
-		}
-	}
+            if (SERVLET_NAME_ELEMENT.equals(localName)) {
+                nextHandler = new StringContentHandler(getReader(), this, servletName);
+            } else if (URL_PATTERN_ELEMENT.equals(localName)) {
+                nextHandler = new StringContentHandler(getReader(), this, urlPattern);
+            } else if (FILTER_NAME_ELEMENT.equals(localName)) {
+                nextHandler = new StringContentHandler(getReader(), this, filterName);
+            }
 
-	@Override
-    public InputSource resolveEntity(String publicId, String systemId) throws SAXException
-    {
-      // Do nothing, to avoid network requests for external DTD/Schema
-      return new InputSource(new StringReader(""));
-    }
-    
-    
-    private abstract class WebappElementHandler extends StateHandler {
-    	
-    	
-    	public WebappElementHandler(ContentHandler parentHandler) {
-			super(parentHandler);
-		}
+            return nextHandler;
+        }
 
-		@Override
-    	protected XMLReader getReader() {
-    		return xmlReader;
-    	}
+        @Override
+        protected void endLastElement() {
+            filterMappings.add(new FilterMapping(filterName.toString().trim(), servletName.toString().trim(),
+                    urlPattern.toString().trim()));
+        }
     }
 
 
-	final class ServletHandler extends WebappElementHandler {
+    final class ServletHandler extends WebappElementHandler {
+        private StringBuilder servletName = new StringBuilder();
+        private StringBuilder servletClass = new StringBuilder();
 
-		private StringBuilder servletName = new StringBuilder();
-		private StringBuilder servletClass = new StringBuilder();
+        public ServletHandler() {
+            super(WebappHandler.this);
+        }
 
-		public ServletHandler() {
-			super(WebappHandler.this);
-		}
+        @Override
+        protected ContentHandler getNextHandler(String uri, String localName, Attributes attributes) {
+            ContentHandler nextHandler = null;
 
-		@Override
-		protected ContentHandler getNextHandler(String uri, String localName,
-				Attributes attributes) {
-			ContentHandler nextHandler = null;
-			if (SERVLET_NAME_ELEMENT.equals(localName)) {
-				nextHandler = new StringContentHandler(getReader(), this,
-						servletName);
-			} else if (SERVLET_CLASS_ELEMENT.equals(localName)) {
-				nextHandler = new StringContentHandler(getReader(), this,
-						servletClass);
-			}
-			return nextHandler;
-		}
+            if (SERVLET_NAME_ELEMENT.equals(localName)) {
+                nextHandler = new StringContentHandler(getReader(), this, servletName);
+            } else if (SERVLET_CLASS_ELEMENT.equals(localName)) {
+                nextHandler = new StringContentHandler(getReader(), this, servletClass);
+            }
 
-		@Override
-		protected void endLastElement() {
-			servlets.add(new ServletBean(servletName.toString().trim(),
-					servletClass.toString().trim()));
-		}
-	}
+            return nextHandler;
+        }
 
-	final class ServletMappingHandler extends WebappElementHandler {
-	
-		private StringBuilder servletName = new StringBuilder();
-		private StringBuilder urlPattern = new StringBuilder();
-	
-		public ServletMappingHandler() {
-			super(WebappHandler.this);
-		}
-	
-		@Override
-		protected ContentHandler getNextHandler(String uri, String localName,
-				Attributes attributes) {
-			ContentHandler nextHandler = null;
-			if (SERVLET_NAME_ELEMENT.equals(localName)) {
-				nextHandler = new StringContentHandler(getReader(), this,
-						servletName);
-			} else if (URL_PATTERN_ELEMENT.equals(localName)) {
-				nextHandler = new StringContentHandler(getReader(), this,
-						urlPattern);
-			}
-			return nextHandler;
-		}
-	
-		@Override
-		protected void endLastElement() {
-			servletMappings.add(new ServletMapping(servletName.toString().trim(),
-					urlPattern.toString().trim()));
-		}
-	}
+        @Override
+        protected void endLastElement() {
+            servlets.add(new ServletBean(servletName.toString().trim(), servletClass.toString().trim()));
+        }
+    }
 
 
-	/**
-	 * @author asmirnov
-	 *
-	 */
-	public class FilterHandler extends WebappElementHandler {
-		
-		private StringBuilder filterName = new StringBuilder();
-		private StringBuilder filterClass = new StringBuilder();
+    final class ServletMappingHandler extends WebappElementHandler {
+        private StringBuilder servletName = new StringBuilder();
+        private StringBuilder urlPattern = new StringBuilder();
 
+        public ServletMappingHandler() {
+            super(WebappHandler.this);
+        }
 
-		public FilterHandler() {
-			super(WebappHandler.this);
-		}
-		
-		@Override
-		protected ContentHandler getNextHandler(String uri, String localName,
-				Attributes attributes) {
-			// TODO Auto-generated method stub
-			ContentHandler handler = null;
-			if(FILTER_CLASS_ELEMENT.equals(localName)){
-				handler = new StringContentHandler(getReader(),this,filterClass);
-			} else if (FILTER_NAME_ELEMENT.equals(localName)) {
-				handler = new StringContentHandler(getReader(),this,filterName);
-			}
-			return handler;
-		}
-		
-		@Override
-		protected void endLastElement() {
-			filters.add(new FilterBean(filterName.toString().trim(),filterClass.toString().trim()));
-		}
-	
-	}
+        @Override
+        protected ContentHandler getNextHandler(String uri, String localName, Attributes attributes) {
+            ContentHandler nextHandler = null;
 
+            if (SERVLET_NAME_ELEMENT.equals(localName)) {
+                nextHandler = new StringContentHandler(getReader(), this, servletName);
+            } else if (URL_PATTERN_ELEMENT.equals(localName)) {
+                nextHandler = new StringContentHandler(getReader(), this, urlPattern);
+            }
 
-	/**
-	 * @author asmirnov
-	 *
-	 */
-	public class FilterMappingHandler extends WebappElementHandler {
+            return nextHandler;
+        }
 
-		private StringBuilder servletName = new StringBuilder();
-		private StringBuilder urlPattern = new StringBuilder();
-		private StringBuilder filterName = new StringBuilder();
+        @Override
+        protected void endLastElement() {
+            servletMappings.add(new ServletMapping(servletName.toString().trim(), urlPattern.toString().trim()));
+        }
+    }
 
-		public FilterMappingHandler() {
-			super(WebappHandler.this);
-		}
-		
-		@Override
-		protected ContentHandler getNextHandler(String uri, String localName,
-				Attributes attributes) {
-			ContentHandler nextHandler = null;
-			if (SERVLET_NAME_ELEMENT.equals(localName)) {
-				nextHandler = new StringContentHandler(getReader(), this,
-						servletName);
-			} else if (URL_PATTERN_ELEMENT.equals(localName)) {
-				nextHandler = new StringContentHandler(getReader(), this,
-						urlPattern);
-			} else if (FILTER_NAME_ELEMENT.equals(localName)) {
-				nextHandler = new StringContentHandler(getReader(), this,
-						filterName);
-				
-			}
-			return nextHandler;
-		}
-		
-		@Override
-		protected void endLastElement() {
-			filterMappings.add(new FilterMapping(filterName.toString().trim(),servletName.toString().trim(),urlPattern.toString().trim()));
-		}
-	
-	}
 
+    private abstract class WebappElementHandler extends StateHandler {
+        public WebappElementHandler(ContentHandler parentHandler) {
+            super(parentHandler);
+        }
+
+        @Override
+        protected XMLReader getReader() {
+            return xmlReader;
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/AjaxContextImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/AjaxContextImpl.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/AjaxContextImpl.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,12 +19,27 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.context;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.application.AjaxViewHandler;
+import org.ajax4jsf.renderkit.AjaxContainerRenderer;
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
+import org.ajax4jsf.renderkit.RendererUtils;
+import org.ajax4jsf.renderkit.RendererUtils.HTML;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.StringWriter;
+
 import java.lang.reflect.Method;
+
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -43,542 +58,535 @@
 import javax.faces.context.ExternalContext;
 import javax.faces.context.FacesContext;
 import javax.faces.context.ResponseWriter;
-import javax.faces.event.AbortProcessingException;
 import javax.faces.render.RenderKit;
 import javax.faces.render.RenderKitFactory;
+
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.application.AjaxViewHandler;
-import org.ajax4jsf.renderkit.AjaxContainerRenderer;
-import org.ajax4jsf.renderkit.AjaxRendererUtils;
-import org.ajax4jsf.renderkit.RendererUtils;
-import org.ajax4jsf.renderkit.RendererUtils.HTML;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * This class incapsulated
- * 
+ *
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.7 $ $Date: 2007/02/08 19:07:16 $
- * 
+ *
  */
 public class AjaxContextImpl extends AjaxContext {
-	
-	public static final String SERVLET_ERROR_EXCEPTION_ATTRIBUTE = "javax.servlet.error.exception";
+    public static final String SERVLET_ERROR_EXCEPTION_ATTRIBUTE = "javax.servlet.error.exception";
+    private static final Logger LOG = RichfacesLogger.CONTEXT.getLogger();
+    Set<String> ajaxAreasToProcess = null;
+    Set<String> ajaxAreasToRender = new LinkedHashSet<String>();
+    Set<String> ajaxRenderedAreas = new LinkedHashSet<String>();
+    boolean ajaxRequest = false;
+    String ajaxSingleClientId = null;
+    Object oncomplete = null;
+    boolean selfRender = false;
+    String submittedRegionClientId = null;
+    ViewIdHolder viewIdHolder = null;
+    Integer viewSequence = new Integer(1);
+    Map<String, Object> responseDataMap = new HashMap<String, Object>();
+    Map<String, Object> commonAjaxParameters = new HashMap<String, Object>();
 
-	private static final Logger log = RichfacesLogger.CONTEXT.getLogger();
+    public void release() {
+        ajaxAreasToRender = new LinkedHashSet<String>();
+        ajaxAreasToProcess = null;
+        ajaxRenderedAreas = new LinkedHashSet<String>();
+        ajaxRequest = false;
+        selfRender = false;
+        viewSequence = new Integer(1);
+        submittedRegionClientId = null;
+        viewIdHolder = null;
+        responseDataMap = new HashMap<String, Object>();
+        commonAjaxParameters = new HashMap<String, Object>();
+    }
 
-	Set<String> ajaxAreasToRender = new LinkedHashSet<String>();
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.context.AjaxContext#decode(javax.faces.context.FacesContext)
+     */
+    @Override
+    public void decode(FacesContext context) {
+        ExternalContext externalContext = context.getExternalContext();
 
-	Set<String> ajaxAreasToProcess = null;
+        if (null == externalContext.getRequestMap().get(SERVLET_ERROR_EXCEPTION_ATTRIBUTE)) {
+            Map<String, String> requestParameterMap = externalContext.getRequestParameterMap();
+            String ajaxRegionId = requestParameterMap.get(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
 
-	Set<String> ajaxRenderedAreas = new LinkedHashSet<String>();
+            setSubmittedRegionClientId(ajaxRegionId);
+            setAjaxRequest(null != ajaxRegionId);
+            setAjaxSingleClientId(requestParameterMap.get(AjaxRendererUtils.AJAX_SINGLE_PARAMETER_NAME));
+        } else {
 
-	boolean ajaxRequest = false;
+            // Error page is always serviced as non-ajax.
+            setAjaxRequest(false);
+            setSubmittedRegionClientId(null);
+            setAjaxSingleClientId(null);
+        }
+    }
 
-	boolean selfRender = false;
+    /**
+     * @param context
+     * @throws javax.faces.event.AbortProcessingException
+     */
+    public void renderAjax(FacesContext context) throws FacesException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.RENDER_AJAX_REQUEST, getSubmittedRegionClientId()));
+        }
 
-	Integer viewSequence = new Integer(1);
+        try {
 
-	String submittedRegionClientId = null;
-	
-	String ajaxSingleClientId = null;
+            // Just in case...
+            setSelfRender(true);
+            setAjaxRequest(true);
 
+            // create response writer.
+            ExternalContext extContext = context.getExternalContext();
+            RenderKit renderKit = context.getRenderKit();
+            String encoding;
 
-	ViewIdHolder viewIdHolder = null;
+            // Depends if we talk about servlets, portlets, ...
+            if (extContext.getRequest() instanceof ServletRequest) {
+                ServletRequest request = (ServletRequest) extContext.getRequest();
+                ServletResponse response = (ServletResponse) extContext.getResponse();
 
-	Map<String, Object> responseDataMap = new HashMap<String, Object> ();
+                // Setup encoding and content type
+                String contentType = "text/xml";
 
-	Map<String, Object>  commonAjaxParameters = new HashMap<String, Object> ();
+                // get the encoding - must be setup by faces context or filter.
+                encoding = request.getCharacterEncoding();
 
-	Object oncomplete = null;
+                if (encoding == null) {
+                    encoding = "UTF-8";
+                }
 
+                response.setContentType(contentType + ";charset=" + encoding);
+            } else {
+                encoding = "UTF-8";
+            }
 
-	
-	public void release() {
+            PrintWriter servletWriter;
 
-		ajaxAreasToRender = new LinkedHashSet<String>();
-		
-		ajaxAreasToProcess = null;
+            servletWriter = getWriter(extContext);
 
-		ajaxRenderedAreas = new LinkedHashSet<String>();
+            ResponseWriter writer = renderKit.createResponseWriter(servletWriter, null, encoding);
 
-		ajaxRequest = false;
+            context.setResponseWriter(writer);
 
-		selfRender = false;
+            // make response
+            writer.startDocument();
+            encodeAjaxBegin(context);
+            context.getViewRoot().encodeAll(context);
+            saveViewState(context);
+            encodeAjaxEnd(context);
+            writer.endDocument();
+            writer.flush();
+            writer.close();
+            servletWriter.close();
 
-		viewSequence = new Integer(1);
+            // Save tree state.
+        } catch (IOException e) {
+            throw new FacesException(Messages.getMessage(Messages.RENDERING_AJAX_REGION_ERROR,
+                    getSubmittedRegionClientId()), e);
+        } finally {
+            context.responseComplete();
 
-		submittedRegionClientId = null;
+            // component.setRendererType(defaultRenderer);
+        }
+    }
 
-		viewIdHolder = null;
+    /**
+     * Encode declaration for AJAX response. Render &lt;html&gt;&lt;body&gt;
+     *
+     * @param context
+     * @throws IOException
+     */
+    public void encodeAjaxBegin(FacesContext context) throws IOException {
+        UIViewRoot viewRoot = context.getViewRoot();
 
-		responseDataMap = new HashMap<String, Object>();
+        // AjaxContainer ajax = (AjaxContainer) component;
+        ResponseWriter out = context.getResponseWriter();
 
-		commonAjaxParameters = new HashMap<String, Object>();
+        // DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
+        out.startElement(HTML.HTML_ELEMENT, viewRoot);
 
-	}
+        Locale locale = viewRoot.getLocale();
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.context.AjaxContext#decode(javax.faces.context.FacesContext)
-	 */
-	@Override
-	public void decode(FacesContext context) {
-		ExternalContext externalContext = context.getExternalContext();
-		if (null == externalContext.getRequestMap().get(
-				SERVLET_ERROR_EXCEPTION_ATTRIBUTE)) {
-			Map<String, String> requestParameterMap = externalContext
-					.getRequestParameterMap();
-			String ajaxRegionId = requestParameterMap
-					.get(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
-			setSubmittedRegionClientId(ajaxRegionId);
-			setAjaxRequest(null != ajaxRegionId);
-			setAjaxSingleClientId(requestParameterMap.get(AjaxRendererUtils.AJAX_SINGLE_PARAMETER_NAME));
-		} else {
-			// Error page is always serviced as non-ajax.
-			setAjaxRequest(false);
-			setSubmittedRegionClientId(null);
-			setAjaxSingleClientId(null);
-		}
-	}
-	
+        out.writeAttribute(HTML.LANG_ATTRIBUTE, locale.toString(), "lang");
+        out.startElement(HTML.BODY_ELEMENT, viewRoot);
+    }
 
-	/**
-	 * @param context
-	 * @throws AbortProcessingException
-	 */
-	public void renderAjax(FacesContext context) throws FacesException {
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.RENDER_AJAX_REQUEST,
-					getSubmittedRegionClientId()));
-		}
-		try {
-			// Just in case...
-			setSelfRender(true);
-			setAjaxRequest(true);
-			// create response writer.
-			ExternalContext extContext = context.getExternalContext();
-			RenderKit renderKit = context.getRenderKit();
-			String encoding;
-			// Depends if we talk about servlets, portlets, ...
-			if (extContext.getRequest() instanceof ServletRequest) {
-				ServletRequest request = (ServletRequest) extContext
-						.getRequest();
-				ServletResponse response = (ServletResponse) extContext
-						.getResponse();
-				// Setup encoding and content type
-				String contentType = "text/xml";
-				// get the encoding - must be setup by faces context or filter.
-				encoding = request.getCharacterEncoding();
-				if (encoding == null) {
-					encoding = "UTF-8";
-				}
-				response.setContentType(contentType + ";charset=" + encoding);
-			} else
-				encoding = "UTF-8";
+    /**
+     * End encoding of AJAX response. Render tag with included areas and close
+     * &lt;/body&gt;&lt;/html&gt;
+     *
+     * @param context
+     * @throws IOException
+     */
+    public void encodeAjaxEnd(FacesContext context) throws IOException {
 
-			PrintWriter servletWriter;
-				servletWriter = getWriter(extContext);
-			ResponseWriter writer = renderKit.createResponseWriter(
-					servletWriter, null, encoding);
-			context.setResponseWriter(writer);
-			// make response
-			writer.startDocument();
-			encodeAjaxBegin(context);
-			context.getViewRoot().encodeAll(context);
-			saveViewState(context);
-			encodeAjaxEnd(context);
-			writer.endDocument();
-			writer.flush();
-			writer.close();
-			servletWriter.close();
-			// Save tree state.
-		} catch (IOException e) {
-			throw new FacesException(Messages.getMessage(
-					Messages.RENDERING_AJAX_REGION_ERROR, getSubmittedRegionClientId()), e);
-		} finally {
-			context.responseComplete();
-			// component.setRendererType(defaultRenderer);
-		}
-	}
+        // AjaxContainer ajax = (AjaxContainer) component;
+        ResponseWriter out = context.getResponseWriter();
 
-	/**
-	 * Encode declaration for AJAX response. Render &lt;html&gt;&lt;body&gt;
-	 * 
-	 * @param context
-	 * @throws IOException
-	 */
-	public void encodeAjaxBegin(FacesContext context)
-			throws IOException {
-		UIViewRoot viewRoot = context.getViewRoot();
-		// AjaxContainer ajax = (AjaxContainer) component;
-		ResponseWriter out = context.getResponseWriter();
-		// DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
-		out.startElement(HTML.HTML_ELEMENT, viewRoot);
-		Locale locale = viewRoot.getLocale();
-		out.writeAttribute(HTML.lang_ATTRIBUTE, locale.toString(), "lang");
-		out.startElement(HTML.BODY_ELEMENT, viewRoot);
-	}
+        // DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
+        out.endElement(HTML.BODY_ELEMENT);
+        out.endElement(HTML.HTML_ELEMENT);
+    }
 
-	/**
-	 * End encoding of AJAX response. Render tag with included areas and close
-	 * &lt;/body&gt;&lt;/html&gt;
-	 * 
-	 * @param context
-	 * @throws IOException
-	 */
-	public void encodeAjaxEnd(FacesContext context)
-			throws IOException {
-		// AjaxContainer ajax = (AjaxContainer) component;
-		ResponseWriter out = context.getResponseWriter();
-		// DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
-		out.endElement(HTML.BODY_ELEMENT);
-		out.endElement(HTML.HTML_ELEMENT);
-	}
+    public void saveViewState(FacesContext context) throws IOException {
+        ResponseWriter writer = context.getResponseWriter();
+        StateManager stateManager = context.getApplication().getStateManager();
+        Object serializedView = stateManager.saveView(context);
 
-	public void saveViewState(FacesContext context) throws IOException {
-		ResponseWriter writer = context.getResponseWriter();
-		StateManager stateManager = context.getApplication().getStateManager();
-		Object serializedView = stateManager
-				.saveView(context);
-		if (null != serializedView && null != writer) {
-			StringWriter bufWriter = new StringWriter();
-			ResponseWriter tempWriter;
-			tempWriter = writer.cloneWithWriter(bufWriter);
-			context.setResponseWriter(tempWriter);
-			stateManager.writeState(context, serializedView);
-			tempWriter.flush();
-			if (bufWriter.getBuffer().length() > 0) {
-				context.getExternalContext().getRequestMap().put(
-						AjaxViewHandler.SERIALIZED_STATE_KEY,
-						bufWriter.toString());
-			}
-			context.setResponseWriter(writer);
-		}
-	}
+        if ((null != serializedView) && (null != writer)) {
+            StringWriter bufWriter = new StringWriter();
+            ResponseWriter tempWriter;
 
-	protected RenderKit getRenderKit(FacesContext context) {
-		RenderKit renderKit = context.getRenderKit();
-		if (null == renderKit) {
-			String renderKitId = context.getApplication().getViewHandler().calculateRenderKitId(context);
-			RenderKitFactory factory = (RenderKitFactory) FactoryFinder
-					.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
-			renderKit = factory.getRenderKit(context, renderKitId);
-		}
-		return renderKit;
-	}
+            tempWriter = writer.cloneWithWriter(bufWriter);
+            context.setResponseWriter(tempWriter);
+            stateManager.writeState(context, serializedView);
+            tempWriter.flush();
 
-	/**
-	 * @return Returns the ajaxRequest.
-	 */
-	public boolean isAjaxRequest() {
-		return ajaxRequest;
-	}
+            if (bufWriter.getBuffer().length() > 0) {
+                context.getExternalContext().getRequestMap().put(AjaxViewHandler.SERIALIZED_STATE_KEY,
+                        bufWriter.toString());
+            }
 
-	/**
-	 * @param ajaxRequest
-	 *            The ajaxRequest to set.
-	 */
-	public void setAjaxRequest(boolean ajaxRequest) {
-		this.ajaxRequest = ajaxRequest;
-	}
+            context.setResponseWriter(writer);
+        }
+    }
 
-	/**
-	 * @return Returns the ajaxAreasToRender.
-	 */
-	public Set<String> getAjaxAreasToRender() {
-		return this.ajaxAreasToRender;
-	}
+    protected RenderKit getRenderKit(FacesContext context) {
+        RenderKit renderKit = context.getRenderKit();
 
-	/**
-	 * @return the ajaxAreasToProcess
-	 */
-	@Override
-	public Set<String> getAjaxAreasToProcess() {
-		return ajaxAreasToProcess;
-	}
+        if (null == renderKit) {
+            String renderKitId = context.getApplication().getViewHandler().calculateRenderKitId(context);
+            RenderKitFactory factory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
 
-	/**
-	 * @param ajaxAreasToProcess the ajaxAreasToProcess to set
-	 */
-	@Override
-	public void setAjaxAreasToProcess(Set<String> ajaxAreasToProcess) {
-		this.ajaxAreasToProcess = ajaxAreasToProcess;
-	}
+            renderKit = factory.getRenderKit(context, renderKitId);
+        }
 
-	/**
-	 * Add affected regions's ID to ajaxView component.
-	 * 
-	 * @param component
-	 */
-	public void addRegionsFromComponent(UIComponent component) {
-		// First step - find parent ajax view
-		Set<String> ajaxRegions = AjaxRendererUtils.getAjaxAreas(component);
-		// if (ajaxRegions == null){
-		// FacesContext context = FacesContext.getCurrentInstance();
-		// ajaxRegions = AjaxRendererUtils.getAbsoluteId(context,component);
-		// }
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.INVOKE_AJAX_REGION_LISTENER,
-					component.getId()));
-		}
-		if (ajaxRegions != null) {
-			for (Iterator<String> iter = ajaxRegions.iterator(); iter.hasNext();) {
-				String id = iter.next().toString();
-				ajaxAreasToRender.add(convertId(component, id));
-			}
-		}
-		// Is that component limit to list ?
-		if(Boolean.TRUE.equals(component.getAttributes().get("limitToList"))){
-			setLimitToList(true);
-		}
-	}
+        return renderKit;
+    }
 
-	/** 
-	 * Add IDs of regions to process 
-	 * 
-	 * @see org.ajax4jsf.context.AjaxContext#addAreasToProcessFromComponent(javax.faces.component.UIComponent)
-	 */
-	@Override
-	public void addAreasToProcessFromComponent(FacesContext context, UIComponent component) {
-		RendererUtils rendererUtils = RendererUtils.getInstance();
-		
-		Set<String> areasToProcess = AjaxRendererUtils.getAjaxAreasToProcess(component);
-		if (areasToProcess != null) {
-			Set<String> convertedAreaIds = new HashSet<String>();
+    /**
+     * @return Returns the ajaxRequest.
+     */
+    public boolean isAjaxRequest() {
+        return ajaxRequest;
+    }
 
-			for (String areaId : areasToProcess) {
-				UIComponent areaComponent = rendererUtils.findComponentFor(component, areaId);
-				if (areaComponent != null) {
-					convertedAreaIds.add(areaComponent.getClientId(context));
-				} else {
-					convertedAreaIds.add(areaId);
-				}
-			}
-		
-			if (this.ajaxAreasToProcess == null) {
-				this.ajaxAreasToProcess = convertedAreaIds;
-			} else {
-				this.ajaxAreasToProcess.addAll(convertedAreaIds);
-			}
-		}
-	}
-	
-	public void addComponentToAjaxRender(UIComponent component) {
-		this.ajaxAreasToRender.add(AjaxRendererUtils.getAbsoluteId(component));
-	}
+    /**
+     * @param ajaxRequest
+     *            The ajaxRequest to set.
+     */
+    public void setAjaxRequest(boolean ajaxRequest) {
+        this.ajaxRequest = ajaxRequest;
+    }
 
-	public void addComponentToAjaxRender(UIComponent base, String id) {
-		this.ajaxAreasToRender.add(convertId(base, id));
-	}
+    /**
+     * @return Returns the ajaxAreasToRender.
+     */
+    public Set<String> getAjaxAreasToRender() {
+        return this.ajaxAreasToRender;
+    }
 
-	/**
-	 * Test for relative id of target components. Attempt convert to absolute.
-	 * For use as argument for
-	 * {@link RendererUtils#findComponentFor(UIComponent, String)}
-	 * 
-	 * @param component
-	 * @param id
-	 * @return
-	 */
-	private String convertId(UIComponent component, String id) {
-		if (id.charAt(0) == NamingContainer.SEPARATOR_CHAR) {
-			return id;
-		}
-		if (null == component) {
-			throw new NullPointerException(
-					"Base component for search re-rendered compnnent is null");
-		}
-		UIComponent target = RendererUtils.getInstance().findComponentFor(
-				component, id);
-		if (null != target) {
-			return AjaxRendererUtils.getAbsoluteId(target);
-		}
-		log.warn("Target component for id " + id + " not found");
-		return id;
-	}
+    /**
+     * @return the ajaxAreasToProcess
+     */
+    @Override
+    public Set<String> getAjaxAreasToProcess() {
+        return ajaxAreasToProcess;
+    }
 
-	/**
-	 * @return Returns the ajaxRenderedAreas.
-	 */
-	public Set<String> getAjaxRenderedAreas() {
-		return ajaxRenderedAreas;
-	}
+    /**
+     * @param ajaxAreasToProcess the ajaxAreasToProcess to set
+     */
+    @Override
+    public void setAjaxAreasToProcess(Set<String> ajaxAreasToProcess) {
+        this.ajaxAreasToProcess = ajaxAreasToProcess;
+    }
 
-	public void addRenderedArea(String id) {
-		ajaxRenderedAreas.add(id);
-	}
+    /**
+     * Add affected regions's ID to ajaxView component.
+     *
+     * @param component
+     */
+    public void addRegionsFromComponent(UIComponent component) {
 
-	public boolean removeRenderedArea(String id) {
-		return ajaxRenderedAreas.remove(id);
-	}
+        // First step - find parent ajax view
+        Set<String> ajaxRegions = AjaxRendererUtils.getAjaxAreas(component);
 
-	/**
-	 * @return Returns the submittedClientId.
-	 */
-	public String getSubmittedRegionClientId() {
-		return this.submittedRegionClientId;
-	}
+        // if (ajaxRegions == null){
+        // FacesContext context = FacesContext.getCurrentInstance();
+        // ajaxRegions = AjaxRendererUtils.getAbsoluteId(context,component);
+        // }
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.INVOKE_AJAX_REGION_LISTENER, component.getId()));
+        }
 
-	/**
-	 * @param submittedClientId
-	 *            The submittedClientId to set.
-	 */
-	@Override
-	public void setSubmittedRegionClientId(String submittedClientId) {
-		this.submittedRegionClientId = submittedClientId;
-	}
+        if (ajaxRegions != null) {
+            for (Iterator<String> iter = ajaxRegions.iterator(); iter.hasNext(); ) {
+                String id = iter.next().toString();
 
-	/**
-	 * @return the ajaxSingleClientId
-	 */
-	@Override
-	public String getAjaxSingleClientId() {
-		return ajaxSingleClientId;
-	}
+                ajaxAreasToRender.add(convertId(component, id));
+            }
+        }
 
-	/**
-	 * @param ajaxSingleClientId the ajaxSingleClientId to set
-	 */
-	@Override
-	public void setAjaxSingleClientId(String ajaxSingleClientId) {
-		this.ajaxSingleClientId = ajaxSingleClientId;
-	}
+        // Is that component limit to list ?
+        if (Boolean.TRUE.equals(component.getAttributes().get("limitToList"))) {
+            setLimitToList(true);
+        }
+    }
 
-	/**
-	 * @return Returns the selfRender.
-	 */
-	public boolean isSelfRender() {
-		return selfRender;
-	}
+    /**
+     * Add IDs of regions to process
+     *
+     * @see org.ajax4jsf.context.AjaxContext#addAreasToProcessFromComponent(javax.faces.component.UIComponent)
+     */
+    @Override
+    public void addAreasToProcessFromComponent(FacesContext context, UIComponent component) {
+        RendererUtils rendererUtils = RendererUtils.getInstance();
+        Set<String> areasToProcess = AjaxRendererUtils.getAjaxAreasToProcess(component);
 
-	/**
-	 * @param selfRender
-	 *            The selfRender to set.
-	 */
-	public void setSelfRender(boolean selfRender) {
-		this.selfRender = selfRender;
-	}
+        if (areasToProcess != null) {
+            Set<String> convertedAreaIds = new HashSet<String>();
 
-	/**
-	 * @return the vievIdHolder
-	 */
-	public ViewIdHolder getViewIdHolder() {
-		return viewIdHolder;
-	}
+            for (String areaId : areasToProcess) {
+                UIComponent areaComponent = rendererUtils.findComponentFor(component, areaId);
 
-	/**
-	 * @param viewIdHolder
-	 *            the vievIdHolder to set
-	 */
-	public void setViewIdHolder(ViewIdHolder viewIdHolder) {
-		this.viewIdHolder = viewIdHolder;
-	}
+                if (areaComponent != null) {
+                    convertedAreaIds.add(areaComponent.getClientId(context));
+                } else {
+                    convertedAreaIds.add(areaId);
+                }
+            }
 
-	/**
-	 * @return the responseData
-	 */
-	public Object getResponseData() {
-		return responseDataMap.get(RESPONSE_DATA_KEY);
-	}
+            if (this.ajaxAreasToProcess == null) {
+                this.ajaxAreasToProcess = convertedAreaIds;
+            } else {
+                this.ajaxAreasToProcess.addAll(convertedAreaIds);
+            }
+        }
+    }
 
-	/**
-	 * @param responseData
-	 *            the responseData to set
-	 */
-	public void setResponseData(Object responseData) {
-		this.responseDataMap.put(RESPONSE_DATA_KEY, responseData);
-	}
+    public void addComponentToAjaxRender(UIComponent component) {
+        this.ajaxAreasToRender.add(AjaxRendererUtils.getAbsoluteId(component));
+    }
 
-	/**
-	 * @return the responseDataMap
-	 */
-	public Map<String, Object> getResponseDataMap() {
-		return responseDataMap;
-	}
+    public void addComponentToAjaxRender(UIComponent base, String id) {
+        this.ajaxAreasToRender.add(convertId(base, id));
+    }
 
-	/**
-	 * Gives back the writer of a Response object.
-	 * 
-	 * @param extContext
-	 *            The external context.
-	 * @return The writer of the response.
-	 * @throws FacesException
-	 *             If the response object has no getWriter() method.
-	 */
-	protected PrintWriter getWriter(ExternalContext extContext)
-			throws FacesException {
-		PrintWriter writer = null;
-		Object response = extContext.getResponse();
-		try {
-			Method gW = response.getClass()
-					.getMethod("getWriter", new Class[0]);
-			writer = (PrintWriter) gW.invoke(response, new Object[0]);
-		} catch (Exception e) {
-			throw new FacesException(e);
-		}
-		return writer;
-	}
+    /**
+     * Test for relative id of target components. Attempt convert to absolute.
+     * For use as argument for
+     * {@link RendererUtils#findComponentFor(UIComponent, String)}
+     *
+     * @param component
+     * @param id
+     * @return
+     */
+    private String convertId(UIComponent component, String id) {
+        if (id.charAt(0) == NamingContainer.SEPARATOR_CHAR) {
+            return id;
+        }
 
+        if (null == component) {
+            throw new NullPointerException("Base component for search re-rendered compnnent is null");
+        }
 
-	public String getAjaxActionURL(FacesContext context) {
-		// Check arguments
-		if (null == context) {
-			throw new NullPointerException(
-					"Faces context for build AJAX Action URL is null");
-		}
-		UIViewRoot viewRoot = context.getViewRoot();
-		if (null == viewRoot) {
-			throw new NullPointerException(
-					"Faces view tree for build AJAX Action URL is null");
-		}
-		String viewId = viewRoot.getViewId();
-		if (null == viewId) {
-			throw new NullPointerException(
-					"View id for build AJAX Action URL is null");
-		}
-		if (!viewId.startsWith("/")) {
-			throw new IllegalArgumentException(
-					"Illegal view Id for build AJAX Action URL: " + viewId);
-		}
-		ViewHandler viewHandler = context.getApplication().getViewHandler();
-		String actionURL = viewHandler.getActionURL(context, viewId);
-		// HACK - check for a Jboss PortletBridge implementation. If present, append DirectLink attribute to url.
-		// TODO - how to detect portlet application ?
-		if (null != context.getExternalContext().getApplicationMap().get(
-				"org.jboss.portletbridge.application.PortletStateHolder")) {
-			// Mark Ajax action url as transparent with jsf-portlet bridge.
-			actionURL = actionURL
-					+ ((actionURL.lastIndexOf('?') > 0) ? "&" : "?")
-					+ "javax.portlet.faces.DirectLink=true";
+        UIComponent target = RendererUtils.getInstance().findComponentFor(component, id);
 
-		}
-		return context.getExternalContext().encodeActionURL(actionURL);
-	}
+        if (null != target) {
+            return AjaxRendererUtils.getAbsoluteId(target);
+        }
 
-	/**
-	 * @return the commonAjaxParameters
-	 */
-	public Map<String, Object> getCommonAjaxParameters() {
-		return commonAjaxParameters;
-	}
+        LOG.warn("Target component for id " + id + " not found");
 
-	/**
-	 * @return the oncomplete
-	 */
-	public Object getOncomplete() {
-		return oncomplete;
-	}
+        return id;
+    }
 
-	/**
-	 * @param oncomplete
-	 *            the oncomplete to set
-	 */
-	public void setOncomplete(Object oncomplete) {
-		this.oncomplete = oncomplete;
-	}
+    /**
+     * @return Returns the ajaxRenderedAreas.
+     */
+    public Set<String> getAjaxRenderedAreas() {
+        return ajaxRenderedAreas;
+    }
 
+    public void addRenderedArea(String id) {
+        ajaxRenderedAreas.add(id);
+    }
+
+    public boolean removeRenderedArea(String id) {
+        return ajaxRenderedAreas.remove(id);
+    }
+
+    /**
+     * @return Returns the submittedClientId.
+     */
+    public String getSubmittedRegionClientId() {
+        return this.submittedRegionClientId;
+    }
+
+    /**
+     * @param submittedClientId
+     *            The submittedClientId to set.
+     */
+    @Override
+    public void setSubmittedRegionClientId(String submittedClientId) {
+        this.submittedRegionClientId = submittedClientId;
+    }
+
+    /**
+     * @return the ajaxSingleClientId
+     */
+    @Override
+    public String getAjaxSingleClientId() {
+        return ajaxSingleClientId;
+    }
+
+    /**
+     * @param ajaxSingleClientId the ajaxSingleClientId to set
+     */
+    @Override
+    public void setAjaxSingleClientId(String ajaxSingleClientId) {
+        this.ajaxSingleClientId = ajaxSingleClientId;
+    }
+
+    /**
+     * @return Returns the selfRender.
+     */
+    public boolean isSelfRender() {
+        return selfRender;
+    }
+
+    /**
+     * @param selfRender
+     *            The selfRender to set.
+     */
+    public void setSelfRender(boolean selfRender) {
+        this.selfRender = selfRender;
+    }
+
+    /**
+     * @return the vievIdHolder
+     */
+    public ViewIdHolder getViewIdHolder() {
+        return viewIdHolder;
+    }
+
+    /**
+     * @param viewIdHolder
+     *            the vievIdHolder to set
+     */
+    public void setViewIdHolder(ViewIdHolder viewIdHolder) {
+        this.viewIdHolder = viewIdHolder;
+    }
+
+    /**
+     * @return the responseData
+     */
+    public Object getResponseData() {
+        return responseDataMap.get(RESPONSE_DATA_KEY);
+    }
+
+    /**
+     * @param responseData
+     *            the responseData to set
+     */
+    public void setResponseData(Object responseData) {
+        this.responseDataMap.put(RESPONSE_DATA_KEY, responseData);
+    }
+
+    /**
+     * @return the responseDataMap
+     */
+    public Map<String, Object> getResponseDataMap() {
+        return responseDataMap;
+    }
+
+    /**
+     * Gives back the writer of a Response object.
+     *
+     * @param extContext
+     *            The external context.
+     * @return The writer of the response.
+     * @throws FacesException
+     *             If the response object has no getWriter() method.
+     */
+    protected PrintWriter getWriter(ExternalContext extContext) throws FacesException {
+        PrintWriter writer = null;
+        Object response = extContext.getResponse();
+
+        try {
+            Method gW = response.getClass().getMethod("getWriter", new Class[0]);
+
+            writer = (PrintWriter) gW.invoke(response, new Object[0]);
+        } catch (Exception e) {
+            throw new FacesException(e);
+        }
+
+        return writer;
+    }
+
+    public String getAjaxActionURL(FacesContext context) {
+
+        // Check arguments
+        if (null == context) {
+            throw new NullPointerException("Faces context for build AJAX Action URL is null");
+        }
+
+        UIViewRoot viewRoot = context.getViewRoot();
+
+        if (null == viewRoot) {
+            throw new NullPointerException("Faces view tree for build AJAX Action URL is null");
+        }
+
+        String viewId = viewRoot.getViewId();
+
+        if (null == viewId) {
+            throw new NullPointerException("View id for build AJAX Action URL is null");
+        }
+
+        if (!viewId.startsWith("/")) {
+            throw new IllegalArgumentException("Illegal view Id for build AJAX Action URL: " + viewId);
+        }
+
+        ViewHandler viewHandler = context.getApplication().getViewHandler();
+        String actionURL = viewHandler.getActionURL(context, viewId);
+
+        // HACK - check for a Jboss PortletBridge implementation. If present, append DirectLink attribute to url.
+        // TODO - how to detect portlet application ?
+        if (null != context.getExternalContext().getApplicationMap().get(
+                "org.jboss.portletbridge.application.PortletStateHolder")) {
+
+            // Mark Ajax action url as transparent with jsf-portlet bridge.
+            actionURL = actionURL + ((actionURL.lastIndexOf('?') > 0) ? "&" : "?")
+                        + "javax.portlet.faces.DirectLink=true";
+        }
+
+        return context.getExternalContext().encodeActionURL(actionURL);
+    }
+
+    /**
+     * @return the commonAjaxParameters
+     */
+    public Map<String, Object> getCommonAjaxParameters() {
+        return commonAjaxParameters;
+    }
+
+    /**
+     * @return the oncomplete
+     */
+    public Object getOncomplete() {
+        return oncomplete;
+    }
+
+    /**
+     * @param oncomplete
+     *            the oncomplete to set
+     */
+    public void setOncomplete(Object oncomplete) {
+        this.oncomplete = oncomplete;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ComponentInvoker.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ComponentInvoker.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ComponentInvoker.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,13 +19,15 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.context;
 
+import org.ajax4jsf.component.AjaxViewRoot;
+
 import javax.faces.component.UIComponent;
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.component.AjaxViewRoot;
-
 /**
  * Interface for call lifecycle methods on component with known clientId
  * For JSF 1.2 implementation must use invokeOnComponent method, for JSF 1.1 use
@@ -35,23 +37,21 @@
  */
 public interface ComponentInvoker {
 
-	/**
-	 * Invoke method on active AjaxContainer component, or on viewRoot, if none.
-	 * @param viewRoot
-	 * @param context
-	 * @param callback
-	 */
-	public abstract void invokeOnRegionOrRoot(AjaxViewRoot viewRoot,
-			FacesContext context, InvokerCallback callback);
+    /**
+     * Invoke method on active AjaxContainer component, or on viewRoot, if none.
+     * @param viewRoot
+     * @param context
+     * @param callback
+     */
+    public abstract void invokeOnRegionOrRoot(AjaxViewRoot viewRoot, FacesContext context, InvokerCallback callback);
 
-	/**
-	 * Recursive call for all children for search component with same clientId as target region
-	 * @param viewRoot
-	 * @param context
-	 * @param callback
-	 * @param regionId
-	 */
-	public abstract boolean invokeOnComponent(UIComponent root,
-			FacesContext context, InvokerCallback callback, String regionId);
-
-}
\ No newline at end of file
+    /**
+     * Recursive call for all children for search component with same clientId as target region
+     * @param viewRoot
+     * @param context
+     * @param callback
+     * @param regionId
+     */
+    public abstract boolean invokeOnComponent(UIComponent root, FacesContext context, InvokerCallback callback,
+            String regionId);
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ContextInitParameters.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ContextInitParameters.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ContextInitParameters.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,98 +18,98 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.context;
 
 import javax.faces.FacesException;
-import javax.faces.application.ViewExpiredException;
 import javax.faces.context.ExternalContext;
 import javax.faces.context.FacesContext;
 
 /**
  * This class hold all methods for get application init parameters. Created for
  * single access point to all parameters - simplest for a documentation.
- * 
+ *
  * @author asmirnov
- * 
+ *
  */
-public class ContextInitParameters {
+public final class ContextInitParameters {
+    public static final String[] DATATABLE_USES_VIEW_LOCALE = {"org.richfaces.datatableUsesViewLocale"};
 
-	/**
-	 * 
-	 */
-	private ContextInitParameters() {
-		// this is a only static methods for a access to Web app Init
-		// parameters. Do not Instantiate !
-	}
+    /**
+     * This parameter define where {@link javax.faces.application.ViewExpiredException} should be handled.
+     * If is it equals "true" , framework should proparate exception to client-side.
+     */
+    public static final String HANDLE_VIEW_EXPIRED_ON_CLIENT = "org.ajax4jsf.handleViewExpiredOnClient";
 
-	/**
-	 * This parameter define where {@link ViewExpiredException} should be handled.
-	 * If is it equals "true" , framework should proparate exception to client-side. 
-	 */
-	public static final String HANDLE_VIEW_EXPIRED_ON_CLIENT="org.ajax4jsf.handleViewExpiredOnClient";
-	
-	public static final String[] DATATABLE_USES_VIEW_LOCALE = {"org.richfaces.datatableUsesViewLocale"};
-	
-	/**
-	 * Defines whether data table should use view root locale for sorting and filtering or the 
-	 * default platform one
-	 * 
-	 * @param context
-	 * @return
-	 */
-	public static boolean isDatatableUsesViewLocale(FacesContext context) {
-		return getBoolean(context, DATATABLE_USES_VIEW_LOCALE, false);
-	}
-	
-	static int getInteger(FacesContext context, String[] paramNames,
-			int defaulValue) {
-		String initParameter = getInitParameter(context,paramNames);
-		if (null == initParameter) {
-			return defaulValue;
-		} else {
-			try {
-				return Integer.parseInt(initParameter);
+    /**
+     *
+     */
+    private ContextInitParameters() {
 
-			} catch (NumberFormatException e) {
-				throw new FacesException("Context parameter " + paramNames
-						+ " must have integer value");
-			}
-		}
-	}
+        // this is a only static methods for a access to Web app Init
+        // parameters. Do not Instantiate !
+    }
 
-	static String getString(FacesContext context, String[] paramNames,
-			String defaulValue) {
-		String initParameter = getInitParameter(context,paramNames);
-		if (null == initParameter) {
-			return defaulValue;
-		} else {
-			return initParameter;
-		}
-	}
+    /**
+     * Defines whether data table should use view root locale for sorting and filtering or the
+     * default platform one
+     *
+     * @param context
+     * @return
+     */
+    public static boolean isDatatableUsesViewLocale(FacesContext context) {
+        return getBoolean(context, DATATABLE_USES_VIEW_LOCALE, false);
+    }
 
-	static boolean getBoolean(FacesContext context, String[] paramNames,
-			boolean defaulValue) {
-		String initParameter = getInitParameter(context,paramNames);
-		if (null == initParameter) {
-			return defaulValue;
-		} else if("true".equalsIgnoreCase(initParameter) || "yes".equalsIgnoreCase(initParameter)) {
-			return true;
-		} else if("false".equalsIgnoreCase(initParameter) || "no".equalsIgnoreCase(initParameter)) {
-			return false;
-		} else {
-			throw new FacesException("Illegal value ["+initParameter+"] for a init parameter +"+paramNames+", only logical values 'true' or 'false' is allowed");
-		}
-	}
+    static int getInteger(FacesContext context, String[] paramNames, int defaulValue) {
+        String initParameter = getInitParameter(context, paramNames);
 
-	static String getInitParameter(FacesContext context,
-			String[] paramNames) {
-		ExternalContext externalContext = context.getExternalContext();
-		String value = null;
-		for (int i = 0; i < paramNames.length && null == value; i++) {
-			value = externalContext.getInitParameter(paramNames[i]);
-		}
-		return value;
-	}
+        if (null == initParameter) {
+            return defaulValue;
+        } else {
+            try {
+                return Integer.parseInt(initParameter);
+            } catch (NumberFormatException e) {
+                throw new FacesException("Context parameter " + paramNames + " must have integer value");
+            }
+        }
+    }
 
+    static String getString(FacesContext context, String[] paramNames, String defaulValue) {
+        String initParameter = getInitParameter(context, paramNames);
 
+        if (null == initParameter) {
+            return defaulValue;
+        } else {
+            return initParameter;
+        }
+    }
+
+    static boolean getBoolean(FacesContext context, String[] paramNames, boolean defaulValue) {
+        String initParameter = getInitParameter(context, paramNames);
+
+        if (null == initParameter) {
+            return defaulValue;
+        } else if ("true".equalsIgnoreCase(initParameter) || "yes".equalsIgnoreCase(initParameter)) {
+            return true;
+        } else if ("false".equalsIgnoreCase(initParameter) || "no".equalsIgnoreCase(initParameter)) {
+            return false;
+        } else {
+            throw new FacesException("Illegal value [" + initParameter + "] for a init parameter +" + paramNames
+                                     + ", only logical values 'true' or 'false' is allowed");
+        }
+    }
+
+    static String getInitParameter(FacesContext context, String[] paramNames) {
+        ExternalContext externalContext = context.getExternalContext();
+        String value = null;
+
+        for (int i = 0; (i < paramNames.length) && (null == value); i++) {
+            value = externalContext.getInitParameter(paramNames[i]);
+        }
+
+        return value;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/InvokerCallback.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/InvokerCallback.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/InvokerCallback.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.context;
 
 import javax.faces.component.ContextCallback;
@@ -26,24 +28,23 @@
 import javax.faces.context.FacesContext;
 
 /**
- * Callback Interface 
+ * Callback Interface
  * for invoke lifecycle methods ( processDecodes, processValidators ... encodeEnd ).
  * @author shura
  *
  */
 public interface InvokerCallback extends ContextCallback {
-	
-	/**
-	 * Process method on given component.
-	 * @param context
-	 * @param component
-	 */
-	public void invokeContextCallback(FacesContext context, UIComponent component);
 
-	/**
-	 * Default processing on UIVewRoot
-	 * @param context
-	 */
-	public void invokeRoot(FacesContext context);
-	
+    /**
+     * Process method on given component.
+     * @param context
+     * @param component
+     */
+    public void invokeContextCallback(FacesContext context, UIComponent component);
+
+    /**
+     * Default processing on UIVewRoot
+     * @param context
+     */
+    public void invokeRoot(FacesContext context);
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ResponseWriterContentHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ResponseWriterContentHandler.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ResponseWriterContentHandler.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,113 +19,104 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.context;
 
-import javax.faces.FacesException;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
 
+package org.ajax4jsf.context;
+
 import org.ajax4jsf.renderkit.RendererUtils.HTML;
+
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
+
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.Locator;
 import org.xml.sax.SAXException;
 
+import javax.faces.FacesException;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
 class ResponseWriterContentHandler implements ContentHandler {
+    private String linkClass;
+    private Node node;
 
-	private String linkClass;
+    public ResponseWriterContentHandler(String linkClass) {
+        super();
 
-	private Node node;
+        try {
+            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
 
-	public ResponseWriterContentHandler(String linkClass) {
-		super();
-		
-		try {
-			Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
-			node = document.createElement("head");
-			document.appendChild(node);
-		} catch (ParserConfigurationException e) {
-			throw new FacesException(e.getLocalizedMessage(), e);
-		}
-		
-		this.linkClass = linkClass;
-	}
+            node = document.createElement("head");
+            document.appendChild(node);
+        } catch (ParserConfigurationException e) {
+            throw new FacesException(e.getLocalizedMessage(), e);
+        }
 
-	public void characters(char[] ch, int start, int length)
-			throws SAXException {
+        this.linkClass = linkClass;
+    }
 
-		node.appendChild(node.getOwnerDocument().createTextNode(new String(ch, start, length)));
-	}
+    public void characters(char[] ch, int start, int length) throws SAXException {
+        node.appendChild(node.getOwnerDocument().createTextNode(new String(ch, start, length)));
+    }
 
-	public void endDocument() throws SAXException {
-	}
+    public void endDocument() throws SAXException {}
 
-	public void endElement(String uri, String localName, String name)
-			throws SAXException {
-		
-		node = node.getParentNode();
-	}
+    public void endElement(String uri, String localName, String name) throws SAXException {
+        node = node.getParentNode();
+    }
 
-	public void endPrefixMapping(String prefix) throws SAXException {
-		throw new UnsupportedOperationException();
-	}
+    public void endPrefixMapping(String prefix) throws SAXException {
+        throw new UnsupportedOperationException();
+    }
 
-	public void ignorableWhitespace(char[] ch, int start, int length)
-			throws SAXException {
-	}
+    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
 
-	public void processingInstruction(String target, String data)
-			throws SAXException {
-		throw new UnsupportedOperationException();
-	}
+    public void processingInstruction(String target, String data) throws SAXException {
+        throw new UnsupportedOperationException();
+    }
 
-	public void setDocumentLocator(Locator locator) {
-		throw new UnsupportedOperationException();
-	}
+    public void setDocumentLocator(Locator locator) {
+        throw new UnsupportedOperationException();
+    }
 
-	public void skippedEntity(String name) throws SAXException {
-		throw new UnsupportedOperationException();
-	}
+    public void skippedEntity(String name) throws SAXException {
+        throw new UnsupportedOperationException();
+    }
 
-	public void startDocument() throws SAXException {
-	}
+    public void startDocument() throws SAXException {}
 
-	public void startElement(String uri, String localName,
-			String name, Attributes atts) throws SAXException {
+    public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException {
+        Document document = node.getOwnerDocument();
+        Element element = document.createElement(localName);
+        int length = atts.getLength();
 
-		Document document = node.getOwnerDocument();
-		Element element = document.createElement(localName);
+        for (int i = 0; i < length; i++) {
+            element.setAttribute(atts.getLocalName(i), atts.getValue(i));
+        }
 
-		int length = atts.getLength();
+        if (HTML.LINK_ELEMENT.equals(localName)) {
+            element.setAttribute(HTML.CLASS_ATTRIBUTE, linkClass);
+        }
 
-		for (int i = 0; i < length; i++) {
-			element.setAttribute(atts.getLocalName(i), atts.getValue(i));
-		}
-		
-		if (HTML.LINK_ELEMENT.equals(localName)) {
-			element.setAttribute(HTML.class_ATTRIBUTE, linkClass);
-		}
+        node = node.appendChild(element);
+    }
 
-		node = node.appendChild(element);
-	}
+    public void startPrefixMapping(String prefix, String uri) throws SAXException {
+        throw new UnsupportedOperationException();
+    }
 
-	public void startPrefixMapping(String prefix, String uri)
-			throws SAXException {
-		throw new UnsupportedOperationException();
-	}
+    public Node[] getNodes() {
+        NodeList childNodes = node.getChildNodes();
+        Node[] list = new Node[childNodes.getLength()];
 
-	public Node[] getNodes() {
-		NodeList childNodes = node.getChildNodes();
-		Node[] list = new Node[childNodes.getLength()];
-		for (int i = 0; i < list.length; i++) {
-			list[i] = childNodes.item(i);
-		}
-		
-		return list;
-	}
-	
-}
\ No newline at end of file
+        for (int i = 0; i < list.length; i++) {
+            list[i] = childNodes.item(i);
+        }
+
+        return list;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ViewResources.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ViewResources.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/ViewResources.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,575 +19,577 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.context;
 
-
 /**
  * @author Nick Belaevski
  */
+
 //TODO remove - https://jira.jboss.org/jira/browse/RFPL-42
 public class ViewResources {
 
-//	private static final String INIT_PARAMETER_PREFIX = "_init_parameter_";
-//	private static final Object NULL = new Object();
+//  private static final String INIT_PARAMETER_PREFIX = "_init_parameter_";
+//  private static final Object NULL = new Object();
 //
-//	private String scriptStrategy;
+//  private String scriptStrategy;
 //
-//	private String styleStrategy;
+//  private String styleStrategy;
 //
-//	private boolean useStdControlsSkinning;
+//  private boolean useStdControlsSkinning;
 //
-//	private boolean useStdControlsSkinningClasses;
+//  private boolean useStdControlsSkinningClasses;
 //
-//	private HeadResponseWriter componentWriter;
+//  private HeadResponseWriter componentWriter;
 //
-//	private HeadResponseWriter userWriter;
+//  private HeadResponseWriter userWriter;
 //
-//	private RenderKit renderKit;
+//  private RenderKit renderKit;
 //
-//	private Node[] headNodes = null;
+//  private Node[] headNodes = null;
 //
-//	private static final String EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY = ViewResources.class.getName() + "EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY";
-//	
-//	private static final InternetResource EXTENDED_SKINNING_ON_RESOURCE = new InternetResourceBase() {
-//		
-//		private final String RESOURCE_KEY = this.getClass().getName();
-//		
-//		@Override
-//		public void encode(FacesContext context, Object data)
-//				throws IOException {
+//  private static final String EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY = ViewResources.class.getName() + "EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY";
+//  
+//  private static final InternetResource EXTENDED_SKINNING_ON_RESOURCE = new InternetResourceBase() {
+//      
+//      private final String RESOURCE_KEY = this.getClass().getName();
+//      
+//      @Override
+//      public void encode(FacesContext context, Object data)
+//              throws IOException {
 //
-//			encode(context, data, Collections.EMPTY_MAP);
-//		}
-//		
-//		@Override
-//		public void encode(FacesContext context, Object data,
-//				Map<String, Object> attributes) throws IOException {
+//          encode(context, data, Collections.EMPTY_MAP);
+//      }
+//      
+//      @Override
+//      public void encode(FacesContext context, Object data,
+//              Map<String, Object> attributes) throws IOException {
 //
-//			Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
-//			if (requestMap.get(RESOURCE_KEY) == null) {
-//				ResponseWriter writer = context.getResponseWriter();
-//				writer.startElement(HTML.SCRIPT_ELEM, null);
-//				
-//				if (!attributes.containsKey(HTML.TYPE_ATTR)) {
-//					writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
-//				}
-//				
-//				for (Map.Entry<String, Object> entry : attributes.entrySet()) {
-//					writer.writeAttribute(entry.getKey(), entry.getValue(), null);
-//				}
-//				
-//				writer.writeText("window.RICH_FACES_EXTENDED_SKINNING_ON=true;", null);
-//				
-//				writer.endElement(HTML.SCRIPT_ELEM);
+//          Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
+//          if (requestMap.get(RESOURCE_KEY) == null) {
+//              ResponseWriter writer = context.getResponseWriter();
+//              writer.startElement(HTML.SCRIPT_ELEM, null);
+//              
+//              if (!attributes.containsKey(HTML.TYPE_ATTR)) {
+//                  writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", null);
+//              }
+//              
+//              for (Map.Entry<String, Object> entry : attributes.entrySet()) {
+//                  writer.writeAttribute(entry.getKey(), entry.getValue(), null);
+//              }
+//              
+//              writer.writeText("window.RICH_FACES_EXTENDED_SKINNING_ON=true;", null);
+//              
+//              writer.endElement(HTML.SCRIPT_ELEM);
 //
-//				requestMap.put(RESOURCE_KEY, Boolean.TRUE);
-//			}
-//		}
-//	};
-//	
-//	public void setScriptStrategy(String scriptsStrategy) {
-//		this.scriptStrategy = scriptsStrategy;
-//	}
+//              requestMap.put(RESOURCE_KEY, Boolean.TRUE);
+//          }
+//      }
+//  };
+//  
+//  public void setScriptStrategy(String scriptsStrategy) {
+//      this.scriptStrategy = scriptsStrategy;
+//  }
 //
-//	public void setStyleStrategy(String stylesStrategy) {
-//		this.styleStrategy = stylesStrategy;
-//	}
+//  public void setStyleStrategy(String stylesStrategy) {
+//      this.styleStrategy = stylesStrategy;
+//  }
 //
-//	public void setUseStdControlsSkinning(boolean stdControlsSkinning) {
-//		this.useStdControlsSkinning = stdControlsSkinning;
-//	}
+//  public void setUseStdControlsSkinning(boolean stdControlsSkinning) {
+//      this.useStdControlsSkinning = stdControlsSkinning;
+//  }
 //
-//	public void setUseStdControlsSkinningClasses(boolean stdControlsSkinningClasses) {
-//		this.useStdControlsSkinningClasses = stdControlsSkinningClasses;
-//	}
+//  public void setUseStdControlsSkinningClasses(boolean stdControlsSkinningClasses) {
+//      this.useStdControlsSkinningClasses = stdControlsSkinningClasses;
+//  }
 //
-//	public void setExtendedSkinningAllowed(boolean extendedSkinningAllowed) {
-//		this.extendedSkinningAllowed = extendedSkinningAllowed;
-//	}
+//  public void setExtendedSkinningAllowed(boolean extendedSkinningAllowed) {
+//      this.extendedSkinningAllowed = extendedSkinningAllowed;
+//  }
 //
-//	private static String SCRIPT = HTML.SCRIPT_ELEM;
-//	private static String SCRIPT_UC = SCRIPT.toUpperCase(Locale.US);
-//	
-//	private static String SRC = HTML.src_ATTRIBUTE;
-//	private static String SRC_UC = SRC.toUpperCase(Locale.US);
+//  private static String SCRIPT = HTML.SCRIPT_ELEM;
+//  private static String SCRIPT_UC = SCRIPT.toUpperCase(Locale.US);
+//  
+//  private static String SRC = HTML.SRC_ATTRIBUTE;
+//  private static String SRC_UC = SRC.toUpperCase(Locale.US);
 //
-//	private void mergeHeadResourceNode(List<Node> nodes, Set<String> renderedScripts, Node node) {
-//		boolean shouldAdd = true;
-//		
-//		String nodeName = node.getNodeName();
-//		if (SCRIPT.equals(nodeName) || SCRIPT_UC.equals(nodeName)) {
-//			if (node.getFirstChild() == null) {
-//				//no text content etc.
-//			
-//				NamedNodeMap attributes = node.getAttributes();
-//				if (attributes != null) {
-//					Node item = attributes.getNamedItem(SRC);
-//					if (item == null) {
-//						attributes.getNamedItem(SRC_UC);
-//					}
-//					
-//					if (item != null) {
-//						String src = item.getNodeValue();
-//						if (src != null) {
-//							if (renderedScripts.contains(src)) {
-//								shouldAdd = false;
-//							} else {
-//								renderedScripts.add(src);
-//							}
-//						}
-//					}
-//				}
-//			}
-//		}
-//		
-//		if (shouldAdd) {
-//			nodes.add(node);
-//		}
-//	}
-//	
-//	private Node[] mergeHeadResourceNodes() {
-//		List<Node> result = new ArrayList<Node>();
-//	
-//		Set<String> scripts = new HashSet<String>();
-//		
-//		for (Node node : componentWriter.getNodes()) {
-//			mergeHeadResourceNode(result, scripts, node);
-//		}
-//		
-//		for (Node node : userWriter.getNodes()) {
-//			mergeHeadResourceNode(result, scripts, node);
-//		}
-//		
-//		return result.toArray(new Node[result.size()]);
-//	}
-//	
-//	public Node[] getHeadEvents() {
-//		if (headNodes == null) {
-//			headNodes = mergeHeadResourceNodes();
-//		}
-//		
-//		return headNodes;
-//	}
+//  private void mergeHeadResourceNode(List<Node> nodes, Set<String> renderedScripts, Node node) {
+//      boolean shouldAdd = true;
+//      
+//      String nodeName = node.getNodeName();
+//      if (SCRIPT.equals(nodeName) || SCRIPT_UC.equals(nodeName)) {
+//          if (node.getFirstChild() == null) {
+//              //no text content etc.
+//          
+//              NamedNodeMap attributes = node.getAttributes();
+//              if (attributes != null) {
+//                  Node item = attributes.getNamedItem(SRC);
+//                  if (item == null) {
+//                      attributes.getNamedItem(SRC_UC);
+//                  }
+//                  
+//                  if (item != null) {
+//                      String src = item.getNodeValue();
+//                      if (src != null) {
+//                          if (renderedScripts.contains(src)) {
+//                              shouldAdd = false;
+//                          } else {
+//                              renderedScripts.add(src);
+//                          }
+//                      }
+//                  }
+//              }
+//          }
+//      }
+//      
+//      if (shouldAdd) {
+//          nodes.add(node);
+//      }
+//  }
+//  
+//  private Node[] mergeHeadResourceNodes() {
+//      List<Node> result = new ArrayList<Node>();
+//  
+//      Set<String> scripts = new HashSet<String>();
+//      
+//      for (Node node : componentWriter.getNodes()) {
+//          mergeHeadResourceNode(result, scripts, node);
+//      }
+//      
+//      for (Node node : userWriter.getNodes()) {
+//          mergeHeadResourceNode(result, scripts, node);
+//      }
+//      
+//      return result.toArray(new Node[result.size()]);
+//  }
+//  
+//  public Node[] getHeadEvents() {
+//      if (headNodes == null) {
+//          headNodes = mergeHeadResourceNodes();
+//      }
+//      
+//      return headNodes;
+//  }
 //
-//	private static final Log log = LogFactory.getLog(ViewResources.class);
+//  private static final Log log = LogFactory.getLog(ViewResources.class);
 //
-//	//todo
+//  //todo
 //
-//	private static final Map<String, Object> EXTENDED_SKINNING = new HashMap<String, Object>(1);
+//  private static final Map<String, Object> EXTENDED_SKINNING = new HashMap<String, Object>(1);
 //
-//	static {
-//		EXTENDED_SKINNING.put(HTML.media_ATTRIBUTE, "rich-extended-skinning");
-//	}
+//  static {
+//      EXTENDED_SKINNING.put(HTML.MEDIA_ATTRIBUTE, "rich-extended-skinning");
+//  }
 //
-//	public static final String SKINNING_STYLES_PATH = "/org/richfaces/renderkit/html/css/";
+//  public static final String SKINNING_STYLES_PATH = "/org/richfaces/renderkit/html/css/";
 //
-//	public static final String QUEUE_SCRIPT_RESOURCE = "org.ajax4jsf.renderkit.html.scripts.QueueScript";
+//  public static final String QUEUE_SCRIPT_RESOURCE = "org.ajax4jsf.renderkit.html.scripts.QueueScript";
 //
-//	private boolean extendedSkinningAllowed;
+//  private boolean extendedSkinningAllowed;
 //
-//	private boolean processScripts;
+//  private boolean processScripts;
 //
-//	private boolean processStyles;
+//  private boolean processStyles;
 //
-//	private boolean useSkinning;
+//  private boolean useSkinning;
 //
-//	private InternetResourceBuilder resourceBuilder;
+//  private InternetResourceBuilder resourceBuilder;
 //
-//	private boolean ajaxRequest;
+//  private boolean ajaxRequest;
 //
-//	public static final String COMPONENT_RESOURCE_LINK_CLASS = "component";
+//  public static final String COMPONENT_RESOURCE_LINK_CLASS = "component";
 //
-//	public static final String USER_RESOURCE_LINK_CLASS = "user";
+//  public static final String USER_RESOURCE_LINK_CLASS = "user";
 //
-//	class HeadResponseWriter extends SAXResponseWriter {
+//  class HeadResponseWriter extends SAXResponseWriter {
 //
-//		public Node[] getNodes() {
-//			return ((ResponseWriterContentHandler) getXmlConsumer()).getNodes();
-//		}
+//      public Node[] getNodes() {
+//          return ((ResponseWriterContentHandler) getXmlConsumer()).getNodes();
+//      }
 //
-//		public HeadResponseWriter(String linkClass) {
-//			super(new ResponseWriterContentHandler(linkClass));
+//      public HeadResponseWriter(String linkClass) {
+//          super(new ResponseWriterContentHandler(linkClass));
 //
-//		}
-//	}
+//      }
+//  }
 //
-//	private void encodeResources(FacesContext context, ResourceRenderer renderer, Set<String> set) throws IOException {
+//  private void encodeResources(FacesContext context, ResourceRenderer renderer, Set<String> set) throws IOException {
 //
-//		if (set != null) {
-//			URIInternetResource resourceImpl = new URIInternetResource();
+//      if (set != null) {
+//          URIInternetResource resourceImpl = new URIInternetResource();
 //
-//			for (String uri : set) {
-//				resourceImpl.setUri(uri);
-//				renderer.encode(resourceImpl, context, null);
-//			}
-//		}
-//	}
+//          for (String uri : set) {
+//              resourceImpl.setUri(uri);
+//              renderer.encode(resourceImpl, context, null);
+//          }
+//      }
+//  }
 //
-//	private boolean encodeSkinningResources(FacesContext context, InternetResourceBuilder resourceBuilder) throws IOException, FacesException {
-//		String resourceSuffix = null;
+//  private boolean encodeSkinningResources(FacesContext context, InternetResourceBuilder resourceBuilder) throws IOException, FacesException {
+//      String resourceSuffix = null;
 //
-//		if (useStdControlsSkinning) {
-//			if (useStdControlsSkinningClasses) {
-//				resourceSuffix = "_both.xcss";
-//			} else {
-//				resourceSuffix = ".xcss";
-//			}
-//		} else {
-//			if (useStdControlsSkinningClasses) {
-//				resourceSuffix = "_classes.xcss";
-//			} else {
-//				//no resources
-//			}
-//		}
+//      if (useStdControlsSkinning) {
+//          if (useStdControlsSkinningClasses) {
+//              resourceSuffix = "_both.xcss";
+//          } else {
+//              resourceSuffix = ".xcss";
+//          }
+//      } else {
+//          if (useStdControlsSkinningClasses) {
+//              resourceSuffix = "_classes.xcss";
+//          } else {
+//              //no resources
+//          }
+//      }
 //
-//		if (resourceSuffix != null) {
-//			resourceBuilder.createResource(
-//					this, SKINNING_STYLES_PATH.concat("basic").concat(resourceSuffix)).encode(context, null);
+//      if (resourceSuffix != null) {
+//          resourceBuilder.createResource(
+//                  this, SKINNING_STYLES_PATH.concat("basic").concat(resourceSuffix)).encode(context, null);
 //
-//			if (extendedSkinningAllowed) {
-//				resourceBuilder.createResource(
-//						this, SKINNING_STYLES_PATH.concat("extended").concat(resourceSuffix)).encode(context, null, EXTENDED_SKINNING);
-//			}
+//          if (extendedSkinningAllowed) {
+//              resourceBuilder.createResource(
+//                      this, SKINNING_STYLES_PATH.concat("extended").concat(resourceSuffix)).encode(context, null, EXTENDED_SKINNING);
+//          }
 //
-//			return true;
-//		}
+//          return true;
+//      }
 //
-//		return false;
-//	}
+//      return false;
+//  }
 //
-//	/**
-//	 * Find renderer for given component.
-//	 * 
-//	 * @param context
-//	 * @param comp
-//	 * @param renderKit
-//	 * @return
-//	 */
-//	private Renderer getRenderer(FacesContext context, UIComponent comp) {
+//  /**
+//   * Find renderer for given component.
+//   * 
+//   * @param context
+//   * @param comp
+//   * @param renderKit
+//   * @return
+//   */
+//  private Renderer getRenderer(FacesContext context, UIComponent comp) {
 //
-//		String rendererType = comp.getRendererType();
-//		if (rendererType != null) {
-//			return (renderKit.getRenderer(comp.getFamily(), rendererType));
-//		} else {
-//			return (null);
-//		}
-//	}
+//      String rendererType = comp.getRendererType();
+//      if (rendererType != null) {
+//          return (renderKit.getRenderer(comp.getFamily(), rendererType));
+//      } else {
+//          return (null);
+//      }
+//  }
 //
-//	public void processHeadResources(FacesContext context) throws FacesException {
+//  public void processHeadResources(FacesContext context) throws FacesException {
 //
-//		RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder
-//		.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
-//		renderKit = rkFactory.getRenderKit(context, context
-//				.getViewRoot().getRenderKitId());
+//      RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder
+//      .getFactory(FactoryFinder.RENDER_KIT_FACTORY);
+//      renderKit = rkFactory.getRenderKit(context, context
+//              .getViewRoot().getRenderKitId());
 //
-//		boolean scriptsOff = false;
-//		
-//		processStyles = true;
-//		processScripts = true;
-//		useSkinning = false;
+//      boolean scriptsOff = false;
+//      
+//      processStyles = true;
+//      processScripts = true;
+//      useSkinning = false;
 //
-//		ajaxRequest = AjaxContext.getCurrentInstance(context).isAjaxRequest(context);
+//      ajaxRequest = AjaxContext.getCurrentInstance(context).isAjaxRequest(context);
 //
-//		if (log.isDebugEnabled()) {
-//			log
-//			.debug("Process component tree for collect used scripts and styles");
-//		}
+//      if (log.isDebugEnabled()) {
+//          log
+//          .debug("Process component tree for collect used scripts and styles");
+//      }
 //
-//		String skinStyleSheetUri = null;
-//		String skinExtendedStyleSheetUri = null;
+//      String skinStyleSheetUri = null;
+//      String skinExtendedStyleSheetUri = null;
 //
-//		Skin skin = null;
-//		try {
-//			skin = SkinFactory.getInstance().getSkin(context);
-//			// For a "NULL" skin, do not collect components stylesheets
-//			if ("false".equals(skin.getParameter(context,
-//					Skin.loadStyleSheets))) {
-//				processStyles = false;
-//			}
-//			// Set default style sheet for current skin.
-//			skinStyleSheetUri = (String) skin.getParameter(context,
-//					Skin.generalStyleSheet);
-//			// Set default style sheet for current skin.
-//			skinExtendedStyleSheetUri = (String) skin.getParameter(context,
-//					Skin.extendedStyleSheet);
-//		} catch (SkinNotFoundException e) {
-//			if (log.isWarnEnabled()) {
-//				log.warn("Current Skin is not found", e);
-//			}
-//		}
+//      Skin skin = null;
+//      try {
+//          skin = SkinFactory.getInstance().getSkin(context);
+//          // For a "NULL" skin, do not collect components stylesheets
+//          if ("false".equals(skin.getParameter(context,
+//                  Skin.LOAD_STYLE_SHEETS))) {
+//              processStyles = false;
+//          }
+//          // Set default style sheet for current skin.
+//          skinStyleSheetUri = (String) skin.getParameter(context,
+//                  Skin.GENERAL_STYLE_SHEET);
+//          // Set default style sheet for current skin.
+//          skinExtendedStyleSheetUri = (String) skin.getParameter(context,
+//                  Skin.EXTENDED_STYLE_SHEET);
+//      } catch (SkinNotFoundException e) {
+//          if (log.isWarnEnabled()) {
+//              log.warn("Current Skin is not found", e);
+//          }
+//      }
 //
-//		resourceBuilder = InternetResourceBuilder.getInstance();
+//      resourceBuilder = InternetResourceBuilder.getInstance();
 //
-//		ResponseWriter oldResponseWriter = context.getResponseWriter();
+//      ResponseWriter oldResponseWriter = context.getResponseWriter();
 //
-//		componentWriter = new HeadResponseWriter("component");
-//		userWriter = new HeadResponseWriter("user");
+//      componentWriter = new HeadResponseWriter("component");
+//      userWriter = new HeadResponseWriter("user");
 //
-//		try {
-//			componentWriter.startDocument();
-//			userWriter.startDocument();
+//      try {
+//          componentWriter.startDocument();
+//          userWriter.startDocument();
 //
-//			context.setResponseWriter(componentWriter);
+//          context.setResponseWriter(componentWriter);
 //
-//			// Check init parameters for a resources processing.
-//			if (null != scriptStrategy) {
-//				if (InternetResourceBuilder.LOAD_NONE
-//						.equals(scriptStrategy)) {
-//					scriptsOff = true;
-//					processScripts = false;
-//				} else if (InternetResourceBuilder.LOAD_ALL
-//						.equals(scriptStrategy)) {
-//					processScripts = false;
-//					// For an "ALL" strategy, it is not necessary to load scripts in the ajax request
-//					if (!ajaxRequest) {
-//						try {
-//							resourceBuilder
-//							.createResource(
-//									this,
-//									InternetResourceBuilder.COMMON_FRAMEWORK_SCRIPT).encode(context, null);
-//							resourceBuilder
-//							.createResource(
-//									this,
-//									InternetResourceBuilder.COMMON_UI_SCRIPT).encode(context, null);
+//          // Check init parameters for a resources processing.
+//          if (null != scriptStrategy) {
+//              if (InternetResourceBuilder.LOAD_NONE
+//                      .equals(scriptStrategy)) {
+//                  scriptsOff = true;
+//                  processScripts = false;
+//              } else if (InternetResourceBuilder.LOAD_ALL
+//                      .equals(scriptStrategy)) {
+//                  processScripts = false;
+//                  // For an "ALL" strategy, it is not necessary to load scripts in the ajax request
+//                  if (!ajaxRequest) {
+//                      try {
+//                          resourceBuilder
+//                          .createResource(
+//                                  this,
+//                                  InternetResourceBuilder.COMMON_FRAMEWORK_SCRIPT).encode(context, null);
+//                          resourceBuilder
+//                          .createResource(
+//                                  this,
+//                                  InternetResourceBuilder.COMMON_UI_SCRIPT).encode(context, null);
 //
-//						} catch (ResourceNotFoundException e) {
-//							if (log.isWarnEnabled()) {
-//								log
-//								.warn("No aggregated javaScript library found "
-//										+ e.getMessage());
-//							}
-//						}
+//                      } catch (ResourceNotFoundException e) {
+//                          if (log.isWarnEnabled()) {
+//                              log
+//                              .warn("No aggregated javaScript library found "
+//                                      + e.getMessage());
+//                          }
+//                      }
 //
-//					}
-//				}
-//			}
+//                  }
+//              }
+//          }
 //
-//			if (InternetResourceBuilder.LOAD_NONE.equals(styleStrategy)) {
-//				processStyles = false;
-//			} else if (InternetResourceBuilder.LOAD_ALL
-//					.equals(styleStrategy)) {
-//				processStyles = false;
-//				// For an "ALL" strategy, it is not necessary to load styles
-//				// in the ajax request
-//				if (!ajaxRequest) {
+//          if (InternetResourceBuilder.LOAD_NONE.equals(styleStrategy)) {
+//              processStyles = false;
+//          } else if (InternetResourceBuilder.LOAD_ALL
+//                  .equals(styleStrategy)) {
+//              processStyles = false;
+//              // For an "ALL" strategy, it is not necessary to load styles
+//              // in the ajax request
+//              if (!ajaxRequest) {
 //
-//					try {
-//						useSkinning = encodeSkinningResources(context, resourceBuilder);
+//                  try {
+//                      useSkinning = encodeSkinningResources(context, resourceBuilder);
 //
-//						resourceBuilder
-//						.createResource(this, InternetResourceBuilder.COMMON_STYLE).encode(context, null);
+//                      resourceBuilder
+//                      .createResource(this, InternetResourceBuilder.COMMON_STYLE).encode(context, null);
 //
-//					} catch (ResourceNotFoundException e) {
-//						if (log.isWarnEnabled()) {
-//							log.warn("No stylesheet found "
-//									+ e.getMessage());
-//						}
-//					}
+//                  } catch (ResourceNotFoundException e) {
+//                      if (log.isWarnEnabled()) {
+//                          log.warn("No stylesheet found "
+//                                  + e.getMessage());
+//                      }
+//                  }
 //
-//				}
-//			} else {
-//				useSkinning = encodeSkinningResources(context, resourceBuilder);
-//			}
+//              }
+//          } else {
+//              useSkinning = encodeSkinningResources(context, resourceBuilder);
+//          }
 //
-//			//traverse components
-//			//traverse(context, context.getViewRoot());
+//          //traverse components
+//          //traverse(context, context.getViewRoot());
 //
-//			context.setResponseWriter(componentWriter);
+//          context.setResponseWriter(componentWriter);
 //
-//			QueueRegistry queueRegistry = QueueRegistry.getInstance(context);
-//			if (Boolean.valueOf(getInitParameterValue(context, "org.richfaces.queue.global.enabled"))) {
-//				queueRegistry.setShouldCreateDefaultGlobalQueue();
-//			}
-//			
-//			if (queueRegistry.hasQueuesToEncode()) {
-//				InternetResource queueScriptResource = resourceBuilder.getResource(QUEUE_SCRIPT_RESOURCE);
-//				queueScriptResource.encode(context, null);
-//			}
-//			
-//			// Append Skin StyleSheet after a
-//			if (null != skinStyleSheetUri) {
-//				String resourceURL = context.getApplication()
-//				.getViewHandler().getResourceURL(context,
-//						skinStyleSheetUri);
+//          QueueRegistry queueRegistry = QueueRegistry.getInstance(context);
+//          if (Boolean.valueOf(getInitParameterValue(context, "org.richfaces.queue.global.enabled"))) {
+//              queueRegistry.setShouldCreateDefaultGlobalQueue();
+//          }
+//          
+//          if (queueRegistry.hasQueuesToEncode()) {
+//              InternetResource queueScriptResource = resourceBuilder.getResource(QUEUE_SCRIPT_RESOURCE);
+//              queueScriptResource.encode(context, null);
+//          }
+//          
+//          // Append Skin StyleSheet after a
+//          if (null != skinStyleSheetUri) {
+//              String resourceURL = context.getApplication()
+//              .getViewHandler().getResourceURL(context,
+//                      skinStyleSheetUri);
 //
-//				URIInternetResource resourceImpl = new URIInternetResource();
-//				resourceImpl.setUri(resourceURL);
-//				resourceImpl.setRenderer(resourceBuilder.getStyleRenderer());
-//				resourceImpl.encode(context, null);
+//              URIInternetResource resourceImpl = new URIInternetResource();
+//              resourceImpl.setUri(resourceURL);
+//              resourceImpl.setRenderer(resourceBuilder.getStyleRenderer());
+//              resourceImpl.encode(context, null);
 //
-//				useSkinning = true;
-//			}
+//              useSkinning = true;
+//          }
 //
-//			if (null != skinExtendedStyleSheetUri && extendedSkinningAllowed) {
-//				String resourceURL = context.getApplication().getViewHandler().getResourceURL(context,
-//						skinExtendedStyleSheetUri);
+//          if (null != skinExtendedStyleSheetUri && extendedSkinningAllowed) {
+//              String resourceURL = context.getApplication().getViewHandler().getResourceURL(context,
+//                      skinExtendedStyleSheetUri);
 //
-//				URIInternetResource resourceImpl = new URIInternetResource();
-//				resourceImpl.setUri(resourceURL);
-//				resourceImpl.setRenderer(resourceBuilder.getStyleRenderer());
-//				resourceImpl.encode(context, null, EXTENDED_SKINNING);
+//              URIInternetResource resourceImpl = new URIInternetResource();
+//              resourceImpl.setUri(resourceURL);
+//              resourceImpl.setRenderer(resourceBuilder.getStyleRenderer());
+//              resourceImpl.encode(context, null, EXTENDED_SKINNING);
 //
-//				useSkinning = true;
-//			}
+//              useSkinning = true;
+//          }
 //
-//			if (useSkinning && extendedSkinningAllowed) {
-//				if (!ajaxRequest) {
-//					if (!scriptsOff) {
-//						//skinning levels aren't dynamic, page-level setting cannot be changed 
-//						//by AJAX request
-//						EXTENDED_SKINNING_ON_RESOURCE.encode(context, null);
-//					} else {
-//						
-//						Map<String, Object> applicationMap = context.getExternalContext().getApplicationMap();
-//						if (applicationMap.get(EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY) == null) {
-//							//do it once per application life - strategies can be changed dynamically
-//							ResponseWriter writer = context.getResponseWriter();
-//							try {
-//								StringWriter stringWriter = new StringWriter();
-//								
-//								if (oldResponseWriter != null) {
-//									context.setResponseWriter(oldResponseWriter.cloneWithWriter(stringWriter));
-//								} else {
-//									context.setResponseWriter(this.renderKit.createResponseWriter(
-//											stringWriter, "text/html", 
-//											"US-ASCII"));
-//								}
-//								
-//								
-//								EXTENDED_SKINNING_ON_RESOURCE.encode(context, null);
+//          if (useSkinning && extendedSkinningAllowed) {
+//              if (!ajaxRequest) {
+//                  if (!scriptsOff) {
+//                      //skinning levels aren't dynamic, page-level setting cannot be changed 
+//                      //by AJAX request
+//                      EXTENDED_SKINNING_ON_RESOURCE.encode(context, null);
+//                  } else {
+//                      
+//                      Map<String, Object> applicationMap = context.getExternalContext().getApplicationMap();
+//                      if (applicationMap.get(EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY) == null) {
+//                          //do it once per application life - strategies can be changed dynamically
+//                          ResponseWriter writer = context.getResponseWriter();
+//                          try {
+//                              StringWriter stringWriter = new StringWriter();
+//                              
+//                              if (oldResponseWriter != null) {
+//                                  context.setResponseWriter(oldResponseWriter.cloneWithWriter(stringWriter));
+//                              } else {
+//                                  context.setResponseWriter(this.renderKit.createResponseWriter(
+//                                          stringWriter, "text/html", 
+//                                          "US-ASCII"));
+//                              }
+//                              
+//                              
+//                              EXTENDED_SKINNING_ON_RESOURCE.encode(context, null);
 //
-//								stringWriter.flush();
-//								
-//								if (log.isInfoEnabled()) {
-//									log.info("Extended skinning is on and NONE scripts loading strategy was detected. " +
-//											"Do not forget that one of " + InternetResourceBuilder.SKINNING_SCRIPT + " or " + 
-//											InternetResourceBuilder.COMMON_FRAMEWORK_SCRIPT + " resources should be presented " +
-//											"on the page together with the following code: \n" + stringWriter.getBuffer().toString() +
-//											"\nfor extended level of skinning to work.");
-//								}
-//							} finally {
-//								if (writer != null) {
-//									context.setResponseWriter(writer);
-//								}
-//							}
+//                              stringWriter.flush();
+//                              
+//                              if (log.isInfoEnabled()) {
+//                                  log.info("Extended skinning is on and NONE scripts loading strategy was detected. " +
+//                                          "Do not forget that one of " + InternetResourceBuilder.SKINNING_SCRIPT + " or " + 
+//                                          InternetResourceBuilder.COMMON_FRAMEWORK_SCRIPT + " resources should be presented " +
+//                                          "on the page together with the following code: \n" + stringWriter.getBuffer().toString() +
+//                                          "\nfor extended level of skinning to work.");
+//                              }
+//                          } finally {
+//                              if (writer != null) {
+//                                  context.setResponseWriter(writer);
+//                              }
+//                          }
 //
-//							applicationMap.put(EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY, Boolean.TRUE);
-//						}
-//					}
-//				}
+//                          applicationMap.put(EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY, Boolean.TRUE);
+//                      }
+//                  }
+//              }
 //
-//				if (processScripts) {
-//					InternetResource resource = resourceBuilder.createResource(null, 
-//						InternetResourceBuilder.SKINNING_SCRIPT);
+//              if (processScripts) {
+//                  InternetResource resource = resourceBuilder.createResource(null, 
+//                      InternetResourceBuilder.SKINNING_SCRIPT);
 //
-//					resource.encode(context, null);
-//				}
-//			}
+//                  resource.encode(context, null);
+//              }
+//          }
 //
-//			componentWriter.endDocument();
-//			userWriter.endDocument();
-//		} catch (IOException e) {
-//			throw new FacesException(e.getLocalizedMessage(), e);
-//		} finally {
-//			if (oldResponseWriter != null) {
-//				context.setResponseWriter(oldResponseWriter);
-//			}
-//		}
-//	}
+//          componentWriter.endDocument();
+//          userWriter.endDocument();
+//      } catch (IOException e) {
+//          throw new FacesException(e.getLocalizedMessage(), e);
+//      } finally {
+//          if (oldResponseWriter != null) {
+//              context.setResponseWriter(oldResponseWriter);
+//          }
+//      }
+//  }
 //
-//	private static String getInitParameterValue(FacesContext context, String parameterName) {
-//		
-//		String key = INIT_PARAMETER_PREFIX + parameterName;
-//		
-//		ExternalContext externalContext = context.getExternalContext();
-//		Map<String, Object> applicationMap = externalContext.getApplicationMap();
-//		Object mutex = externalContext.getRequest();
-//		Object parameterValue = null;
-//		
-//		synchronized (mutex) {
-//			parameterValue = applicationMap.get(key);
+//  private static String getInitParameterValue(FacesContext context, String parameterName) {
+//      
+//      String key = INIT_PARAMETER_PREFIX + parameterName;
+//      
+//      ExternalContext externalContext = context.getExternalContext();
+//      Map<String, Object> applicationMap = externalContext.getApplicationMap();
+//      Object mutex = externalContext.getRequest();
+//      Object parameterValue = null;
+//      
+//      synchronized (mutex) {
+//          parameterValue = applicationMap.get(key);
 //
-//			if (parameterValue == null) {
+//          if (parameterValue == null) {
 //
-//				String initParameter = externalContext.getInitParameter(parameterName);
-//				if (initParameter != null) {
-//					
-//					if (ELUtils.isValueReference(initParameter)) {
-//						Application application = context.getApplication();
-//						ExpressionFactory expressionFactory = application.getExpressionFactory();
-//						
-//						parameterValue = expressionFactory.createValueExpression(context.getELContext(), 
-//								initParameter,
-//								String.class);
-//					} else {
-//						parameterValue = initParameter;
-//					}
-//					
-//				} else {
-//					parameterValue = NULL;
-//				}
-//				
-//				applicationMap.put(key, parameterValue);
-//			}
-//		}
-//		
-//		return evaluate(context, parameterValue);
-//	}
-//	
-//	private static String evaluate(FacesContext context, Object parameterValue) {
-//		if (parameterValue == NULL || parameterValue == null) {
-//			return null;
-//		} else if (parameterValue instanceof ValueExpression) {
-//			ValueExpression expression = (ValueExpression) parameterValue;
-//			
-//			return (String) expression.getValue(context.getELContext());
-//		} else {
-//			return parameterValue.toString();
-//		}
-//	}
+//              String initParameter = externalContext.getInitParameter(parameterName);
+//              if (initParameter != null) {
+//                  
+//                  if (ELUtils.isValueReference(initParameter)) {
+//                      Application application = context.getApplication();
+//                      ExpressionFactory expressionFactory = application.getExpressionFactory();
+//                      
+//                      parameterValue = expressionFactory.createValueExpression(context.getELContext(), 
+//                              initParameter,
+//                              String.class);
+//                  } else {
+//                      parameterValue = initParameter;
+//                  }
+//                  
+//              } else {
+//                  parameterValue = NULL;
+//              }
+//              
+//              applicationMap.put(key, parameterValue);
+//          }
+//      }
+//      
+//      return evaluate(context, parameterValue);
+//  }
+//  
+//  private static String evaluate(FacesContext context, Object parameterValue) {
+//      if (parameterValue == NULL || parameterValue == null) {
+//          return null;
+//      } else if (parameterValue instanceof ValueExpression) {
+//          ValueExpression expression = (ValueExpression) parameterValue;
+//          
+//          return (String) expression.getValue(context.getELContext());
+//      } else {
+//          return parameterValue.toString();
+//      }
+//  }
 //
-//	public void initialize(FacesContext context) {
-//		boolean extendedSkinningAllowed = true;
-//		String skinningLevel = getInitParameterValue(context, InternetResourceBuilder.CONTROL_SKINNING_LEVEL);
-//		if (skinningLevel != null && skinningLevel.length() > 0) {
-//			if (InternetResourceBuilder.BASIC.equals(skinningLevel)) {
-//				extendedSkinningAllowed = false;
-//			} else if (!InternetResourceBuilder.EXTENDED.equals(skinningLevel)) {
-//				throw new IllegalArgumentException("Value: " + skinningLevel + 
-//						" of " + InternetResourceBuilder.CONTROL_SKINNING_LEVEL 
-//						+ " init parameter is invalid! Only " + InternetResourceBuilder.EXTENDED 
-//						+ ", " + InternetResourceBuilder.BASIC + " can be used");
-//			}
-//		}
-//		
-//		this.setExtendedSkinningAllowed(extendedSkinningAllowed);
-//		
-//		this.setScriptStrategy(getInitParameterValue(context, 
-//				InternetResourceBuilder.LOAD_SCRIPT_STRATEGY_PARAM));
+//  public void initialize(FacesContext context) {
+//      boolean extendedSkinningAllowed = true;
+//      String skinningLevel = getInitParameterValue(context, InternetResourceBuilder.CONTROL_SKINNING_LEVEL);
+//      if (skinningLevel != null && skinningLevel.length() > 0) {
+//          if (InternetResourceBuilder.BASIC.equals(skinningLevel)) {
+//              extendedSkinningAllowed = false;
+//          } else if (!InternetResourceBuilder.EXTENDED.equals(skinningLevel)) {
+//              throw new IllegalArgumentException("Value: " + skinningLevel + 
+//                      " of " + InternetResourceBuilder.CONTROL_SKINNING_LEVEL 
+//                      + " init parameter is invalid! Only " + InternetResourceBuilder.EXTENDED 
+//                      + ", " + InternetResourceBuilder.BASIC + " can be used");
+//          }
+//      }
+//      
+//      this.setExtendedSkinningAllowed(extendedSkinningAllowed);
+//      
+//      this.setScriptStrategy(getInitParameterValue(context, 
+//              InternetResourceBuilder.LOAD_SCRIPT_STRATEGY_PARAM));
 //
-//		boolean useStdControlsSkinning = false;
+//      boolean useStdControlsSkinning = false;
 //
-//		String stdControlsSkinning = getInitParameterValue(context, InternetResourceBuilder.STD_CONTROLS_SKINNING_PARAM);
-//		if (stdControlsSkinning != null) {
-//			useStdControlsSkinning = InternetResourceBuilder.ENABLE.equals(stdControlsSkinning);
-//		}
-//		
-//		this.setUseStdControlsSkinning(useStdControlsSkinning);
+//      String stdControlsSkinning = getInitParameterValue(context, InternetResourceBuilder.STD_CONTROLS_SKINNING_PARAM);
+//      if (stdControlsSkinning != null) {
+//          useStdControlsSkinning = InternetResourceBuilder.ENABLE.equals(stdControlsSkinning);
+//      }
+//      
+//      this.setUseStdControlsSkinning(useStdControlsSkinning);
 //
-//		boolean useStdControlsSkinningClasses = true;
+//      boolean useStdControlsSkinningClasses = true;
 //
-//		String stdControlsSkinningClasses = getInitParameterValue(context, InternetResourceBuilder.STD_CONTROLS_SKINNING_CLASSES_PARAM);
-//		if (stdControlsSkinningClasses != null) {
-//			useStdControlsSkinningClasses = InternetResourceBuilder.ENABLE.equals(stdControlsSkinningClasses);
-//		}
+//      String stdControlsSkinningClasses = getInitParameterValue(context, InternetResourceBuilder.STD_CONTROLS_SKINNING_CLASSES_PARAM);
+//      if (stdControlsSkinningClasses != null) {
+//          useStdControlsSkinningClasses = InternetResourceBuilder.ENABLE.equals(stdControlsSkinningClasses);
+//      }
 //
-//		this.setUseStdControlsSkinningClasses(useStdControlsSkinningClasses);
-//		
-//		this.setStyleStrategy(getInitParameterValue(context, 
-//				InternetResourceBuilder.LOAD_STYLE_STRATEGY_PARAM));
+//      this.setUseStdControlsSkinningClasses(useStdControlsSkinningClasses);
+//      
+//      this.setStyleStrategy(getInitParameterValue(context, 
+//              InternetResourceBuilder.LOAD_STYLE_STRATEGY_PARAM));
 //
 //
-//	}
-//	
+//  }
+//  
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/context/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Classes and interfaces that defines contextual request information
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/css/CssCompressor.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/css/CssCompressor.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/css/CssCompressor.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -8,187 +8,207 @@
  * This code is a port of Isaac Schlueter's cssmin utility.
  */
 
+
+
 package org.ajax4jsf.css;
 
 import java.io.IOException;
 import java.io.Writer;
+
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 public class CssCompressor {
+    private StringBuffer srcsb = null;
 
-	private StringBuffer srcsb = null;
+    public CssCompressor(StringBuffer buffer) throws IOException {
+        srcsb = buffer;
+    }
 
-	public CssCompressor(StringBuffer buffer) throws IOException {
-		srcsb = buffer;
-	}
+    public int compress(Writer out, int linebreakpos) throws IOException {
+        Pattern p;
+        Matcher m;
+        String css;
+        StringBuffer sb;
+        int startIndex;
+        int endIndex;
 
-	public int compress(Writer out, int linebreakpos) throws IOException {
+        // Remove all comment blocks...
+        startIndex = 0;
 
-		Pattern p;
-		Matcher m;
-		String css;
-		StringBuffer sb;
-		int startIndex, endIndex;
+        boolean iemac = false;
+        boolean preserve = false;
 
-		// Remove all comment blocks...
-		startIndex = 0;
-		boolean iemac = false;
-		boolean preserve = false;
-		sb = new StringBuffer(srcsb.toString());
-		while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
-			preserve = sb.length() > startIndex + 2
-					&& sb.charAt(startIndex + 2) == '!';
-			endIndex = sb.indexOf("*/", startIndex + 2);
-			if (endIndex < 0) {
-				if (!preserve) {
-					sb.delete(startIndex, sb.length());
-				}
-			} else if (endIndex >= startIndex + 2) {
-				if (sb.charAt(endIndex - 1) == '\\') {
-					// Looks like a comment to hide rules from IE Mac.
-					// Leave this comment, and the following one, alone...
-					startIndex = endIndex + 2;
-					iemac = true;
-				} else if (iemac) {
-					startIndex = endIndex + 2;
-					iemac = false;
-				} else if (!preserve) {
-					sb.delete(startIndex, endIndex + 2);
-				} else {
-					startIndex = endIndex + 2;
-				}
-			}
-		}
+        sb = new StringBuffer(srcsb.toString());
 
-		css = sb.toString();
+        while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
+            preserve = (sb.length() > startIndex + 2) && (sb.charAt(startIndex + 2) == '!');
+            endIndex = sb.indexOf("*/", startIndex + 2);
 
-		// Normalize all whitespace strings to single spaces. Easier to work
-		// with that way.
-		css = css.replaceAll("\\s+", " ");
+            if (endIndex < 0) {
+                if (!preserve) {
+                    sb.delete(startIndex, sb.length());
+                }
+            } else if (endIndex >= startIndex + 2) {
+                if (sb.charAt(endIndex - 1) == '\\') {
 
-		// Make a pseudo class for the Box Model Hack
-		css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___");
+                    // Looks like a comment to hide rules from IE Mac.
+                    // Leave this comment, and the following one, alone...
+                    startIndex = endIndex + 2;
+                    iemac = true;
+                } else if (iemac) {
+                    startIndex = endIndex + 2;
+                    iemac = false;
+                } else if (!preserve) {
+                    sb.delete(startIndex, endIndex + 2);
+                } else {
+                    startIndex = endIndex + 2;
+                }
+            }
+        }
 
-		// Remove the spaces before the things that should not have spaces
-		// before them.
-		// But, be careful not to turn "p :link {...}" into "p:link{...}"
-		// Swap out any pseudo-class colons with the token, and then swap back.
-		sb = new StringBuffer();
-		p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
-		m = p.matcher(css);
-		while (m.find()) {
-			String s = m.group();
-			s = s.replaceAll(":", "___PSEUDOCLASSCOLON___");
-			m.appendReplacement(sb, s);
-		}
-		m.appendTail(sb);
-		css = sb.toString();
-		css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
-		css = css.replaceAll("___PSEUDOCLASSCOLON___", ":");
+        css = sb.toString();
 
-		// Remove the spaces after the things that should not have spaces after
-		// them.
-		css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
+        // Normalize all whitespace strings to single spaces. Easier to work
+        // with that way.
+        css = css.replaceAll("\\s+", " ");
 
-		// Add the semicolon where it's missing.
-		css = css.replaceAll("([^;\\}])}", "$1;}");
+        // Make a pseudo class for the Box Model Hack
+        css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___");
 
-		// Replace 0(px,em,%) with 0.
-		css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
+        // Remove the spaces before the things that should not have spaces
+        // before them.
+        // But, be careful not to turn "p :link {...}" into "p:link{...}"
+        // Swap out any pseudo-class colons with the token, and then swap back.
+        sb = new StringBuffer();
+        p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
+        m = p.matcher(css);
 
-		// Replace 0 0 0 0; with 0.
-		css = css.replaceAll(":0 0 0 0;", ":0;");
-		css = css.replaceAll(":0 0 0;", ":0;");
-		css = css.replaceAll(":0 0;", ":0;");
-		// Replace background-position:0; with background-position:0 0;
-		css = css.replaceAll("background-position:0;",
-				"background-position:0 0;");
+        while (m.find()) {
+            String s = m.group();
 
-		// Replace 0.6 to .6, but only when preceded by : or a white-space
-		css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
+            s = s.replaceAll(":", "___PSEUDOCLASSCOLON___");
+            m.appendReplacement(sb, s);
+        }
 
-		// Shorten colors from rgb(51,102,153) to #336699
-		// This makes it more likely that it'll get further compressed in the
-		// next step.
-		p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
-		m = p.matcher(css);
-		sb = new StringBuffer();
-		while (m.find()) {
-			String[] rgbcolors = m.group(1).split(",");
-			StringBuffer hexcolor = new StringBuffer("#");
-			for (int i = 0; i < rgbcolors.length; i++) {
-				int val = Integer.parseInt(rgbcolors[i]);
-				if (val < 16) {
-					hexcolor.append("0");
-				}
-				hexcolor.append(Integer.toHexString(val));
-			}
-			m.appendReplacement(sb, hexcolor.toString());
-		}
-		m.appendTail(sb);
-		css = sb.toString();
+        m.appendTail(sb);
+        css = sb.toString();
+        css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
+        css = css.replaceAll("___PSEUDOCLASSCOLON___", ":");
 
-		// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
-		// the color is not preceded by either ", " or =. Indeed, the property
-		// filter: chroma(color="#FFFFFF");
-		// would become
-		// filter: chroma(color="#FFF");
-		// which makes the filter break in IE.
-		p = Pattern
-				.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
-		m = p.matcher(css);
-		sb = new StringBuffer();
-		while (m.find()) {
-			// Test for AABBCC pattern
-			if (m.group(3).equalsIgnoreCase(m.group(4))
-					&& m.group(5).equalsIgnoreCase(m.group(6))
-					&& m.group(7).equalsIgnoreCase(m.group(8))) {
-				m.appendReplacement(sb, m.group(1) + m.group(2) + "#"
-						+ m.group(3) + m.group(5) + m.group(7));
-			} else {
-				m.appendReplacement(sb, m.group());
-			}
-		}
-		m.appendTail(sb);
-		css = sb.toString();
+        // Remove the spaces after the things that should not have spaces after
+        // them.
+        css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
 
-		// Remove empty rules.
-		css = css.replaceAll("[^\\}]+\\{;\\}", "");
+        // Add the semicolon where it's missing.
+        css = css.replaceAll("([^;\\}])}", "$1;}");
 
-		if (linebreakpos >= 0) {
-			// Some source control tools don't like it when files containing
-			// lines longer
-			// than, say 8000 characters, are checked in. The linebreak option
-			// is used in
-			// that case to split long lines after a specific column.
-			int i = 0;
-			int linestartpos = 0;
-			sb = new StringBuffer(css);
-			while (i < sb.length()) {
-				char c = sb.charAt(i++);
-				if (c == '}' && i - linestartpos > linebreakpos) {
-					sb.insert(i, '\n');
-					linestartpos = i;
-				}
-			}
+        // Replace 0(px,em,%) with 0.
+        css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
 
-			css = sb.toString();
-		}
+        // Replace 0 0 0 0; with 0.
+        css = css.replaceAll(":0 0 0 0;", ":0;");
+        css = css.replaceAll(":0 0 0;", ":0;");
+        css = css.replaceAll(":0 0;", ":0;");
 
-		// Replace the pseudo class for the Box Model Hack
-		css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\"");
+        // Replace background-position:0; with background-position:0 0;
+        css = css.replaceAll("background-position:0;", "background-position:0 0;");
 
-		// Replace multiple semi-colons in a row by a single one
-		// See SF bug #1980989
-		css = css.replaceAll(";;+", ";");
+        // Replace 0.6 to .6, but only when preceded by : or a white-space
+        css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
 
-		// Trim the final string (for any leading or trailing white spaces)
-		css = css.trim();
+        // Shorten colors from rgb(51,102,153) to #336699
+        // This makes it more likely that it'll get further compressed in the
+        // next step.
+        p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
+        m = p.matcher(css);
+        sb = new StringBuffer();
 
-		// Write the output...
-		out.write(css);
-		
-		return css.length();
-	}
+        while (m.find()) {
+            String[] rgbcolors = m.group(1).split(",");
+            StringBuffer hexcolor = new StringBuffer("#");
+
+            for (int i = 0; i < rgbcolors.length; i++) {
+                int val = Integer.parseInt(rgbcolors[i]);
+
+                if (val < 16) {
+                    hexcolor.append("0");
+                }
+
+                hexcolor.append(Integer.toHexString(val));
+            }
+
+            m.appendReplacement(sb, hexcolor.toString());
+        }
+
+        m.appendTail(sb);
+        css = sb.toString();
+
+        // Shorten colors from #AABBCC to #ABC. Note that we want to make sure
+        // the color is not preceded by either ", " or =. Indeed, the property
+        // filter: chroma(color="#FFFFFF");
+        // would become
+        // filter: chroma(color="#FFF");
+        // which makes the filter break in IE.
+        p = Pattern.compile(
+            "([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
+        m = p.matcher(css);
+        sb = new StringBuffer();
+
+        while (m.find()) {
+
+            // Test for AABBCC pattern
+            if (m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6))
+                    && m.group(7).equalsIgnoreCase(m.group(8))) {
+                m.appendReplacement(sb, m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7));
+            } else {
+                m.appendReplacement(sb, m.group());
+            }
+        }
+
+        m.appendTail(sb);
+        css = sb.toString();
+
+        // Remove empty rules.
+        css = css.replaceAll("[^\\}]+\\{;\\}", "");
+
+        if (linebreakpos >= 0) {
+
+            // Some source control tools don't like it when files containing
+            // lines longer
+            // than, say 8000 characters, are checked in. The linebreak option
+            // is used in
+            // that case to split long lines after a specific column.
+            int i = 0;
+            int linestartpos = 0;
+
+            sb = new StringBuffer(css);
+
+            while (i < sb.length()) {
+                char c = sb.charAt(i++);
+
+                if ((c == '}') && (i - linestartpos > linebreakpos)) {
+                    sb.insert(i, '\n');
+                    linestartpos = i;
+                }
+            }
+
+            css = sb.toString();
+        }
+
+        // Replace the pseudo class for the Box Model Hack
+        css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\"");
+
+        // Replace multiple semi-colons in a row by a single one
+        // See SF bug #1980989
+        css = css.replaceAll(";;+", ";");
+
+        // Trim the final string (for any leading or trailing white spaces)
+        css = css.trim();
+
+        // Write the output...
+        out.write(css);
+
+        return css.length();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/css/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/css/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/css/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * CSS-processing classes
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/el/ELContextWrapper.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/el/ELContextWrapper.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/el/ELContextWrapper.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,6 +18,9 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.el;
 
 import java.util.Locale;
@@ -32,67 +35,66 @@
  *
  */
 public class ELContextWrapper extends ELContext {
-	
-	private final ELContext parent;
-	
-	private final ELResolver resolver;
+    private final ELContext parent;
+    private final ELResolver resolver;
 
-	/**
-	 * @param parent
-	 */
-	public ELContextWrapper(ELContext parent,ELResolver resolver) {
-		super();
-		this.resolver = resolver;
-		this.parent = parent;
-	}
+    /**
+     * @param parent
+     */
+    public ELContextWrapper(ELContext parent, ELResolver resolver) {
+        super();
+        this.resolver = resolver;
+        this.parent = parent;
+    }
 
-	/* (non-Javadoc)
-	 * @see javax.el.ELContext#getELResolver()
-	 */
-	@Override
-	public ELResolver getELResolver() {
-		return resolver;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.el.ELContext#getELResolver()
+     */
+    @Override
+    public ELResolver getELResolver() {
+        return resolver;
+    }
 
-	/**
-	 * @return
-	 * @see javax.el.ELContext#getFunctionMapper()
-	 */
-	public FunctionMapper getFunctionMapper() {
-		return parent.getFunctionMapper();
-	}
+    /**
+     * @return
+     * @see javax.el.ELContext#getFunctionMapper()
+     */
+    public FunctionMapper getFunctionMapper() {
+        return parent.getFunctionMapper();
+    }
 
-	/**
-	 * @return
-	 * @see javax.el.ELContext#getVariableMapper()
-	 */
-	public VariableMapper getVariableMapper() {
-		return parent.getVariableMapper();
-	}
+    /**
+     * @return
+     * @see javax.el.ELContext#getVariableMapper()
+     */
+    public VariableMapper getVariableMapper() {
+        return parent.getVariableMapper();
+    }
 
-	/**
-	 * @param key
-	 * @return
-	 * @see javax.el.ELContext#getContext(java.lang.Class)
-	 */
-	public Object getContext(Class key) {
-		return parent.getContext(key);
-	}
+    /**
+     * @param key
+     * @return
+     * @see javax.el.ELContext#getContext(java.lang.Class)
+     */
+    public Object getContext(Class key) {
+        return parent.getContext(key);
+    }
 
-	/**
-	 * @param key
-	 * @param contextObject
-	 * @see javax.el.ELContext#putContext(java.lang.Class, java.lang.Object)
-	 */
-	public void putContext(Class key, Object contextObject) {
-		parent.putContext(key, contextObject);
-	}
+    /**
+     * @param key
+     * @param contextObject
+     * @see javax.el.ELContext#putContext(java.lang.Class, java.lang.Object)
+     */
+    public void putContext(Class key, Object contextObject) {
+        parent.putContext(key, contextObject);
+    }
 
-	public Locale getLocale() {
-		return parent.getLocale();
-	}
-	
-	public void setLocale(Locale locale) {
-		parent.setLocale(locale);
-	}
+    public Locale getLocale() {
+        return parent.getLocale();
+    }
+
+    public void setLocale(Locale locale) {
+        parent.setLocale(locale);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/el/ELResolverWrapper.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/el/ELResolverWrapper.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/el/ELResolverWrapper.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,9 +19,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.el;
 
 import java.beans.FeatureDescriptor;
+
 import java.util.Iterator;
 
 import javax.el.ELContext;
@@ -31,79 +34,75 @@
  * @author Nick Belaevski
  * @since 3.3.0
  */
-
 public class ELResolverWrapper extends ELResolver {
+    private ELResolver resolver;
 
-	public ELResolverWrapper(ELResolver resolver) {
-		super();
-		this.resolver = resolver;
-	}
+    public ELResolverWrapper(ELResolver resolver) {
+        super();
+        this.resolver = resolver;
+    }
 
-	private ELResolver resolver;
+    /**
+     * @param context
+     * @param base
+     * @return
+     * @see javax.el.ELResolver#getCommonPropertyType(javax.el.ELContext, java.lang.Object)
+     */
+    public Class<?> getCommonPropertyType(ELContext context, Object base) {
+        return resolver.getCommonPropertyType(context, base);
+    }
 
-	/**
-	 * @param context
-	 * @param base
-	 * @return
-	 * @see javax.el.ELResolver#getCommonPropertyType(javax.el.ELContext, java.lang.Object)
-	 */
-	public Class<?> getCommonPropertyType(ELContext context, Object base) {
-		return resolver.getCommonPropertyType(context, base);
-	}
+    /**
+     * @param context
+     * @param base
+     * @return
+     * @see javax.el.ELResolver#getFeatureDescriptors(javax.el.ELContext, java.lang.Object)
+     */
+    public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
+        return resolver.getFeatureDescriptors(context, base);
+    }
 
-	/**
-	 * @param context
-	 * @param base
-	 * @return
-	 * @see javax.el.ELResolver#getFeatureDescriptors(javax.el.ELContext, java.lang.Object)
-	 */
-	public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context,
-			Object base) {
-		return resolver.getFeatureDescriptors(context, base);
-	}
+    /**
+     * @param context
+     * @param base
+     * @param property
+     * @return
+     * @see javax.el.ELResolver#getType(javax.el.ELContext, java.lang.Object, java.lang.Object)
+     */
+    public Class<?> getType(ELContext context, Object base, Object property) {
+        return resolver.getType(context, base, property);
+    }
 
-	/**
-	 * @param context
-	 * @param base
-	 * @param property
-	 * @return
-	 * @see javax.el.ELResolver#getType(javax.el.ELContext, java.lang.Object, java.lang.Object)
-	 */
-	public Class<?> getType(ELContext context, Object base, Object property) {
-		return resolver.getType(context, base, property);
-	}
+    /**
+     * @param context
+     * @param base
+     * @param property
+     * @return
+     * @see javax.el.ELResolver#getValue(javax.el.ELContext, java.lang.Object, java.lang.Object)
+     */
+    public Object getValue(ELContext context, Object base, Object property) {
+        return resolver.getValue(context, base, property);
+    }
 
-	/**
-	 * @param context
-	 * @param base
-	 * @param property
-	 * @return
-	 * @see javax.el.ELResolver#getValue(javax.el.ELContext, java.lang.Object, java.lang.Object)
-	 */
-	public Object getValue(ELContext context, Object base, Object property) {
-		return resolver.getValue(context, base, property);
-	}
+    /**
+     * @param context
+     * @param base
+     * @param property
+     * @return
+     * @see javax.el.ELResolver#isReadOnly(javax.el.ELContext, java.lang.Object, java.lang.Object)
+     */
+    public boolean isReadOnly(ELContext context, Object base, Object property) {
+        return resolver.isReadOnly(context, base, property);
+    }
 
-	/**
-	 * @param context
-	 * @param base
-	 * @param property
-	 * @return
-	 * @see javax.el.ELResolver#isReadOnly(javax.el.ELContext, java.lang.Object, java.lang.Object)
-	 */
-	public boolean isReadOnly(ELContext context, Object base, Object property) {
-		return resolver.isReadOnly(context, base, property);
-	}
-
-	/**
-	 * @param context
-	 * @param base
-	 * @param property
-	 * @param value
-	 * @see javax.el.ELResolver#setValue(javax.el.ELContext, java.lang.Object, java.lang.Object, java.lang.Object)
-	 */
-	public void setValue(ELContext context, Object base, Object property,
-			Object value) {
-		resolver.setValue(context, base, property, value);
-	}
+    /**
+     * @param context
+     * @param base
+     * @param property
+     * @param value
+     * @see javax.el.ELResolver#setValue(javax.el.ELContext, java.lang.Object, java.lang.Object, java.lang.Object)
+     */
+    public void setValue(ELContext context, Object base, Object property, Object value) {
+        resolver.setValue(context, base, property, value);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxListenerHelper.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxListenerHelper.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxListenerHelper.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,100 +19,104 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.event;
 
 import java.io.Serializable;
 
 import javax.el.ValueExpression;
+
 import javax.faces.component.StateHolder;
 import javax.faces.component.UIComponentBase;
 import javax.faces.context.FacesContext;
-import javax.faces.el.ValueBinding;
 
 /**
  * Helper class to keep reference to listener binded as EL-expression.
  * @author shura
  *
  */
-public class AjaxListenerHelper implements AjaxListener,StateHolder {
-	
-	
-	private ValueExpression _expression;
-	
-	
-	private boolean _transient = false;
+public class AjaxListenerHelper implements AjaxListener, StateHolder {
+    private boolean isTransient = false;
+    private ValueExpression expression;
 
-	
-	/**
-	 * 
-	 */
-	public AjaxListenerHelper() {
-		super();
-		// TODO Auto-generated constructor stub
-	}
+    /**
+     *
+     */
+    public AjaxListenerHelper() {
+        super();
 
-	/**
-	 * @param binding
-	 */
-	public AjaxListenerHelper(ValueExpression expression) {
-		super();
-		if (null == expression) {
-			throw new IllegalArgumentException("Binding expression for AjaxListener helper must be not null");
-		}
-		_expression = expression;
-	}
+        // TODO Auto-generated constructor stub
+    }
 
-	private AjaxListener getHandler(FacesContext context) {
-		return (AjaxListener) _expression.getValue(context.getELContext());
-	}
+    /**
+     * @param expression
+     */
+    public AjaxListenerHelper(ValueExpression expression) {
+        super();
 
-	/* (non-Javadoc)
-	 * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object)
-	 */
-	public void restoreState(FacesContext context, Object state) {
-		State helperState = (State) state;
-		_expression = (ValueExpression) UIComponentBase.restoreAttachedState(context,helperState.binding);
-	}
+        if (null == expression) {
+            throw new IllegalArgumentException("Binding expression for AjaxListener helper must be not null");
+        }
 
-	/* (non-Javadoc)
-	 * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext)
-	 */
-	public Object saveState(FacesContext context) {
-		State helperState = new State();
-		helperState.binding = UIComponentBase.saveAttachedState(context,_expression);
-		return helperState;
-	}
+        this.expression = expression;
+    }
 
-	/**
-	 * @return Returns the transient.
-	 */
-	public boolean isTransient() {
-		return _transient;
-	}
+    private AjaxListener getHandler(FacesContext context) {
+        return (AjaxListener) expression.getValue(context.getELContext());
+    }
 
-	/**
-	 * @param transient1 The transient to set.
-	 */
-	public void setTransient(boolean transient1) {
-		_transient = transient1;
-	}
-	
-	/**
-	 * @author shura
-	 *
-	 */
-	private static class State implements Serializable {
-		
-		
-		private Object binding;
-		
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.component.StateHolder#restoreState(javax.faces.context.FacesContext, java.lang.Object)
+     */
+    public void restoreState(FacesContext context, Object state) {
+        State helperState = (State) state;
 
-	}
+        expression = (ValueExpression) UIComponentBase.restoreAttachedState(context, helperState.binding);
+    }
 
-	public void processAjax(AjaxEvent event) {
-		FacesContext context = FacesContext.getCurrentInstance();
-		AjaxListener handler = getHandler(context);
-		handler.processAjax(event);
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.component.StateHolder#saveState(javax.faces.context.FacesContext)
+     */
+    public Object saveState(FacesContext context) {
+        State helperState = new State();
 
+        helperState.binding = UIComponentBase.saveAttachedState(context, expression);
+
+        return helperState;
+    }
+
+    /**
+     * @return Returns the transient.
+     */
+    public boolean isTransient() {
+        return isTransient;
+    }
+
+    /**
+     * @param transient1 The transient to set.
+     */
+    public void setTransient(boolean transient1) {
+        isTransient = transient1;
+    }
+
+    public void processAjax(AjaxEvent event) {
+        FacesContext context = FacesContext.getCurrentInstance();
+        AjaxListener handler = getHandler(context);
+
+        handler.processAjax(event);
+    }
+
+    /**
+     * @author shura
+     * TODO Refactoring
+     */
+    private static final class State implements Serializable {
+        private static final long serialVersionUID = 1978277414406556172L;
+        private Object binding;
+
+        private State() {}
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxPhaseListener.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxPhaseListener.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxPhaseListener.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,18 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.event;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.context.AjaxContext;
+
+import org.richfaces.log.RichfacesLogger;
+import org.richfaces.skin.SkinFactory;
+
+import org.slf4j.Logger;
+
 import java.util.Map;
 
 import javax.faces.component.UIViewRoot;
@@ -29,115 +39,105 @@
 import javax.faces.event.PhaseId;
 import javax.faces.event.PhaseListener;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.context.AjaxContext;
-import org.richfaces.log.RichfacesLogger;
-import org.richfaces.skin.SkinFactory;
-import org.slf4j.Logger;
-
 /**
  * Listener for act before Render phase to set RenderKit Id for current skin.
- * 
+ *
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.3 $ $Date: 2007/02/06 16:23:19 $
- * 
+ *
  */
 public class AjaxPhaseListener implements PhaseListener {
+    public static final String AJAX_BEAN_PREFIX = "org.ajax4jsf.ajaxviewbean:";
+    public static final String VIEW_BEAN_PREFIX = "org.ajax4jsf.viewbean:";
+    private static final long serialVersionUID = -4087936963051339868L;
+    private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
 
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -4087936963051339868L;
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
+     */
+    public void afterPhase(PhaseEvent event) {
+        PhaseId phaseId = event.getPhaseId();
 
-	public static final String VIEW_BEAN_PREFIX = "org.ajax4jsf.viewbean:";
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Process after phase " + phaseId.toString());
+        }
 
-	private static final Logger log = RichfacesLogger.APPLICATION.getLogger();
+        FacesContext context = event.getFacesContext();
+        Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
+        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
 
-	public static final String AJAX_BEAN_PREFIX = "org.ajax4jsf.ajaxviewbean:";
+        if (phaseId == PhaseId.RESTORE_VIEW) {
+            UIViewRoot viewRoot = context.getViewRoot();
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
-	 */
-	public void afterPhase(PhaseEvent event) {
-		PhaseId phaseId = event.getPhaseId();
-		if (log.isDebugEnabled()) {
-			log.debug("Process after phase " + phaseId.toString());
-		}
-		FacesContext context = event.getFacesContext();
-		Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
-		AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-		if (phaseId == PhaseId.RESTORE_VIEW) {
-			UIViewRoot viewRoot = context.getViewRoot();
-			if (null != viewRoot) {
-				boolean isAjax = ajaxContext.isAjaxRequest();
-				Map<String, Object> attributes = viewRoot.getAttributes();
-				for(String stringKey:attributes.keySet()) {
-						if (stringKey.startsWith(VIEW_BEAN_PREFIX)) {
-							requestMap.put(stringKey.substring(VIEW_BEAN_PREFIX
-									.length()), attributes.get(stringKey));
-						} else if (isAjax
-								&& stringKey.startsWith(AJAX_BEAN_PREFIX)) {
-							requestMap.put(stringKey.substring(AJAX_BEAN_PREFIX
-									.length()), attributes.get(stringKey));
-						}
+            if (null != viewRoot) {
+                boolean isAjax = ajaxContext.isAjaxRequest();
+                Map<String, Object> attributes = viewRoot.getAttributes();
 
-				}
-			}
-		}
-	}
+                for (String stringKey : attributes.keySet()) {
+                    if (stringKey.startsWith(VIEW_BEAN_PREFIX)) {
+                        requestMap.put(stringKey.substring(VIEW_BEAN_PREFIX.length()), attributes.get(stringKey));
+                    } else if (isAjax && stringKey.startsWith(AJAX_BEAN_PREFIX)) {
+                        requestMap.put(stringKey.substring(AJAX_BEAN_PREFIX.length()), attributes.get(stringKey));
+                    }
+                }
+            }
+        }
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
-	 */
-	public void beforePhase(PhaseEvent event) {
-		PhaseId phaseId = event.getPhaseId();
-		if (log.isDebugEnabled()) {
-			log.debug("Process before phase " + phaseId.toString());
-		}
-		FacesContext context = event.getFacesContext();
-		if (phaseId == PhaseId.RENDER_RESPONSE) {
-			// Clear ViewId replacement, to avoid incorrect rendering of forms
-			// URI.
-			AjaxContext.getCurrentInstance(context).setViewIdHolder(null);
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
+     */
+    public void beforePhase(PhaseEvent event) {
+        PhaseId phaseId = event.getPhaseId();
 
-			UIViewRoot root = context.getViewRoot();
-			if (null != root) {
-				log.debug(Messages.getMessage(
-						Messages.ENTER_BEFORE_RENDER_VIEW_PHASE, root
-								.getViewId(), root.getRenderKitId()));
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Process before phase " + phaseId.toString());
+        }
 
-				// TODO - create special skin-config.xml configuration.
-				String renderKitId = null;
-				try {
-					renderKitId = SkinFactory.getInstance().getSkin(context)
-							.getRenderKitId(context);
-				} catch (Exception e) {
-					log.error("Exception on get current Skin ", e);
-				}
-				if (null != renderKitId) {
-					log.debug(Messages.getMessage(
-							Messages.SET_RENDER_KIT_ID_INFO, renderKitId));
-					root.setRenderKitId(renderKitId);
-				}
+        FacesContext context = event.getFacesContext();
 
-			}
-		} else if (phaseId == PhaseId.RESTORE_VIEW) {
+        if (phaseId == PhaseId.RENDER_RESPONSE) {
 
-		}
-	}
+            // Clear ViewId replacement, to avoid incorrect rendering of forms
+            // URI.
+            AjaxContext.getCurrentInstance(context).setViewIdHolder(null);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.event.PhaseListener#getPhaseId()
-	 */
-	public PhaseId getPhaseId() {
-		return PhaseId.ANY_PHASE;
-	}
+            UIViewRoot root = context.getViewRoot();
 
+            if (null != root) {
+                LOG.debug(Messages.getMessage(Messages.ENTER_BEFORE_RENDER_VIEW_PHASE, root.getViewId(),
+                                              root.getRenderKitId()));
 
+                // TODO - create special skin-config.xml configuration.
+                String renderKitId = null;
+
+                try {
+                    renderKitId = SkinFactory.getInstance().getSkin(context).getRenderKitId(context);
+                } catch (Exception e) {
+                    LOG.error("Exception on get current Skin ", e);
+                }
+
+                if (null != renderKitId) {
+                    LOG.debug(Messages.getMessage(Messages.SET_RENDER_KIT_ID_INFO, renderKitId));
+                    root.setRenderKitId(renderKitId);
+                }
+            }
+        } else if (phaseId == PhaseId.RESTORE_VIEW) {
+
+            // TODO Refactoring
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.event.PhaseListener#getPhaseId()
+     */
+    public PhaseId getPhaseId() {
+        return PhaseId.ANY_PHASE;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxValidationActionEvent.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxValidationActionEvent.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/AjaxValidationActionEvent.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.event;
 
 import javax.faces.component.UIComponent;
@@ -34,26 +36,27 @@
  */
 public class AjaxValidationActionEvent extends ActionEvent {
 
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = 941784856915815112L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 941784856915815112L;
 
-	/**
-	 * @param component
-	 */
-	public AjaxValidationActionEvent(UIComponent component) {
-		super(component);
-		// TODO Auto-generated constructor stub
-	}
+    /**
+     * @param component
+     */
+    public AjaxValidationActionEvent(UIComponent component) {
+        super(component);
 
-	/* (non-Javadoc)
-	 * @see javax.faces.event.FacesEvent#getPhaseId()
-	 */
-	public PhaseId getPhaseId() {
-		// TODO Auto-generated method stub
-		return PhaseId.PROCESS_VALIDATIONS;
-	}
+        // TODO Auto-generated constructor stub
+    }
 
-	
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.event.FacesEvent#getPhaseId()
+     */
+    public PhaseId getPhaseId() {
+
+        // TODO Auto-generated method stub
+        return PhaseId.PROCESS_VALIDATIONS;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/CacheInitializationListener.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/CacheInitializationListener.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/CacheInitializationListener.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,30 +1,26 @@
 package org.ajax4jsf.event;
 
-import java.util.Map;
-import java.util.Set;
+import org.ajax4jsf.cache.CacheManager;
 
 import javax.faces.event.SystemEvent;
 
-import org.ajax4jsf.cache.Cache;
-import org.ajax4jsf.cache.CacheManager;
-
 /**
  * @author Anton Belevich
  *
  */
 public class CacheInitializationListener extends InitializationListener {
-	
-	@Override
-	public void init(SystemEvent event) {
-		//TODO read configuration ??
-	}
+    @Override
+    public void init(SystemEvent event) {
 
+        // TODO read configuration ??
+    }
+
     @Override
     public void destroy(SystemEvent event) {
         try {
             CacheManager.getInstance().destroy();
         } catch (Exception e) {
-            looger.error("Error during stop caches.", e);
+            LOG.error("Error during stop caches.", e);
         }
     }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/EventsQueue.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/EventsQueue.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/EventsQueue.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,6 +18,9 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.event;
 
 import java.util.AbstractQueue;
@@ -31,130 +34,133 @@
  * @author asmirnov
  *
  */
-public class EventsQueue  extends AbstractQueue<FacesEvent>{
-	
-	private QueueElement first;
-	
-	private QueueElement last;
+public class EventsQueue extends AbstractQueue<FacesEvent> {
+    private int size = 0;
+    private QueueElement first;
+    private QueueElement last;
 
-	private int size = 0;
-	
-	/**
-	 * Remove and return first queued event.
-	 * @return faces event form top of queue
-	 * @throws NoSuchElementException , if queue is empty.
-	 */
-	public FacesEvent poll()  {
-		FacesEvent element = null;
-		if (!isEmpty()) {
-			element = first.getElement();
-			first = first.getPrevious();
-			if (null == first) {
-				last = null;
-				size = 0;
-			} else {
-			size--;
-			}
-		}
-		return element;
-	}
+    /**
+     * Remove and return first queued event.
+     * @return faces event form top of queue
+     * @throws NoSuchElementException , if queue is empty.
+     */
+    public FacesEvent poll() {
+        FacesEvent element = null;
 
-	public FacesEvent peek()  {
-		FacesEvent element = null;
-		if (!isEmpty()) {
-			element = first.getElement();
-		}
-		return element;
-	}
-	/**
-	 * Add event to queue.
-	 * @param element
-	 * @return TODO
-	 */
-	public boolean offer(FacesEvent element) {
-		QueueElement queueElement = new QueueElement(element);
-		if(isEmpty()){
-			first = last = queueElement;
-		} else {
-			last.setPrevious(queueElement);
-			last = queueElement;
-		}
-		size++;
-		return true;
-	}
+        if (!isEmpty()) {
+            element = first.getElement();
+            first = first.getPrevious();
 
-	public void clear() {
-		size = 0;
-		first = last = null;
-	}
+            if (null == first) {
+                last = null;
+                size = 0;
+            } else {
+                size--;
+            }
+        }
 
-	public boolean isEmpty() {		
-		return null == first;
-	}
-	
-	public int size() {
-		return size;
-	}
+        return element;
+    }
 
-	private static class QueueElement {
-		
-		private QueueElement previous;
-		
-		private FacesEvent element;
+    public FacesEvent peek() {
+        FacesEvent element = null;
 
-		public QueueElement(FacesEvent element) {
-			this.element = element;
-		}
+        if (!isEmpty()) {
+            element = first.getElement();
+        }
 
-		
-		/**
-		 * @param previous the previous to set
-		 */
-		public void setPrevious(QueueElement previsious) {
-			this.previous = previsious;
-		}
+        return element;
+    }
 
+    /**
+     * Add event to queue.
+     * @param element
+     * @return TODO
+     */
+    public boolean offer(FacesEvent element) {
+        QueueElement queueElement = new QueueElement(element);
 
-		/**
-		 * @return the previous
-		 */
-		public QueueElement getPrevious() {
-			return previous;
-		}
+        if (isEmpty()) {
+            first = queueElement;
+            last = queueElement;
+        } else {
+            last.setPrevious(queueElement);
+            last = queueElement;
+        }
 
-		/**
-		 * @return the element
-		 */
-		public FacesEvent getElement() {
-			return element;
-		}
-		
-	}
+        size++;
 
-	@Override
-	public Iterator<FacesEvent> iterator() {
-		
-		return new Iterator<FacesEvent>(){
-			
-			private QueueElement current = first;
+        return true;
+    }
 
-			public boolean hasNext() {
-				return null != current;
-			}
+    @Override
+    public void clear() {
+        size = 0;
+        first = null;
+        last = null;
+    }
 
-			public FacesEvent next() {
-				if(null == current){
-					throw new NoSuchElementException();
-				}
-				FacesEvent event = current.getElement();
-				current = current.getPrevious();
-				return event;
-			}
+    @Override
+    public boolean isEmpty() {
+        return null == first;
+    }
 
-			public void remove() {
-				throw new UnsupportedOperationException();				
-			}
-			
-		};
-	}
+    @Override
+    public int size() {
+        return size;
+    }
+
+    @Override
+    public Iterator<FacesEvent> iterator() {
+        return new Iterator<FacesEvent>() {
+            private QueueElement current = first;
+            public boolean hasNext() {
+                return null != current;
+            }
+            public FacesEvent next() {
+                if (null == current) {
+                    throw new NoSuchElementException();
+                }
+
+                FacesEvent event = current.getElement();
+
+                current = current.getPrevious();
+
+                return event;
+            }
+            public void remove() {
+                throw new UnsupportedOperationException();
+            }
+        };
+    }
+
+    private static class QueueElement {
+        private FacesEvent element;
+        private QueueElement previous;
+
+        public QueueElement(FacesEvent element) {
+            this.element = element;
+        }
+
+        /**
+         * @param previous the previous to set
+         */
+        public void setPrevious(QueueElement previsious) {
+            this.previous = previsious;
+        }
+
+        /**
+         * @return the previous
+         */
+        public QueueElement getPrevious() {
+            return previous;
+        }
+
+        /**
+         * @return the element
+         */
+        public FacesEvent getElement() {
+            return element;
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/InitPhaseListener.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/InitPhaseListener.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/InitPhaseListener.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.event;
 
+import org.ajax4jsf.application.AjaxViewHandler;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.util.Iterator;
 
 import javax.faces.FactoryFinder;
@@ -33,78 +41,77 @@
 import javax.faces.lifecycle.Lifecycle;
 import javax.faces.lifecycle.LifecycleFactory;
 
-import org.ajax4jsf.application.AjaxViewHandler;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * One time called listener, for initialize framework at first request.
  * @author shura
  *
  */
 public class InitPhaseListener implements PhaseListener {
-	
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = 8389169240912928686L;
-	private volatile boolean removed= false;
-	private volatile boolean initialized = false;
-	
-	private static final Logger log = RichfacesLogger.APPLICATION.getLogger();
+    private static final long serialVersionUID = 8389169240912928686L;
+    private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
+    private volatile boolean removed = false;
+    private volatile boolean initialized = false;
 
-	/* (non-Javadoc)
-	 * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
-	 */
-	public synchronized void afterPhase(PhaseEvent event) {
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
+     */
+    public synchronized void afterPhase(PhaseEvent event) {
         if (!removed) {
-        	if(log.isDebugEnabled()){
-        		log.debug("Remove init phase listener from factories");
-        	}
-            LifecycleFactory factory = (LifecycleFactory)
-                  FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
-            for(Iterator<String> iter = factory.getLifecycleIds(); iter.hasNext(); ) {
-                Lifecycle lifecycle = factory.getLifecycle((String) iter.next());
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Remove init phase listener from factories");
+            }
+
+            LifecycleFactory factory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
+
+            for (Iterator<String> iter = factory.getLifecycleIds(); iter.hasNext(); ) {
+                Lifecycle lifecycle = factory.getLifecycle(iter.next());
+
                 lifecycle.removePhaseListener(this);
             }
+
             removed = true;
         }
-	}
+    }
 
-	/* (non-Javadoc)
-	 * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
-	 */
-	public synchronized void beforePhase(PhaseEvent event) {
-		if(!initialized){
-			if(log.isDebugEnabled()){
-				log.debug("Perform additional framework initialization on first request");
-			}
-			FacesContext facesContext = event.getFacesContext();
-			Application application = facesContext.getApplication();
-			ViewHandler viewHandler = application.getViewHandler();
-			
-			if (!(viewHandler instanceof AjaxViewHandler)) {
-				if(log.isDebugEnabled()){
-					log.debug("Set AjaxViewHandler on top of chain");
-				}
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
+     */
+    public synchronized void beforePhase(PhaseEvent event) {
+        if (!initialized) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Perform additional framework initialization on first request");
+            }
 
-				AjaxViewHandler ajaxViewHandler = new AjaxViewHandler(viewHandler);
-				ajaxViewHandler.fillChain(facesContext);
-				
-				application.setViewHandler(ajaxViewHandler);
-			} else {
-				((AjaxViewHandler) viewHandler).fillChain(facesContext);
-			}
-			initialized = true;
-		}
-	}
+            FacesContext facesContext = event.getFacesContext();
+            Application application = facesContext.getApplication();
+            ViewHandler viewHandler = application.getViewHandler();
 
-	/* (non-Javadoc)
-	 * @see javax.faces.event.PhaseListener#getPhaseId()
-	 */
-	public PhaseId getPhaseId() {
-		// TODO Auto-generated method stub
-		return PhaseId.ANY_PHASE;
-	}
+            if (!(viewHandler instanceof AjaxViewHandler)) {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Set AjaxViewHandler on top of chain");
+                }
 
+                AjaxViewHandler ajaxViewHandler = new AjaxViewHandler(viewHandler);
+
+                ajaxViewHandler.fillChain(facesContext);
+                application.setViewHandler(ajaxViewHandler);
+            } else {
+                ((AjaxViewHandler) viewHandler).fillChain(facesContext);
+            }
+
+            initialized = true;
+        }
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.event.PhaseListener#getPhaseId()
+     */
+    public PhaseId getPhaseId() {
+
+        // TODO Auto-generated method stub
+        return PhaseId.ANY_PHASE;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/InitializationListener.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/InitializationListener.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/InitializationListener.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,38 +1,36 @@
 package org.ajax4jsf.event;
 
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import javax.faces.application.Application;
-import javax.faces.event.AbortProcessingException;
 import javax.faces.event.PostConstructApplicationEvent;
 import javax.faces.event.PreDestroyApplicationEvent;
 import javax.faces.event.SystemEvent;
 import javax.faces.event.SystemEventListener;
 
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * framework initialization listener
  * @author Anton Belevich
  *
  */
 public abstract class InitializationListener implements SystemEventListener {
-	
-	protected static final Logger looger = RichfacesLogger.CACHE.getLogger();
-	
-	public boolean isListenerForSource(Object source) {
-		return source instanceof Application ? true : false;
-	}
+    protected static final Logger LOG = RichfacesLogger.CACHE.getLogger();
 
-	public void processEvent(SystemEvent event) throws AbortProcessingException {
-		if(event instanceof PostConstructApplicationEvent) {
-			init(event);	
-		} else if(event instanceof PreDestroyApplicationEvent) {
-			destroy(event);
-		}
-	}
-	
-	public abstract void init(SystemEvent event);
-	
-	public abstract void destroy(SystemEvent event);
-	
+    public boolean isListenerForSource(Object source) {
+        return source instanceof Application;
+    }
+
+    public void processEvent(SystemEvent event) {
+        if (event instanceof PostConstructApplicationEvent) {
+            init(event);
+        } else if (event instanceof PreDestroyApplicationEvent) {
+            destroy(event);
+        }
+    }
+
+    public abstract void init(SystemEvent event);
+
+    public abstract void destroy(SystemEvent event);
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Classes implementing event-handling logic of JSF framework
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/exception/FileUploadException.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/exception/FileUploadException.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/exception/FileUploadException.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,27 +19,25 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.exception;
 
 /**
- * Thrown when an exception occurs while uploading a file. 
- *  
+ * Thrown when an exception occurs while uploading a file.
+ *
  * @author Shane Bryzak
  */
-public class FileUploadException extends RuntimeException
-{   
-   public FileUploadException()
-   {
-      this(null, null);
-   }
-   
-   public FileUploadException(String message)
-   {
-      this(message, null);
-   }
-   
-   public FileUploadException(String message, Throwable cause)
-   {
-      super(message, cause);
-   }   
+public class FileUploadException extends RuntimeException {
+    public FileUploadException() {
+        this(null, null);
+    }
+
+    public FileUploadException(String message) {
+        this(message, null);
+    }
+
+    public FileUploadException(String message, Throwable cause) {
+        super(message, cause);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/exception/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/exception/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/exception/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Exception classes of RichFaces components
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/ByteBuffer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/ByteBuffer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/ByteBuffer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,218 +19,234 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.io;
 
 import java.io.UnsupportedEncodingException;
 
 /**
- * A single link in chain of byte arrays. 
+ * A single link in chain of byte arrays.
  * @author glory
  */
 public class ByteBuffer {
-	
-	private static final int MAX_WASTE = 16384;
-	
-	private ByteBuffer prev;
-	private ByteBuffer next;
+    private static final int MAX_WASTE = 16384;
 
-	/**
-	 * Stored bytes
-	 */
-	private byte[] bytes;
+    /**
+     * Stored bytes
+     */
+    private byte[] bytes;
 
-	/**
-	 * Length of byte array.
-	 */
-	private int cacheSize;
+    /**
+     * Length of byte array.
+     */
+    private int cacheSize;
+    private ByteBuffer next;
+    private ByteBuffer prev;
 
-	/**
-	 * Number of bytes stored in the array.
-	 */
-	private int usedSize;
+    /**
+     * Number of bytes stored in the array.
+     */
+    private int usedSize;
 
-	/**
-	 * Creates instance of ByteBuffer with byte array of required length.
-	 * @param cacheSize length of byte array
-	 */	
-	public ByteBuffer(int cacheSize) {
-		bytes = new byte[cacheSize];
-		this.cacheSize = cacheSize;
-		usedSize = 0;
-	}
-	
-	/**
-	 * Creates instance of ByteBuffer already filled by bytes.
-	 * @param bytes
-	 */
-	public ByteBuffer(byte[] bytes) {
-		this.bytes = bytes;
-		usedSize = bytes.length;
-		cacheSize = usedSize;
-	}
+    /**
+     * Creates instance of ByteBuffer already filled by bytes.
+     * @param bytes
+     */
+    public ByteBuffer(byte[] bytes) {
+        this.bytes = bytes;
+        usedSize = bytes.length;
+        cacheSize = usedSize;
+    }
 
-	/**
-	 * Appends byte to array if there are unfilled positions in it.
-	 * Otherwize creates next link in the chain, and appends the byte to it.
-	 * @param c
-	 * @return instance of ByteBuffer to which byte was appended.
-	 */	
-	public ByteBuffer append(byte c) {
-		if(next != null) {
-			return next.append(c);
-		}
-		if(usedSize < cacheSize) {
-			bytes[usedSize] = c;
-			usedSize++;
-			return this;
-		} else {
-			next = new ByteBuffer(cacheSize * 2);
-			next.prev = this;
-			return next.append(c);
-		}
-	}
+    /**
+     * Creates instance of ByteBuffer with byte array of required length.
+     * @param cacheSize length of byte array
+     */
+    public ByteBuffer(int cacheSize) {
+        bytes = new byte[cacheSize];
+        this.cacheSize = cacheSize;
+        usedSize = 0;
+    }
 
-	/**
-	 * Appends segment of a byte array to array if there are unfilled positions in it.
-	 * Otherwize creates next link in the chain, and appends data to it.
-	 * @param c
-	 * @return instance of ByteBuffer to which byte array was appended.
-	 */	
-	public ByteBuffer append(byte[] bs, int off, int len) {
-		if(next != null) {
-			return append(bs, off, len);
-		}
-		if(len + usedSize <= cacheSize) {
-			System.arraycopy(bs, off, bytes, usedSize, len);
-			usedSize += len;
-			return this;
-		}
-		int av = cacheSize - usedSize;
-		if(av > 0) {
-			System.arraycopy(bs, off, bytes, usedSize, av);
-			usedSize += av;
-			off += av;
-			len -= av;
-		}
-		next = new ByteBuffer(cacheSize * 2);
-		next.prev = this;
-		return next.append(bs, off, len);
-	}
+    /**
+     * Appends byte to array if there are unfilled positions in it.
+     * Otherwize creates next link in the chain, and appends the byte to it.
+     * @param c
+     * @return instance of ByteBuffer to which byte was appended.
+     */
+    public ByteBuffer append(byte c) {
+        if (next != null) {
+            return next.append(c);
+        }
 
-	/**
-	 * Returns stored byte array.
-	 * @return stored byte array
-	 */	
-	public byte[] getBytes() {
-		return bytes;
-	}
-	
-	/**
-	 * Returns byte at index. No check is fulfilled to provide high speed.
-	 * @param index
-	 * @return
-	 */
-	public byte getByteAt(int index) {
-		return bytes[index];
-	}
-	
-	/**
-	 * Returns actual number of byte stored in this link.
-	 * @return
-	 */	
-	public int getUsedSize() {
-		return usedSize;
-	}
-	
-	/**
-	 * Returns capacity of this link.
-	 * @return
-	 */	
-	public int getCacheSize() {
-		return cacheSize;
-	}
-	
-	/**
-	 * Returns total number of bytes stored in this link and all its predecessors. 
-	 * @return
-	 */	
-	public int getTotalSize() {
-		return (prev == null) ? usedSize : prev.getTotalSize() + usedSize;
-	}
-	
-	/**
-	 * Returns the previous link in the chain.
-	 * @return
-	 */	
-	public ByteBuffer getPrevious() {
-		return prev;
-	}
-	
-	/**
-	 * Returns the next link in the chain.
-	 * @return
-	 */	
-	public ByteBuffer getNext() {
-		return next;
-	}
-	
-	/**
-	 * Sets the next link in the chain.
-	 * @param b
-	 */	
-	public void setNext(ByteBuffer b) {
-		next = b;
-		if(b != null) b.prev = this;
-	}
-	
-	/**
-	 * Transforms this instance to instance of CharBuffer (a link of chain of char arrays).
-	 * @param encoding
-	 * @return link of chain of char arrays
-	 * @throws UnsupportedEncodingException
-	 */
-	public CharBuffer toCharBuffer(String encoding) throws UnsupportedEncodingException {
-		String s;
-		if (null != encoding) {
-			s = new String(bytes, 0, usedSize, encoding);
-		} else {
-			s = new String(bytes, 0, usedSize);			
-		}
-		return new CharBuffer(s.toCharArray());
-	}
+        if (usedSize < cacheSize) {
+            bytes[usedSize] = c;
+            usedSize++;
 
-	/**
-	 * Transforms this instance to instance of CharBuffer (a link of chain of char arrays).
-	 * @return link of chain of char arrays
-	 */
-	public CharBuffer toCharBuffer() {
-		String s = new String(bytes, 0, usedSize);
-		return new CharBuffer(s.toCharArray());
-	}
+            return this;
+        } else {
+            next = new ByteBuffer(cacheSize * 2);
+            next.prev = this;
 
-	/**
-	 * Resets this byte buffer to empty state
-	 * @since 3.3.0
-	 */
-	public void reset() {
-		usedSize = 0;
-		next = null;
-		prev = null;
-	}
+            return next.append(c);
+        }
+    }
 
-	/**
-	 * @since 4.0
-	 */
-	public void compact() {
-		if (bytes.length - usedSize > MAX_WASTE) {
-			byte[] bs = new byte[usedSize];
-			System.arraycopy(bytes, 0, bs, 0, usedSize);
-			this.bytes = bs;
-			this.cacheSize = bs.length;
-		}
-		
-		if (next != null) {
-			next.compact();
-		}
-	}
+    /**
+     * Appends segment of a byte array to array if there are unfilled positions in it.
+     * Otherwize creates next link in the chain, and appends data to it.
+     * @param c
+     * @return instance of ByteBuffer to which byte array was appended.
+     */
+    public ByteBuffer append(byte[] bs, int off, int len) {
+        if (next != null) {
+            return append(bs, off, len);
+        }
+
+        if (len + usedSize <= cacheSize) {
+            System.arraycopy(bs, off, bytes, usedSize, len);
+            usedSize += len;
+
+            return this;
+        }
+
+        int av = cacheSize - usedSize;
+
+        if (av > 0) {
+            System.arraycopy(bs, off, bytes, usedSize, av);
+            usedSize += av;
+            off += av;
+            len -= av;
+        }
+
+        next = new ByteBuffer(cacheSize * 2);
+        next.prev = this;
+
+        return next.append(bs, off, len);
+    }
+
+    /**
+     * Returns stored byte array.
+     * @return stored byte array
+     */
+    public byte[] getBytes() {
+        return bytes;
+    }
+
+    /**
+     * Returns byte at index. No check is fulfilled to provide high speed.
+     * @param index
+     * @return
+     */
+    public byte getByteAt(int index) {
+        return bytes[index];
+    }
+
+    /**
+     * Returns actual number of byte stored in this link.
+     * @return
+     */
+    public int getUsedSize() {
+        return usedSize;
+    }
+
+    /**
+     * Returns capacity of this link.
+     * @return
+     */
+    public int getCacheSize() {
+        return cacheSize;
+    }
+
+    /**
+     * Returns total number of bytes stored in this link and all its predecessors.
+     * @return
+     */
+    public int getTotalSize() {
+        return (prev == null) ? usedSize : prev.getTotalSize() + usedSize;
+    }
+
+    /**
+     * Returns the previous link in the chain.
+     * @return
+     */
+    public ByteBuffer getPrevious() {
+        return prev;
+    }
+
+    /**
+     * Returns the next link in the chain.
+     * @return
+     */
+    public ByteBuffer getNext() {
+        return next;
+    }
+
+    /**
+     * Sets the next link in the chain.
+     * @param b
+     */
+    public void setNext(ByteBuffer b) {
+        next = b;
+
+        if (b != null) {
+            b.prev = this;
+        }
+    }
+
+    /**
+     * Transforms this instance to instance of CharBuffer (a link of chain of char arrays).
+     * @param encoding
+     * @return link of chain of char arrays
+     * @throws UnsupportedEncodingException
+     */
+    public CharBuffer toCharBuffer(String encoding) throws UnsupportedEncodingException {
+        String s;
+
+        if (null != encoding) {
+            s = new String(bytes, 0, usedSize, encoding);
+        } else {
+            s = new String(bytes, 0, usedSize);
+        }
+
+        return new CharBuffer(s.toCharArray());
+    }
+
+    /**
+     * Transforms this instance to instance of CharBuffer (a link of chain of char arrays).
+     * @return link of chain of char arrays
+     */
+    public CharBuffer toCharBuffer() {
+        String s = new String(bytes, 0, usedSize);
+
+        return new CharBuffer(s.toCharArray());
+    }
+
+    /**
+     * Resets this byte buffer to empty state
+     * @since 3.3.0
+     */
+    public void reset() {
+        usedSize = 0;
+        next = null;
+        prev = null;
+    }
+
+    /**
+     * @since 4.0
+     */
+    public void compact() {
+        if (bytes.length - usedSize > MAX_WASTE) {
+            byte[] bs = new byte[usedSize];
+
+            System.arraycopy(bytes, 0, bs, 0, usedSize);
+            this.bytes = bs;
+            this.cacheSize = bs.length;
+        }
+
+        if (next != null) {
+            next.compact();
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/CharBuffer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/CharBuffer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/CharBuffer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,217 +19,234 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.io;
 
 import java.io.UnsupportedEncodingException;
 
 /**
- * A single link in chain of char arrays. 
+ * A single link in chain of char arrays.
  * @author glory
  */
 public class CharBuffer {
+    private static final int MAX_WASTE = 16384;
+    private static final int MIN_CACHE_SIZE = 64;
 
-	private static final int MAX_WASTE = 16384;
+    /**
+     * Length of char array.
+     */
+    private int cacheSize;
 
-	private CharBuffer prev;
-	private CharBuffer next;
-	
-	/**
-	 * Stored characters
-	 */
-	private char[] chars;
-	
-	/**
-	 * Length of char array.
-	 */
-	private int cacheSize;
-	private static int MIN_CACHE_SIZE = 64;
-	/**
-	 * number of characters stored in the array.
-	 */
-	private int usedSize;
-	
-	/**
-	 * Creates instance of CharBuffer with char array of required length.
-	 * @param cacheSize length of char array
-	 */	
-	public CharBuffer(int cacheSize) {
-		if (cacheSize<MIN_CACHE_SIZE) {
-			this.cacheSize = MIN_CACHE_SIZE;
-		} else {
-			this.cacheSize = cacheSize;
-		}
-		chars = new char[this.cacheSize];
-		usedSize = 0;
-	}
-	
-	/**
-	 * Creates instance of CharBuffer already filled by chars.
-	 * @param bytes
-	 */
-	public CharBuffer(char[] chars) {
-		this.chars = chars;
-		usedSize = chars.length;
-		cacheSize = usedSize;
-	}
-	
-	/**
-	 * Appends character to array chars if there are unfilled positions in it.
-	 * Otherwise creates next link in the chain, and appends the character to it.
-	 * @param c
-	 * @return instance of CharBuffer to which character was appended.
-	 */	
-	public CharBuffer append(char c) {
-		if(next != null) {
-			return next.append(c);
-		}
-		if(usedSize < cacheSize) {
-			chars[usedSize] = c;
-			usedSize++;
-			return this;
-		} else {
-			next = new CharBuffer(cacheSize * 2);
-			next.prev = this;
-			return next.append(c);
-		}
-	}
-	
-	/**
-	 * Appends segment of a char array to array if there are unfilled positions in it.
-	 * Otherwise creates next link in the chain, and appends data to it.
-	 * @param c
-	 * @return instance of CharBuffer to which char array was appended.
-	 */	
-	public CharBuffer append(char[] cs, int off, int len) {
-		if(next != null) {
-			return next.append(cs, off, len);
-		}
-		if(len + usedSize <= cacheSize) {
-			System.arraycopy(cs, off, chars, usedSize, len);
-			usedSize += len;
-			return this;
-		}
-		int av = cacheSize - usedSize;
-		if(av > 0) {
-			System.arraycopy(cs, off, chars, usedSize, av);
-			usedSize += av;
-			off += av;
-			len -= av;
-		}
-		next = new CharBuffer(cacheSize * 2);
-		next.prev = this;
-		return next.append(cs, off, len);
-	}
+    /**
+     * Stored characters
+     */
+    private char[] chars;
+    private CharBuffer next;
+    private CharBuffer prev;
 
-	/**
-	 * Returns stored char array.
-	 * @return stored char array
-	 */	
-	public char[] getChars() {
-		return chars;
-	}
+    /**
+     * number of characters stored in the array.
+     */
+    private int usedSize;
 
-	/**
-	 * Returns character at index. No check is fulfilled to provide high speed.
-	 * @param index
-	 * @return
-	 */
-	public char getCharAt(int index) {
-		return chars[index];
-	}
-	
-	/**
-	 * Returns actual number of characters stored in this link.
-	 * @return
-	 */	
-	public int getUsedSize() {
-		return usedSize;
-	}
-	
-	/**
-	 * Returns capacity of this link.
-	 * @return
-	 */	
-	public int getCacheSize() {
-		return cacheSize;
-	}
-	
-	/**
-	 * Returns total number of characters stored in this link and all its predecessors. 
-	 * @return
-	 */	
-	public int getTotalSize() {
-		return (prev == null) ? usedSize : prev.getTotalSize() + usedSize;
-	}
-	
-	/**
-	 * Returns the previous link in the chain.
-	 * @return
-	 */	
-	public CharBuffer getPrevious() {
-		return prev;
-	}
-	
-	/**
-	 * Returns the next link in the chain.
-	 * @return
-	 */	
-	public CharBuffer getNext() {
-		return next;
-	}
-	
-	/**
-	 * Sets the next link in the chain.
-	 * @param b
-	 */	
-	public void setNext(CharBuffer b) {
-		next = b;
-		if(b != null) b.prev = this;
-	}
+    /**
+     * Creates instance of CharBuffer already filled by chars.
+     * @param bytes
+     */
+    public CharBuffer(char[] chars) {
+        this.chars = chars;
+        usedSize = chars.length;
+        cacheSize = usedSize;
+    }
 
-	/**
-	 * Transforms this instance to instance of ByteBuffer (a link of chain of byte arrays).
-	 * @param encoding
-	 * @return link of chain of byte arrays
-	 * @throws UnsupportedEncodingException
-	 */
-	public ByteBuffer toByteBuffer(String encoding) throws UnsupportedEncodingException {
-		byte[] bs = new String(chars, 0, usedSize).getBytes(encoding);
-		return new ByteBuffer(bs);
-	}
+    /**
+     * Creates instance of CharBuffer with char array of required length.
+     * @param cacheSize length of char array
+     */
+    public CharBuffer(int cacheSize) {
+        if (cacheSize < MIN_CACHE_SIZE) {
+            this.cacheSize = MIN_CACHE_SIZE;
+        } else {
+            this.cacheSize = cacheSize;
+        }
 
-	/**
-	 * Transforms this instance to instance of ByteBuffer (a link of chain of byte arrays).
-	 * @return link of chain of byte arrays
-	 */
-	public ByteBuffer toByteBuffer() {
-		byte[] bs = new String(chars, 0, usedSize).getBytes();
-		return new ByteBuffer(bs);
-	}
+        chars = new char[this.cacheSize];
+        usedSize = 0;
+    }
 
-	/**
-	 * Resets this char buffer to empty state
-	 * @since 3.3.0
-	 */
-	public void reset() {
-		usedSize = 0;
-		next = null;
-		prev = null;
-	}
-	
-	/**
-	 * @since 4.0
-	 */
-	public void compact() {
-		if (chars.length - usedSize > MAX_WASTE) {
-			char[] cs = new char[usedSize];
-			System.arraycopy(chars, 0, cs, 0, usedSize);
-			this.chars = cs;
-			this.cacheSize = cs.length;
-		}
-		
-		if (next != null) {
-			next.compact();
-		}
-	}
+    /**
+     * Appends character to array chars if there are unfilled positions in it.
+     * Otherwise creates next link in the chain, and appends the character to it.
+     * @param c
+     * @return instance of CharBuffer to which character was appended.
+     */
+    public CharBuffer append(char c) {
+        if (next != null) {
+            return next.append(c);
+        }
+
+        if (usedSize < cacheSize) {
+            chars[usedSize] = c;
+            usedSize++;
+
+            return this;
+        } else {
+            next = new CharBuffer(cacheSize * 2);
+            next.prev = this;
+
+            return next.append(c);
+        }
+    }
+
+    /**
+     * Appends segment of a char array to array if there are unfilled positions in it.
+     * Otherwise creates next link in the chain, and appends data to it.
+     * @param c
+     * @return instance of CharBuffer to which char array was appended.
+     */
+    public CharBuffer append(char[] cs, int off, int len) {
+        if (next != null) {
+            return next.append(cs, off, len);
+        }
+
+        if (len + usedSize <= cacheSize) {
+            System.arraycopy(cs, off, chars, usedSize, len);
+            usedSize += len;
+
+            return this;
+        }
+
+        int av = cacheSize - usedSize;
+
+        if (av > 0) {
+            System.arraycopy(cs, off, chars, usedSize, av);
+            usedSize += av;
+            off += av;
+            len -= av;
+        }
+
+        next = new CharBuffer(cacheSize * 2);
+        next.prev = this;
+
+        return next.append(cs, off, len);
+    }
+
+    /**
+     * Returns stored char array.
+     * @return stored char array
+     */
+    public char[] getChars() {
+        return chars;
+    }
+
+    /**
+     * Returns character at index. No check is fulfilled to provide high speed.
+     * @param index
+     * @return
+     */
+    public char getCharAt(int index) {
+        return chars[index];
+    }
+
+    /**
+     * Returns actual number of characters stored in this link.
+     * @return
+     */
+    public int getUsedSize() {
+        return usedSize;
+    }
+
+    /**
+     * Returns capacity of this link.
+     * @return
+     */
+    public int getCacheSize() {
+        return cacheSize;
+    }
+
+    /**
+     * Returns total number of characters stored in this link and all its predecessors.
+     * @return
+     */
+    public int getTotalSize() {
+        return (prev == null) ? usedSize : prev.getTotalSize() + usedSize;
+    }
+
+    /**
+     * Returns the previous link in the chain.
+     * @return
+     */
+    public CharBuffer getPrevious() {
+        return prev;
+    }
+
+    /**
+     * Returns the next link in the chain.
+     * @return
+     */
+    public CharBuffer getNext() {
+        return next;
+    }
+
+    /**
+     * Sets the next link in the chain.
+     * @param b
+     */
+    public void setNext(CharBuffer b) {
+        next = b;
+
+        if (b != null) {
+            b.prev = this;
+        }
+    }
+
+    /**
+     * Transforms this instance to instance of ByteBuffer (a link of chain of byte arrays).
+     * @param encoding
+     * @return link of chain of byte arrays
+     * @throws UnsupportedEncodingException
+     */
+    public ByteBuffer toByteBuffer(String encoding) throws UnsupportedEncodingException {
+        byte[] bs = new String(chars, 0, usedSize).getBytes(encoding);
+
+        return new ByteBuffer(bs);
+    }
+
+    /**
+     * Transforms this instance to instance of ByteBuffer (a link of chain of byte arrays).
+     * @return link of chain of byte arrays
+     */
+    public ByteBuffer toByteBuffer() {
+        byte[] bs = new String(chars, 0, usedSize).getBytes();
+
+        return new ByteBuffer(bs);
+    }
+
+    /**
+     * Resets this char buffer to empty state
+     * @since 3.3.0
+     */
+    public void reset() {
+        usedSize = 0;
+        next = null;
+        prev = null;
+    }
+
+    /**
+     * @since 4.0
+     */
+    public void compact() {
+        if (chars.length - usedSize > MAX_WASTE) {
+            char[] cs = new char[usedSize];
+
+            System.arraycopy(chars, 0, cs, 0, usedSize);
+            this.chars = cs;
+            this.cacheSize = cs.length;
+        }
+
+        if (next != null) {
+            next.compact();
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferInputStream.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferInputStream.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferInputStream.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.io;
 
 import java.io.IOException;
@@ -26,181 +28,235 @@
 
 /**
  * Class for reading from a byte array chain.
- * 
+ *
  * @author glory
  *
  */
 public class FastBufferInputStream extends InputStream {
-	/**
-	 * The first link in the chain of char arrays.
-	 */
-	ByteBuffer firstLink;
-	
-	/**
-	 * Currently read link.
-	 */
-	ByteBuffer current;
-	
-	/**
-	 * Position of next byte in current link.
-	 */
-	int index;
-	
-	int mark;
-	
-	/**
-	 * Creates instance of FastBufferInputStream.
-	 * @param stream
-	 */	
-	@Deprecated
-	public FastBufferInputStream(FastBufferOutputStream stream) {
-		this(stream.getFirstBuffer());
-	}
-	
-	public FastBufferInputStream(ByteBuffer byteBuffer) {
-		this.firstLink = byteBuffer;
-		current = byteBuffer;
-		index = 0;
-		mark = 0;
-	}
-	
-	/**
-	 * @see java.io.InputStream.read()
-	 */
-	public int read() throws IOException {
-		if(current == null) return -1;
-		if(current.getUsedSize() <= index) {
-			current = current.getNext();
-			if(current == null) return -1;
-			index = 0;
-		}
-		byte c = current.getByteAt(index);
-		index++;
-		return c;
-	}
 
-	/**
-	 * @see java.io.InputStream.read(byte b[])
-	 */
-	public int read(byte b[]) throws IOException {
-		if (b == null) {
-			throw new NullPointerException();
-		}
-		if(current == null) return -1;
-		int off = 0;
-		int len = b.length;
-		int actuallyRead = 0;
-		while(current != null && len > 0) {
-			int av = current.getUsedSize() - index;
-			if(av <= 0) {
-				current = current.getNext();
-				index = 0;
-				continue;
-			}
-			if(av > len) av = len;
-			System.arraycopy(current.getBytes(), index, b, off, av);
-			index += av;
-			off += av;
-			actuallyRead += av;
-			len -= av;
-		}
-		return actuallyRead == 0 ? -1 : actuallyRead;
-	}
+    /**
+     * Currently read link.
+     */
+    ByteBuffer current;
 
-	/**
-	 * @see java.io.InputStream.read(byte b[], int off, int len)
-	 */
-	public int read(byte[] b, int off, int len) throws IOException {
-		if (b == null) {
-			throw new NullPointerException();
-		} else if ((off < 0) || (off > b.length) || (len < 0) ||
-				((off + len) > b.length) || ((off + len) < 0)) {
-			throw new IndexOutOfBoundsException();
-		} else if (len == 0) {
-			return 0;
-		}
-		if(current == null) return -1;
+    /**
+     * The first link in the chain of char arrays.
+     */
+    ByteBuffer firstLink;
 
-		int actuallyRead = 0;
-		while(current != null && len > 0) {
-			int av = current.getUsedSize() - index;
-			if(av <= 0) {
-				current = current.getNext();
-				index = 0;
-				continue;
-			}
-			if(av > len) av = len;
-			System.arraycopy(current.getBytes(), index, b, off, av);
-			index += av;
-			off += av;
-			actuallyRead += av;
-			len -= av;
-		}
-		return actuallyRead == 0 ? -1 : actuallyRead;
-	}
+    /**
+     * Position of next byte in current link.
+     */
+    int index;
+    int mark;
 
-	/**
-	 * @see java.io.InputStream.available()
-	 */
-	public int available() throws IOException {
-		if(current == null) return 0;
-		ByteBuffer b = current;
-		int result = -index;
-		while(b != null) {
-			result += b.getUsedSize();
-			b = b.getNext();
-		}
-		return result;
-	}
+    public FastBufferInputStream(ByteBuffer byteBuffer) {
+        this.firstLink = byteBuffer;
+        current = byteBuffer;
+        index = 0;
+        mark = 0;
+    }
 
-	/**
-	 * @see java.io.InputStream.mark()
-	 */
-	public void mark(int readAheadLimit) {
-		if(current == null) {
-			mark = 0;
-		} else {
-			mark = index;
-			ByteBuffer b = current.getPrevious();
-			if(b != null) mark += b.getTotalSize();
-		}
-	}
-	
-	/**
-	 * @see java.io.InputStream.reset()
-	 */
-	public void reset() {
-		if(current == null) current = firstLink;
-		int m = 0;
-		while(current != null && current.getUsedSize() + m <= mark) {
-			m += current.getUsedSize();
-			current = current.getNext();
-		}
-		if(current != null) {
-			index = mark - m;
-		}
-	}
+    /**
+     * Creates instance of FastBufferInputStream.
+     * @param stream
+     */
+    @Deprecated
+    public FastBufferInputStream(FastBufferOutputStream stream) {
+        this(stream.getFirstBuffer());
+    }
 
-	/**
-	 * @see java.io.InputStream.skip()
-	 */
-	public long skip(long n) throws IOException {
-		long skipped = 0;
-		while(n > 0) {
-			if(current == null) return 0;
-			if(current.getUsedSize() - index <= n) {
-				index += n;
-				skipped += n;
-				break;
-			} else {
-				int dn = current.getUsedSize() - index;
-				skipped += dn;
-				n -= dn;
-				current = current.getNext();
-				index = 0;
-			}
-		}
-		return skipped;
-	}
+    /**
+     * @see java.io.InputStream.read()
+     */
+    public int read() throws IOException {
+        if (current == null) {
+            return -1;
+        }
 
+        if (current.getUsedSize() <= index) {
+            current = current.getNext();
+
+            if (current == null) {
+                return -1;
+            }
+
+            index = 0;
+        }
+
+        byte c = current.getByteAt(index);
+
+        index++;
+
+        return c;
+    }
+
+    /**
+     * @see java.io.InputStream.read(byte b[])
+     */
+    @Override
+    public int read(byte[] b) throws IOException {
+        if (b == null) {
+            throw new NullPointerException();
+        }
+
+        if (current == null) {
+            return -1;
+        }
+
+        int off = 0;
+        int len = b.length;
+        int actuallyRead = 0;
+
+        while ((current != null) && (len > 0)) {
+            int av = current.getUsedSize() - index;
+
+            if (av <= 0) {
+                current = current.getNext();
+                index = 0;
+
+                continue;
+            }
+
+            if (av > len) {
+                av = len;
+            }
+
+            System.arraycopy(current.getBytes(), index, b, off, av);
+            index += av;
+            off += av;
+            actuallyRead += av;
+            len -= av;
+        }
+
+        return (actuallyRead == 0) ? -1 : actuallyRead;
+    }
+
+    /**
+     * @see java.io.InputStream.read(byte b[], int off, int len)
+     */
+    @Override
+    public int read(byte[] b, int off, int len) throws IOException {
+        if (b == null) {
+            throw new NullPointerException();
+        } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {
+            throw new IndexOutOfBoundsException();
+        } else if (len == 0) {
+            return 0;
+        }
+
+        if (current == null) {
+            return -1;
+        }
+
+        int actuallyRead = 0;
+
+        while ((current != null) && (len > 0)) {
+            int av = current.getUsedSize() - index;
+
+            if (av <= 0) {
+                current = current.getNext();
+                index = 0;
+
+                continue;
+            }
+
+            if (av > len) {
+                av = len;
+            }
+
+            System.arraycopy(current.getBytes(), index, b, off, av);
+            index += av;
+            off += av;
+            actuallyRead += av;
+            len -= av;
+        }
+
+        return (actuallyRead == 0) ? -1 : actuallyRead;
+    }
+
+    /**
+     * @see java.io.InputStream.available()
+     */
+    public int available() throws IOException {
+        if (current == null) {
+            return 0;
+        }
+
+        ByteBuffer b = current;
+        int result = -index;
+
+        while (b != null) {
+            result += b.getUsedSize();
+            b = b.getNext();
+        }
+
+        return result;
+    }
+
+    /**
+     * @see java.io.InputStream.mark()
+     */
+    public void mark(int readAheadLimit) {
+        if (current == null) {
+            mark = 0;
+        } else {
+            mark = index;
+
+            ByteBuffer b = current.getPrevious();
+
+            if (b != null) {
+                mark += b.getTotalSize();
+            }
+        }
+    }
+
+    /**
+     * @see java.io.InputStream.reset()
+     */
+    public void reset() {
+        if (current == null) {
+            current = firstLink;
+        }
+
+        int m = 0;
+
+        while ((current != null) && (current.getUsedSize() + m <= mark)) {
+            m += current.getUsedSize();
+            current = current.getNext();
+        }
+
+        if (current != null) {
+            index = mark - m;
+        }
+    }
+
+    /**
+     * @see java.io.InputStream.skip()
+     */
+    public long skip(long n) throws IOException {
+        long skipped = 0;
+
+        while (n > 0) {
+            if (current == null) {
+                return 0;
+            }
+
+            if (current.getUsedSize() - index <= n) {
+                index += n;
+                skipped += n;
+
+                break;
+            } else {
+                int dn = current.getUsedSize() - index;
+
+                skipped += dn;
+                n -= dn;
+                current = current.getNext();
+                index = 0;
+            }
+        }
+
+        return skipped;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferOutputStream.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferOutputStream.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferOutputStream.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.io;
 
 import java.io.IOException;
@@ -28,191 +30,222 @@
 
 /**
  * Class for writing to chain of byte arrays extending OutputStream.
- *  
+ *
  * @author glory
  *
  */
 public class FastBufferOutputStream extends OutputStream {
-	/**
-	 * The beginning of the chain of byte arrays.
-	 */
-	ByteBuffer firstBuffer;
-	
-	/**
-	 * Currently filled link of the chain of byte arrays.
-	 */
-	ByteBuffer lastBuffer;
-	
-	/**
-	 * Total number of written bytes.
-	 */	
-	int length;
-	
-	/**
-	 * Creates instance of default initial capacity.
-	 */	
-	public FastBufferOutputStream() {
-		this(256);
-	}
 
-	/**
-	 * Creates instance with required initial capacity.
-	 * @param initialSize
-	 */
-	public FastBufferOutputStream(int initialSize) {
-		this(new ByteBuffer(initialSize));
-	}
-	
-	/**
-	 * Creates instance for an already existing chain of byte arrays.
-	 * @param firstBuffer
-	 */	
-	public FastBufferOutputStream(ByteBuffer firstBuffer) {
-		this.firstBuffer = firstBuffer;
-		this.lastBuffer = firstBuffer;
-	}
-	
-	/**
-	 * @see java.io.OutputStream.write(int c)
-	 */
-	public void write(int c) throws IOException {
-		lastBuffer = lastBuffer.append((byte)c);
-		length++;
-	}
+    /**
+     * The beginning of the chain of byte arrays.
+     */
+    ByteBuffer firstBuffer;
 
-	/**
-	 * @see java.io.OutputStream.write(byte b[])
-	 */
-    public void write(byte b[]) throws IOException {
-    	if (b == null) {
-    		throw new NullPointerException();
-    	}
-    	int limit = b.length;
-    	length += limit;
-    	lastBuffer = lastBuffer.append(b, 0, limit);
+    /**
+     * Currently filled link of the chain of byte arrays.
+     */
+    ByteBuffer lastBuffer;
+
+    /**
+     * Total number of written bytes.
+     */
+    int length;
+
+    /**
+     * Creates instance of default initial capacity.
+     */
+    public FastBufferOutputStream() {
+        this(256);
     }
 
-	/**
-	 * @see java.io.OutputStream.write(byte[] b, int off, int len)
-	 */
+    /**
+     * Creates instance for an already existing chain of byte arrays.
+     * @param firstBuffer
+     */
+    public FastBufferOutputStream(ByteBuffer firstBuffer) {
+        this.firstBuffer = firstBuffer;
+        this.lastBuffer = firstBuffer;
+    }
+
+    /**
+     * Creates instance with required initial capacity.
+     * @param initialSize
+     */
+    public FastBufferOutputStream(int initialSize) {
+        this(new ByteBuffer(initialSize));
+    }
+
+    /**
+     * @see java.io.OutputStream.write(int c)
+     */
+    public void write(int c) throws IOException {
+        lastBuffer = lastBuffer.append((byte) c);
+        length++;
+    }
+
+    /**
+     * @see java.io.OutputStream.write(byte b[])
+     */
+    public void write(byte[] b) throws IOException {
+        if (b == null) {
+            throw new NullPointerException();
+        }
+
+        int limit = b.length;
+
+        length += limit;
+        lastBuffer = lastBuffer.append(b, 0, limit);
+    }
+
+    /**
+     * @see java.io.OutputStream.write(byte[] b, int off, int len)
+     */
     public void write(byte[] b, int off, int len) throws IOException {
-    	if (b == null) {
-    		throw new NullPointerException();
-    	} else if ((off < 0) || (off > b.length) || (len < 0) ||
-    			((off + len) > b.length) || ((off + len) < 0)) {
-    		throw new IndexOutOfBoundsException();
-    	} else if (len == 0) {
-    		return;
-    	}
-    	lastBuffer = lastBuffer.append(b, off, len);
-    	length += len;
-	}
-    
+        if (b == null) {
+            throw new NullPointerException();
+        } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {
+            throw new IndexOutOfBoundsException();
+        } else if (len == 0) {
+            return;
+        }
+
+        lastBuffer = lastBuffer.append(b, off, len);
+        length += len;
+    }
+
     /**
      * Returns the total number of written bytes.
      * @return
      */
-	public int getLength() {
-		return length;
-	}
-	
-	/**
-	 * Returns the first link of the chain of byte arrays.
-	 * @return
-	 */	
-	public ByteBuffer getFirstBuffer() {
-		return firstBuffer;
-	}
-	
-	public byte[] toByteArray() {
-		ByteBuffer b = getFirstBuffer();
-		if(b == null) return new byte[0];
-		ByteBuffer l = b;
-		while(l.getNext() != null) l = l.getNext();
-		byte[] result = new byte[l.getTotalSize()];
-		int index = 0;
-		while(b != null) {
-			int s = b.getUsedSize();
-			System.arraycopy(b.getBytes(), 0, result, index, s);
-			index += s;
-			b = b.getNext();
-		}		
-		return result;
-	}
+    public int getLength() {
+        return length;
+    }
 
-	/**
-	 * Writes all data written up to the moment to out.
-	 * @param out
-	 * @throws IOException
-	 */
-	public void writeTo(OutputStream out) throws IOException {
-		ByteBuffer b = getFirstBuffer();
-		while(b != null) {
-			out.write(b.getBytes(), 0, b.getUsedSize());
-			b = b.getNext();
-		}
-	}
+    /**
+     * Returns the first link of the chain of byte arrays.
+     * @return
+     */
+    public ByteBuffer getFirstBuffer() {
+        return firstBuffer;
+    }
 
-	/**
-	 * Writes all data written up to the moment to out.
-	 * @param out
-	 * @throws IOException
-	 */
-	public void writeTo(Writer out,String encoding) throws IOException {
-		ByteBuffer b = getFirstBuffer();
-		while(b != null) {
-			CharBuffer c = b.toCharBuffer(encoding);
-			out.write(c.getChars(), 0, c.getUsedSize());
-			b = b.getNext();
-		}
-	}
-	/**
+    public byte[] toByteArray() {
+        ByteBuffer b = getFirstBuffer();
+
+        if (b == null) {
+            return new byte[0];
+        }
+
+        ByteBuffer l = b;
+
+        while (l.getNext() != null) {
+            l = l.getNext();
+        }
+
+        byte[] result = new byte[l.getTotalSize()];
+        int index = 0;
+
+        while (b != null) {
+            int s = b.getUsedSize();
+
+            System.arraycopy(b.getBytes(), 0, result, index, s);
+            index += s;
+            b = b.getNext();
+        }
+
+        return result;
+    }
+
+    /**
+     * Writes all data written up to the moment to out.
+     * @param out
+     * @throws IOException
+     */
+    public void writeTo(OutputStream out) throws IOException {
+        ByteBuffer b = getFirstBuffer();
+
+        while (b != null) {
+            out.write(b.getBytes(), 0, b.getUsedSize());
+            b = b.getNext();
+        }
+    }
+
+    /**
+     * Writes all data written up to the moment to out.
+     * @param out
+     * @throws IOException
+     */
+    public void writeTo(Writer out, String encoding) throws IOException {
+        ByteBuffer b = getFirstBuffer();
+
+        while (b != null) {
+            CharBuffer c = b.toCharBuffer(encoding);
+
+            out.write(c.getChars(), 0, c.getUsedSize());
+            b = b.getNext();
+        }
+    }
+
+    /**
      * Returns instance of FastBufferWriter containing all data written to this output stream.
-	 * @param encoding
-	 * @return
-	 * @throws UnsupportedEncodingException
-	 */
-	public FastBufferWriter convertToWriter(String encoding) throws UnsupportedEncodingException {
-		ByteBuffer c = firstBuffer;
-		CharBuffer first = c.toCharBuffer(encoding);
-		CharBuffer b = first;
-		while(c != null) {
-			c = c.getNext();
-			if(c == null) break;
-			CharBuffer n = c.toCharBuffer(encoding);
-			b.setNext(n);
-			b = n;
-		}
-		return new FastBufferWriter(first);
-	}
-	
-	/**
+     * @param encoding
+     * @return
+     * @throws UnsupportedEncodingException
+     */
+    public FastBufferWriter convertToWriter(String encoding) throws UnsupportedEncodingException {
+        ByteBuffer c = firstBuffer;
+        CharBuffer first = c.toCharBuffer(encoding);
+        CharBuffer b = first;
+
+        while (c != null) {
+            c = c.getNext();
+
+            if (c == null) {
+                break;
+            }
+
+            CharBuffer n = c.toCharBuffer(encoding);
+
+            b.setNext(n);
+            b = n;
+        }
+
+        return new FastBufferWriter(first);
+    }
+
+    /**
      * Returns instance of FastBufferWriter containing all data written to this output stream.
-	 * @return
-	 */
-	public FastBufferWriter convertToWriter() {
-		ByteBuffer c = firstBuffer;
-		CharBuffer first = c.toCharBuffer();
-		CharBuffer b = first;
-		while(c != null) {
-			c = c.getNext();
-			if(c == null) break;
-			CharBuffer n = c.toCharBuffer();
-			b.setNext(n);
-			b = n;
-		}
-		return new FastBufferWriter(first);
-	}
+     * @return
+     */
+    public FastBufferWriter convertToWriter() {
+        ByteBuffer c = firstBuffer;
+        CharBuffer first = c.toCharBuffer();
+        CharBuffer b = first;
 
-	/**
-	 * Resets stream to empty state
-	 * 
-	 * @since 3.3.0
-	 */
-	public void reset() {
-		this.firstBuffer.reset();
-		this.lastBuffer = this.firstBuffer;
-	
-		this.length = 0;
-	}
+        while (c != null) {
+            c = c.getNext();
+
+            if (c == null) {
+                break;
+            }
+
+            CharBuffer n = c.toCharBuffer();
+
+            b.setNext(n);
+            b = n;
+        }
+
+        return new FastBufferWriter(first);
+    }
+
+    /**
+     * Resets stream to empty state
+     *
+     * @since 3.3.0
+     */
+    public void reset() {
+        this.firstBuffer.reset();
+        this.lastBuffer = this.firstBuffer;
+        this.length = 0;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferReader.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferReader.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferReader.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.io;
 
 import java.io.IOException;
@@ -27,122 +29,152 @@
 
 /**
  * Class for reading from a char array chain.
- * 
+ *
  * @author glory
  *
  */
 public class FastBufferReader extends Reader {
-	/**
-	 * The first link in the chain of char arrays.
-	 */
-	CharBuffer firstLink;
 
-	/**
-	 * Currently read link.
-	 */
-	CharBuffer current;
+    /**
+     * Currently read link.
+     */
+    CharBuffer current;
 
-	/**
-	 * Position of next char in current link.
-	 */
-	int index;
-	
-	/**
-	 * Creates instance for given writer.
-	 * @param writer
-	 */	
-	@Deprecated
-	public FastBufferReader(FastBufferWriter writer) {
-		firstLink = writer.getFirstBuffer();
-		current = firstLink;
-		index = 0;
-	}
+    /**
+     * The first link in the chain of char arrays.
+     */
+    CharBuffer firstLink;
 
-	public FastBufferReader(CharBuffer buffer) {
-		firstLink = buffer;
-		current = firstLink;
-		index = 0;
-	}
+    /**
+     * Position of next char in current link.
+     */
+    int index;
 
-	public void close() throws IOException {
-	}
-	
-	/**
-	 * @see java.io.Reader.read()
-	 */
-	public int read() throws IOException {
-		if(current == null) return -1;
-		if(current.getUsedSize() <= index) {
-			current = current.getNext();
-			if(current == null) return -1;
-			index = 0;
-		}
-		char c = current.getCharAt(index);
-		index++;
-		return c;
-	}
+    public FastBufferReader(CharBuffer buffer) {
+        firstLink = buffer;
+        current = firstLink;
+        index = 0;
+    }
 
-	/**
-	 * @see java.io.Reader.read(char[] cbuf, int off, int len)
-	 */
-	public int read(char[] cbuf, int off, int len) throws IOException {
-        if ((off < 0) || (off > cbuf.length) || (len < 0) ||
-                ((off + len) > cbuf.length) || ((off + len) < 0)) {
-                throw new IndexOutOfBoundsException();
-            } else if (len == 0) {
-                return 0;
+    /**
+     * Creates instance for given writer.
+     * @param writer
+     */
+    @Deprecated
+    public FastBufferReader(FastBufferWriter writer) {
+        firstLink = writer.getFirstBuffer();
+        current = firstLink;
+        index = 0;
+    }
+
+    public void close() throws IOException {}
+
+    /**
+     * @see java.io.Reader.read()
+     */
+    public int read() throws IOException {
+        if (current == null) {
+            return -1;
+        }
+
+        if (current.getUsedSize() <= index) {
+            current = current.getNext();
+
+            if (current == null) {
+                return -1;
             }
-        if(current == null) return -1;
-		int actuallyRead = 0;
-		while(current != null && len > 0) {
-			int av = current.getUsedSize() - index;
-			if(av <= 0) {
-				current = current.getNext();
-				index = 0;
-				continue;
-			}
-			if(av > len) av = len;
-			System.arraycopy(current.getChars(), index, cbuf, off, av);
-			index += av;
-			off += av;
-			actuallyRead += av;
-			len -= av;
-		}
-		return actuallyRead == 0 ? -1 : actuallyRead;
-	}
-	
-	/**
-	 * Returns the number of chars that may be read from this storage.
-	 * @return
-	 * @throws IOException
-	 */
-	public int available() throws IOException {
-		if(current == null) return 0;
-		CharBuffer b = current;
-		int result = -index;
-		while(b != null) {
-			result += b.getUsedSize();
-			b = b.getNext();
-		}
-		return result;
-	}
-	
-	/** Writes rest of data written up to the moment to out.
-	 * @param out
-	 * @throws IOException
-	 */
-	public void writeTo(Writer writer) throws IOException {
-		if(current == null) return ;
-		if(current.getUsedSize() > index) {
-			writer.write(current.getChars(), index, current.getUsedSize()-index);
-			current = current.getNext();
-		}
-		while(current != null) {
-			writer.write(current.getChars(), 0, current.getUsedSize());
-			current = current.getNext();
-		}
-		index = 0;
-	}
 
-	
+            index = 0;
+        }
+
+        char c = current.getCharAt(index);
+
+        index++;
+
+        return c;
+    }
+
+    /**
+     * @see java.io.Reader.read(char[] cbuf, int off, int len)
+     */
+    public int read(char[] cbuf, int off, int len) throws IOException {
+        if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) {
+            throw new IndexOutOfBoundsException();
+        } else if (len == 0) {
+            return 0;
+        }
+
+        if (current == null) {
+            return -1;
+        }
+
+        int actuallyRead = 0;
+
+        while ((current != null) && (len > 0)) {
+            int av = current.getUsedSize() - index;
+
+            if (av <= 0) {
+                current = current.getNext();
+                index = 0;
+
+                continue;
+            }
+
+            if (av > len) {
+                av = len;
+            }
+
+            System.arraycopy(current.getChars(), index, cbuf, off, av);
+            index += av;
+            off += av;
+            actuallyRead += av;
+            len -= av;
+        }
+
+        return (actuallyRead == 0) ? -1 : actuallyRead;
+    }
+
+    /**
+     * Returns the number of chars that may be read from this storage.
+     * @return
+     * @throws IOException
+     */
+    public int available() throws IOException {
+        if (current == null) {
+            return 0;
+        }
+
+        CharBuffer b = current;
+        int result = -index;
+
+        while (b != null) {
+            result += b.getUsedSize();
+            b = b.getNext();
+        }
+
+        return result;
+    }
+
+    /**
+     * Writes rest of data written up to the moment to out.
+     * @param out
+     * @throws IOException
+     */
+    public void writeTo(Writer writer) throws IOException {
+        if (current == null) {
+            return;
+        }
+
+        if (current.getUsedSize() > index) {
+            writer.write(current.getChars(), index, current.getUsedSize() - index);
+            current = current.getNext();
+        }
+
+        while (current != null) {
+            writer.write(current.getChars(), 0, current.getUsedSize());
+            current = current.getNext();
+        }
+
+        index = 0;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferWriter.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferWriter.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/FastBufferWriter.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.io;
 
 import java.io.IOException;
@@ -29,200 +31,226 @@
 
 /**
  * Class for writing to chain of char arrays extending Writer.
- *  
+ *
  * @author glory
  *
  */
 public class FastBufferWriter extends Writer {
-	/**
-	 * The beginning of the chain of char arrays.
-	 */
-	CharBuffer firstBuffer;
 
-	/**
-	 * Currently filled link of the chain of char arrays.
-	 */
-	CharBuffer lastBuffer;
-	
-	/**
-	 * Total number of written chars.
-	 */	
-	int length;
-	
-	/**
-	 * Creates instance of default initial capacity.
-	 */	
-	public FastBufferWriter() {
-		this(256);
-	}
-	
-	/**
-	 * Creates instance with required initial capacity.
-	 * @param initialSize
-	 */
-	public FastBufferWriter(int initialSize) {
-		this(new CharBuffer(initialSize));
-	}
-	
-	/**
-	 * Creates instance for an already existing chain of char arrays.
-	 * @param firstBuffer
-	 */	
-	public FastBufferWriter(CharBuffer firstBuffer) {
-		this.firstBuffer = firstBuffer;
-		lastBuffer = firstBuffer;
-	}
-	
-	/**
-	 * @see java.io.Writer.write(int c)
-	 */
-	public void write(int c) throws IOException {
-		lastBuffer = lastBuffer.append((char)c);
-		length++;
-	}
+    /**
+     * The beginning of the chain of char arrays.
+     */
+    CharBuffer firstBuffer;
 
-	/**
-	 * @see java.io.Writer.write(char cbuf[])
-	 */
-	public void write(char cbuf[]) throws IOException {
-    	if(cbuf == null) {
-    		throw new NullPointerException();
-    	}
+    /**
+     * Currently filled link of the chain of char arrays.
+     */
+    CharBuffer lastBuffer;
 
-    	lastBuffer = lastBuffer.append(cbuf, 0, cbuf.length);
-    	length += cbuf.length;
-    	
-	}
+    /**
+     * Total number of written chars.
+     */
+    int length;
 
-	/**
-	 * @see java.io.Writer.write(char cbuf[], int off, int len)
-	 */
+    /**
+     * Creates instance of default initial capacity.
+     */
+    public FastBufferWriter() {
+        this(256);
+    }
+
+    /**
+     * Creates instance for an already existing chain of char arrays.
+     * @param firstBuffer
+     */
+    public FastBufferWriter(CharBuffer firstBuffer) {
+        this.firstBuffer = firstBuffer;
+        lastBuffer = firstBuffer;
+    }
+
+    /**
+     * Creates instance with required initial capacity.
+     * @param initialSize
+     */
+    public FastBufferWriter(int initialSize) {
+        this(new CharBuffer(initialSize));
+    }
+
+    /**
+     * @see java.io.Writer.write(int c)
+     */
+    public void write(int c) throws IOException {
+        lastBuffer = lastBuffer.append((char) c);
+        length++;
+    }
+
+    /**
+     * @see java.io.Writer.write(char cbuf[])
+     */
+    public void write(char[] cbuf) throws IOException {
+        if (cbuf == null) {
+            throw new NullPointerException();
+        }
+
+        lastBuffer = lastBuffer.append(cbuf, 0, cbuf.length);
+        length += cbuf.length;
+    }
+
+    /**
+     * @see java.io.Writer.write(char cbuf[], int off, int len)
+     */
     public void write(char[] cbuf, int off, int len) throws IOException {
-    	if(cbuf == null) {
-    		throw new NullPointerException();
-    	}
-		if ((off < 0) || (off > cbuf.length) || (len < 0) ||
-				((off + len) > cbuf.length) || ((off + len) < 0)) {
-				throw new IndexOutOfBoundsException();
-		} else if (len == 0) {
-			return;
-		}
-    	lastBuffer = lastBuffer.append(cbuf, off, len);
-    	length += len;
+        if (cbuf == null) {
+            throw new NullPointerException();
+        }
 
-	}
-	
+        if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) {
+            throw new IndexOutOfBoundsException();
+        } else if (len == 0) {
+            return;
+        }
+
+        lastBuffer = lastBuffer.append(cbuf, off, len);
+        length += len;
+    }
+
     /**
      * Returns the total number of written chars.
      * @return
      */
-	public int getLength() {
-		return length;
-	}
-	
-	/**
-	 * Returns the first link of the chain of char arrays.
-	 * @return
-	 */	
-	public CharBuffer getFirstBuffer() {
-		return firstBuffer;
-	}
+    public int getLength() {
+        return length;
+    }
 
-	public void close() throws IOException {
-	}
+    /**
+     * Returns the first link of the chain of char arrays.
+     * @return
+     */
+    public CharBuffer getFirstBuffer() {
+        return firstBuffer;
+    }
 
-	public void flush() throws IOException {
-	}
-	
-	/**
-	 * Writes all data written up to the moment to string buffer.
-	 * @param out
-	 * @throws IOException
-	 */
-	public char[] toCharArray() {
-		CharBuffer b = firstBuffer;
-		if(b == null) return new char[0];
-		CharBuffer l = b;
-		while(l.getNext() != null) l = l.getNext();
-		char[] result = new char[l.getTotalSize()];
-		int index = 0;
-		while(b != null) {
-			int s = b.getUsedSize();
-			System.arraycopy(b.getChars(), 0, result, index, s);
-			index += s;
-			b = b.getNext();
-		}		
-		return result;
-	}
+    @Override
+    public void close() throws IOException {}
 
-	/**
-	 * Writes all data written up to the moment to out.
-	 * @param out
-	 * @throws IOException
-	 */
-	public void writeTo(Writer writer) throws IOException {
-		CharBuffer b = firstBuffer;
-		while(b != null) {
-			writer.write(b.getChars(), 0, b.getUsedSize());
-			b = b.getNext();
-		}
-	}
-	
-	public void printTo(ServletOutputStream outputStream) throws IOException {
-		CharBuffer b = firstBuffer;
-		while(b != null) {
-			outputStream.print(new String(b.getChars()));
-			b = b.getNext();
-		}
-	}
+    @Override
+    public void flush() throws IOException {}
 
-	/**
+    /**
+     * Writes all data written up to the moment to string buffer.
+     * @param out
+     * @throws IOException
+     */
+    public char[] toCharArray() {
+        CharBuffer b = firstBuffer;
+
+        if (b == null) {
+            return new char[0];
+        }
+
+        CharBuffer l = b;
+
+        while (l.getNext() != null) {
+            l = l.getNext();
+        }
+
+        char[] result = new char[l.getTotalSize()];
+        int index = 0;
+
+        while (b != null) {
+            int s = b.getUsedSize();
+
+            System.arraycopy(b.getChars(), 0, result, index, s);
+            index += s;
+            b = b.getNext();
+        }
+
+        return result;
+    }
+
+    /**
+     * Writes all data written up to the moment to out.
+     * @param out
+     * @throws IOException
+     */
+    public void writeTo(Writer writer) throws IOException {
+        CharBuffer b = firstBuffer;
+
+        while (b != null) {
+            writer.write(b.getChars(), 0, b.getUsedSize());
+            b = b.getNext();
+        }
+    }
+
+    public void printTo(ServletOutputStream outputStream) throws IOException {
+        CharBuffer b = firstBuffer;
+
+        while (b != null) {
+            outputStream.print(new String(b.getChars()));
+            b = b.getNext();
+        }
+    }
+
+    /**
      * Returns instance of FastBufferOutputStream containing all data written to this writer.
-	 * @param encoding
-	 * @return
-	 * @throws UnsupportedEncodingException
-	 */
-	public FastBufferOutputStream convertToOutputStream(String encoding) throws UnsupportedEncodingException {
-		CharBuffer c = firstBuffer;
-		ByteBuffer first = c.toByteBuffer(encoding);
-		ByteBuffer b = first;
-		while(c != null) {
-			c = c.getNext();
-			if(c == null) break;
-			ByteBuffer n = c.toByteBuffer(encoding);
-			b.setNext(n);
-			b = n;
-		}
-		return new FastBufferOutputStream(first);
-	}
+     * @param encoding
+     * @return
+     * @throws UnsupportedEncodingException
+     */
+    public FastBufferOutputStream convertToOutputStream(String encoding) throws UnsupportedEncodingException {
+        CharBuffer c = firstBuffer;
+        ByteBuffer first = c.toByteBuffer(encoding);
+        ByteBuffer b = first;
 
-	/**
+        while (c != null) {
+            c = c.getNext();
+
+            if (c == null) {
+                break;
+            }
+
+            ByteBuffer n = c.toByteBuffer(encoding);
+
+            b.setNext(n);
+            b = n;
+        }
+
+        return new FastBufferOutputStream(first);
+    }
+
+    /**
      * Returns instance of FastBufferOutputStream containing all data written to this writer.
-	 * @return
-	 */
-	public FastBufferOutputStream convertToOutputStream() {
-		CharBuffer c = firstBuffer;
-		ByteBuffer first = c.toByteBuffer();
-		ByteBuffer b = first;
-		while(c != null) {
-			c = c.getNext();
-			if(c == null) break;
-			ByteBuffer n = c.toByteBuffer();
-			b.setNext(n);
-			b = n;
-		}
-		return new FastBufferOutputStream(first);
-	}
+     * @return
+     */
+    public FastBufferOutputStream convertToOutputStream() {
+        CharBuffer c = firstBuffer;
+        ByteBuffer first = c.toByteBuffer();
+        ByteBuffer b = first;
 
-	/**
-	 * Resets writer to empty state
-	 * 
-	 * @since 3.3.0
-	 */
-	public void reset() {
-		this.firstBuffer.reset();
-		this.lastBuffer = this.firstBuffer;
-	
-		this.length = 0;
-	}
+        while (c != null) {
+            c = c.getNext();
+
+            if (c == null) {
+                break;
+            }
+
+            ByteBuffer n = c.toByteBuffer();
+
+            b.setNext(n);
+            b = n;
+        }
+
+        return new FastBufferOutputStream(first);
+    }
+
+    /**
+     * Resets writer to empty state
+     *
+     * @since 3.3.0
+     */
+    public void reset() {
+        this.firstBuffer.reset();
+        this.lastBuffer = this.firstBuffer;
+        this.length = 0;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/SAXResponseWriter.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/SAXResponseWriter.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/SAXResponseWriter.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,73 +18,70 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.io;
 
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.ext.LexicalHandler;
+import org.xml.sax.helpers.AttributesImpl;
+
 import java.io.IOException;
 import java.io.Writer;
 
 import javax.faces.component.UIComponent;
 import javax.faces.context.ResponseWriter;
 
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-import org.xml.sax.ext.LexicalHandler;
-import org.xml.sax.helpers.AttributesImpl;
-
 /**
  * @author shura
- * 
+ *
  * Realization of Faces <code>ResponseWriter</code> for Cocoon Environment.
  * Use ONLY Markup-specific calls , send it as SAX events to
  * <code>XMLConsumer</code> Use "State" pattern for control of events flow.
  * TODO - implement namespace capabilites
- *  
+ *
  */
 public class SAXResponseWriter extends ResponseWriter {
 
     /**
-     * As we in XML framework, only xml supported for <code>CONTENT_TYPE</code>
-     */
-    static final private String CONTENT_TYPE = "text/xml";
-
-    /**
      * As we in XML framework, only UTF-8 supported for
      * <code>CHARTER_ENCODING</code>
      */
-    static final private String CHARTER_ENCODING = "UTF-8";
+    private static final String CHARTER_ENCODING = "UTF-8";
 
     /**
-     * Hold Cocoon Generator XML <code>consumer</code>
+     * As we in XML framework, only xml supported for <code>CONTENT_TYPE</code>
      */
-    private ContentHandler xmlConsumer;
-    
+    private static final String CONTENT_TYPE = "text/xml";
+    private String namespaceURI = "http://www.w3.org/1999/xhtml";
     private LexicalHandler xmlLexicalHandler = null;
-    
-    private String namespaceURI = "http://www.w3.org/1999/xhtml";
-
+    private AttributesImpl attributes;
+    private XMLResponseWriterState cdataState;
     private String element;
 
-    private AttributesImpl attributes;
-
-    private XMLResponseWriterState state;
-
     /**
-     * Before StartDocument or after EndDocument <code>notDocumentState</code>
+     * State after startElement. Collect Attributes for SAX startElement
+     * <code>elementState</code>
      */
-    private XMLResponseWriterState notDocumentState;
+    private XMLResponseWriterState elementState;
 
     /**
      * State in normal document <code>inDocumentState</code>
      */
     private XMLResponseWriterState inDocumentState;
 
-    private XMLResponseWriterState cdataState;
+    /**
+     * Before StartDocument or after EndDocument <code>notDocumentState</code>
+     */
+    private XMLResponseWriterState notDocumentState;
+    private XMLResponseWriterState state;
 
     /**
-     * State after startElement. Collect Attributes for SAX startElement
-     * <code>elementState</code>
+     * Hold Cocoon Generator XML <code>consumer</code>
      */
-    private XMLResponseWriterState elementState;
+    private ContentHandler xmlConsumer;
 
     /**
      * @param consumer -
@@ -93,41 +90,45 @@
     public SAXResponseWriter(ContentHandler consumer) {
         super();
         this.xmlConsumer = consumer;
+
         if (consumer instanceof LexicalHandler) {
-			 xmlLexicalHandler = (LexicalHandler) consumer;
-		}
+            xmlLexicalHandler = (LexicalHandler) consumer;
+        }
+
         // Initialise states. May be must implemented in static block ?
         this.notDocumentState = new NotDocumentState();
+
         // inside document. allow any events exclude attributes and
         // startDocument.
         this.inDocumentState = new InDocumentState();
         this.cdataState = new CDATAState();
+
         // In element, collect attributes ...
         this.elementState = new ElementState();
         this.state = notDocumentState;
     }
 
     public ContentHandler getXmlConsumer() {
-		return xmlConsumer;
-	}
+        return xmlConsumer;
+    }
 
     /**
-	 * @return Returns the namespaceURI.
-	 */
-	public String getNamespaceURI() {
-		return namespaceURI;
-	}
+     * @return Returns the namespaceURI.
+     */
+    public String getNamespaceURI() {
+        return namespaceURI;
+    }
 
-	/**
-	 * @param namespaceURI The namespaceURI to set.
-	 */
-	public void setNamespaceURI(String namespaceURI) {
-		this.namespaceURI = namespaceURI;
-	}
+    /**
+     * @param namespaceURI The namespaceURI to set.
+     */
+    public void setNamespaceURI(String namespaceURI) {
+        this.namespaceURI = namespaceURI;
+    }
 
-	/*
+    /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#getContentType()
      */
     public String getContentType() {
@@ -136,7 +137,7 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#getCharacterEncoding()
      */
     public String getCharacterEncoding() {
@@ -145,49 +146,45 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see java.io.Flushable#flush()
      */
     public void flush() throws IOException {
+
         // DO NOTHING...
-
     }
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#startDocument()
      */
     public void startDocument() throws IOException {
         state.startDocument();
-
     }
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#endDocument()
      */
     public void endDocument() throws IOException {
         state.endDocument();
-
     }
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#startElement(java.lang.String,
      *      javax.faces.component.UIComponent)
      */
-    public void startElement(String name, UIComponent component)
-            throws IOException {
+    public void startElement(String name, UIComponent component) throws IOException {
         state.startElement(name, component);
-
     }
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#endElement(java.lang.String)
      */
     public void endElement(String name) throws IOException {
@@ -196,29 +193,27 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#writeAttribute(java.lang.String,
      *      java.lang.Object, java.lang.String)
      */
-    public void writeAttribute(String name, Object value, String property)
-            throws IOException {
+    public void writeAttribute(String name, Object value, String property) throws IOException {
         state.writeAttribute(name, value, property);
     }
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#writeURIAttribute(java.lang.String,
      *      java.lang.Object, java.lang.String)
      */
-    public void writeURIAttribute(String name, Object value, String property)
-            throws IOException {
+    public void writeURIAttribute(String name, Object value, String property) throws IOException {
         state.writeURIAttribute(name, value, property);
     }
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#writeComment(java.lang.Object)
      */
     public void writeComment(Object comment) throws IOException {
@@ -227,7 +222,7 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#writeText(java.lang.Object,
      *      java.lang.String)
      */
@@ -237,7 +232,7 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#writeText(char[], int, int)
      */
     public void writeText(char[] text, int off, int len) throws IOException {
@@ -246,10 +241,11 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see javax.faces.context.ResponseWriter#cloneWithWriter(java.io.Writer)
      */
     public ResponseWriter cloneWithWriter(Writer writer) {
+
         // TODO as used XML consumer to get sax Events, we simple return current
         // instance.
         // if will used wrapper to combine XML Consumer with plain Servlet
@@ -261,7 +257,7 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see java.io.Writer#write(char[], int, int)
      */
     public void write(char[] cbuf, int off, int len) throws IOException {
@@ -270,142 +266,153 @@
 
     /*
      * (non-Javadoc)
-     * 
+     *
      * @see java.io.Closeable#close()
      */
     public void close() throws IOException {
+
         // TODO Auto-generated method stub
-
     }
 
-    // Private classes
     /**
      * @author shura
-     * 
-     * state before startDocument - only allow startDocument.
+     *
+     * CDATA section. allow regular write() functions, write any text.
      */
-    private final class NotDocumentState extends XMLResponseWriterState {
+    private final class CDATAState extends XMLResponseWriterState {
+        void flushCDATA() throws IOException {
+
+            // try {
+            // xmlConsumer.endCDATA();
+            // } catch (SAXException e) {
+            // throw new IOException("Exception in endCDATA: "+ e.getMessage());
+            // }
+        }
+
         /*
          * (non-Javadoc)
-         * 
-         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#startDocument()
+         *
+         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#endDocument()
          */
-        void startDocument() throws IOException {
-            try {
-                // 
-                xmlConsumer.startDocument();
-            } catch (SAXException e) {
-                // 
-                throw new IOException("StartDocument SAX exception :"
-                        + e.getMessage());
-            } finally {
-                state = inDocumentState;
-            }
+        void endDocument() throws IOException {
+            flushCDATA();
+            state = inDocumentState;
+            state.endDocument();
         }
-    }
 
-    /**
-     * @author shura
-     * 
-     * State in regular document. Disabled attributes & startDocument.
-     */
-    private final class InDocumentState extends XMLResponseWriterState {
-        void startElement(String name, UIComponent component) {
+        /*
+         * (non-Javadoc)
+         *
+         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#endElement(java.lang.String)
+         */
+        void endElement(String name) throws IOException {
+            flushCDATA();
+            state = inDocumentState;
+            state.endElement(name);
+        }
+
+        /*
+         * (non-Javadoc)
+         *
+         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#startElement(java.lang.String,
+         *      javax.faces.component.UIComponent)
+         */
+        void startElement(String name, UIComponent component) throws IOException {
+            flushCDATA();
             element = name;
             attributes = new AttributesImpl();
             state = elementState;
+        }
 
+        /*
+         * (non-Javadoc)
+         *
+         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeComment(java.lang.Object)
+         */
+        void writeComment(Object comment) throws IOException {
+            flushCDATA();
+            state = inDocumentState;
+            state.writeComment(comment);
         }
 
-        void writeComment(Object comment) throws IOException {
-            String remark = comment.toString();
+        /*
+         * (non-Javadoc)
+         *
+         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeText(char[],
+         *      int, int)
+         */
+        void writeText(char[] text, int off, int len) throws IOException {
             try {
-                xmlLexicalHandler.comment(remark.toCharArray(), 0, remark.length());
+                xmlConsumer.characters(text, off, len);
             } catch (SAXException e) {
-                throw new IOException("Comment SAX exception :"
-                        + e.getMessage());
+                throw new IOException("Sax exceptions in writeText: " + e.getMessage());
             }
         }
 
-        void writeText(Object o, String property) throws IOException {
-            writeText(o.toString().toCharArray(), 0, o.toString().length());
+        /*
+         * (non-Javadoc)
+         *
+         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeText(java.lang.Object,
+         *      java.lang.String)
+         */
+        void writeText(Object text, String property) throws IOException {
+            writeText(text.toString().toCharArray(), 0, text.toString().length());
         }
 
-        void writeText(char[] text, int start, int lenght) throws IOException {
-            //			try {
-            //				xmlConsumer.startCDATA();
-            //			} catch (SAXException e) {
-            //				throw new IOException("Sax exceptions in writeText: "+
-            // e.getMessage());
-            //			} finally {
-            state = cdataState;
-            //			}
-            state.writeText(text, start, lenght);
+        /*
+         * (non-Javadoc)
+         *
+         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#write(char[],
+         *      int, int)
+         */
+        void write(char[] cbuf, int off, int len) throws IOException {
+            writeText(cbuf, off, len);
         }
+    }
 
-        void endElement(String name) throws IOException {
-            try {
-                xmlConsumer.endElement(getNamespaceURI(), name, name);
-            } catch (SAXException e) {
-                throw new IOException("Sax exceptions in endElement: "
-                        + e.getMessage());
-            }
-        }
 
-        void endDocument() throws IOException {
-            try {
-                xmlConsumer.endDocument();
-            } catch (SAXException e) {
-                throw new IOException("Sax exceptions in endDocument"
-                        + e.getMessage());
-            } finally {
-                // after endDocument all events disabled ...
-                state = new XMLResponseWriterState();
-            }
-        }
-    }
-
     /**
      * @author shura State in element declsration. Collect attributes, on any
      *         other eventss - generate SAX startElement()
      */
     private final class ElementState extends XMLResponseWriterState {
+
         /**
          * Generate SAX StartElement event
-         * 
+         *
          * @throws IOException
          */
         void flushElement() throws IOException {
             try {
                 xmlConsumer.startElement(getNamespaceURI(), element, element, attributes);
             } catch (SAXException e) {
-                throw new IOException("Exception in startElement: "
-                        + e.getMessage());
+                throw new IOException("Exception in startElement: " + e.getMessage());
             } finally {
                 element = null;
                 attributes = null;
             }
         }
 
-        void writeAttribute(String name, Object value, String property)
-                throws IOException {
-            attributes.addAttribute(getNamespaceURI(), name, name, "id".equalsIgnoreCase(name)?"ID":"CDATA", value.toString());
+        void writeAttribute(String name, Object value, String property) throws IOException {
+            attributes.addAttribute(getNamespaceURI(), name, name, "id".equalsIgnoreCase(name) ? "ID" : "CDATA",
+                                    value.toString());
         }
 
-        void writeURIAttribute(String name, Object value, String property)
-                throws IOException {
+        void writeURIAttribute(String name, Object value, String property) throws IOException {
             String uri = value.toString();
+
             // TODO - perform encodeActionURL() or ???
             attributes.addAttribute(getNamespaceURI(), name, name, "CDATA", uri);
         }
 
         /*
          * (non-Javadoc)
-         * 
+         *
          * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#endElement(java.lang.String)
          */
         void endElement(String name) throws IOException {
-            // 
+
+            //
             flushElement();
             state = inDocumentState;
             state.endElement(name);
@@ -413,13 +420,13 @@
 
         /*
          * (non-Javadoc)
-         * 
+         *
          * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#startElement(java.lang.String,
          *      javax.faces.component.UIComponent)
          */
-        void startElement(String name, UIComponent component)
-                throws IOException {
-            // 
+        void startElement(String name, UIComponent component) throws IOException {
+
+            //
             flushElement();
             element = name;
             attributes = new AttributesImpl();
@@ -427,10 +434,11 @@
 
         /*
          * (non-Javadoc)
-         * 
+         *
          * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeComment(java.lang.Object)
          */
         void writeComment(Object comment) throws IOException {
+
             // TODO Auto-generated method stub
             flushElement();
             state = inDocumentState;
@@ -439,11 +447,12 @@
 
         /*
          * (non-Javadoc)
-         * 
+         *
          * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeText(char[],
          *      int, int)
          */
         void writeText(char[] text, int off, int len) throws IOException {
+
             // TODO Auto-generated method stub
             flushElement();
             state = cdataState;
@@ -452,11 +461,12 @@
 
         /*
          * (non-Javadoc)
-         * 
+         *
          * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeText(java.lang.Object,
          *      java.lang.String)
          */
         void writeText(Object text, String property) throws IOException {
+
             // TODO Auto-generated method stub
             flushElement();
             state = cdataState;
@@ -464,103 +474,95 @@
         }
     }
 
+
     /**
      * @author shura
-     * 
-     * CDATA section. allow regular write() functions, write any text.
+     *
+     * State in regular document. Disabled attributes & startDocument.
      */
-    private final class CDATAState extends XMLResponseWriterState {
-
-        void flushCDATA() throws IOException {
-            //			try {
-            //				xmlConsumer.endCDATA();
-            //			} catch (SAXException e) {
-            //				throw new IOException("Exception in endCDATA: "+ e.getMessage());
-            //			}
+    private final class InDocumentState extends XMLResponseWriterState {
+        void startElement(String name, UIComponent component) {
+            element = name;
+            attributes = new AttributesImpl();
+            state = elementState;
         }
 
-        /*
-         * (non-Javadoc)
-         * 
-         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#endDocument()
-         */
-        void endDocument() throws IOException {
-            flushCDATA();
-            state = inDocumentState;
-            state.endDocument();
+        void writeComment(Object comment) throws IOException {
+            String remark = comment.toString();
+
+            try {
+                xmlLexicalHandler.comment(remark.toCharArray(), 0, remark.length());
+            } catch (SAXException e) {
+                throw new IOException("Comment SAX exception :" + e.getMessage());
+            }
         }
 
-        /*
-         * (non-Javadoc)
-         * 
-         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#endElement(java.lang.String)
-         */
-        void endElement(String name) throws IOException {
-            flushCDATA();
-            state = inDocumentState;
-            state.endElement(name);
+        void writeText(Object o, String property) throws IOException {
+            writeText(o.toString().toCharArray(), 0, o.toString().length());
         }
 
-        /*
-         * (non-Javadoc)
-         * 
-         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#startElement(java.lang.String,
-         *      javax.faces.component.UIComponent)
-         */
-        void startElement(String name, UIComponent component)
-                throws IOException {
-            flushCDATA();
-            element = name;
-            attributes = new AttributesImpl();
-            state = elementState;
+        void writeText(char[] text, int start, int lenght) throws IOException {
+
+            // try {
+            // xmlConsumer.startCDATA();
+            // } catch (SAXException e) {
+            // throw new IOException("Sax exceptions in writeText: "+
+            // e.getMessage());
+            // } finally {
+            state = cdataState;
+
+            // }
+            state.writeText(text, start, lenght);
         }
 
-        /*
-         * (non-Javadoc)
-         * 
-         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeComment(java.lang.Object)
-         */
-        void writeComment(Object comment) throws IOException {
-            flushCDATA();
-            state = inDocumentState;
-            state.writeComment(comment);
+        void endElement(String name) throws IOException {
+            try {
+                xmlConsumer.endElement(getNamespaceURI(), name, name);
+            } catch (SAXException e) {
+                throw new IOException("Sax exceptions in endElement: " + e.getMessage());
+            }
         }
 
-        /*
-         * (non-Javadoc)
-         * 
-         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeText(char[],
-         *      int, int)
-         */
-        void writeText(char[] text, int off, int len) throws IOException {
+        void endDocument() throws IOException {
             try {
-                xmlConsumer.characters(text, off, len);
+                xmlConsumer.endDocument();
             } catch (SAXException e) {
-                throw new IOException("Sax exceptions in writeText: "
-                        + e.getMessage());
+                throw new IOException("Sax exceptions in endDocument" + e.getMessage());
+            } finally {
+
+                // after endDocument all events disabled ...
+                state = new XMLResponseWriterState();
             }
         }
+    }
 
+
+    // Private classes
+
+    /**
+     * @author shura
+     *
+     * state before startDocument - only allow startDocument.
+     */
+    private final class NotDocumentState extends XMLResponseWriterState {
+
         /*
          * (non-Javadoc)
-         * 
-         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#writeText(java.lang.Object,
-         *      java.lang.String)
+         *
+         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#startDocument()
          */
-        void writeText(Object text, String property) throws IOException {
-            writeText(text.toString().toCharArray(), 0, text.toString()
-                    .length());
-        }
+        void startDocument() throws IOException {
+            try {
 
-        /*
-         * (non-Javadoc)
-         * 
-         * @see org.apache.cocoon.components.faces.context.XMLResponseWriterState#write(char[],
-         *      int, int)
-         */
-        void write(char[] cbuf, int off, int len) throws IOException {
-            writeText(cbuf, off, len);
+                //
+                xmlConsumer.startDocument();
+            } catch (SAXException e) {
+
+                //
+                throw new IOException("StartDocument SAX exception :" + e.getMessage());
+            } finally {
+                state = inDocumentState;
+            }
         }
     }
-    
-}
\ No newline at end of file
+}

Deleted: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/Test.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/Test.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/Test.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,231 +0,0 @@
-/**
- * License Agreement.
- *
- * Rich Faces - Natural Ajax for Java Server Faces (JSF)
- *
- * Copyright (C) 2007 Exadel, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License version 2.1 as published by the Free Software Foundation.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
- */
-
-package org.ajax4jsf.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.StringWriter;
-
-public class Test {
-	static int ARRAY_LENGTH = 27;
-	static int READ_OFF = 4;
-	static int READ_LENGTH = 22;
-	
-	static boolean BUILD_STRING = false;
-	static boolean OUT_STRING = true;
-	
-	static void testStreams() throws IOException {
-		String s = "This is a senseless text to test streams.\n";
-		for (int i = 0; i < 10; i++) s = s + s; //repeated 16 times 
-		byte[] bytes = s.getBytes();
-		
-		FastBufferOutputStream output = new FastBufferOutputStream(16);
-		//write it several times.
-		for (int i = 0; i < 4; i++) output.write(bytes);
-		//write it one more time by one byte
-		for (int i = 0; i < bytes.length; i++) {
-			output.write(bytes[i]);
-		}
-		FastBufferInputStream input = new FastBufferInputStream(output);
-		StringBuffer sb = new StringBuffer();
-		//use for reading unconvenient array length.
-		byte[] bs = new byte[ARRAY_LENGTH];
-		int l = 0;
-		while((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
-			if(BUILD_STRING) sb.append(new String(bs, READ_OFF, l));
-		}
-		if(BUILD_STRING && OUT_STRING) {
-			System.out.println(sb);
-			System.out.println("Length=" + output.getLength());
-		}
-	}
-	
-	static void testStandardStreams() throws IOException {
-		String s = "This is a senseless text to test streams.\n";
-		for (int i = 0; i < 10; i++) s = s + s; //repeated 16 times 
-		byte[] bytes = s.getBytes();
-		
-		ByteArrayOutputStream output = new ByteArrayOutputStream(16);
-		//write it several times.
-		for (int i = 0; i < 4; i++) output.write(bytes);
-		//write it one more time by one byte
-		for (int i = 0; i < bytes.length; i++) {
-			output.write(bytes[i]);
-		}
-		ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
-		StringBuffer sb = new StringBuffer();
-		//use for reading unconvenient array length.
-		byte[] bs = new byte[ARRAY_LENGTH];
-		int l = 0;
-		while((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
-			if(BUILD_STRING) sb.append(new String(bs, READ_OFF, l));
-		}
-		if(BUILD_STRING && OUT_STRING) System.out.println(sb);
-	}
-
-
-	static void testReaders() throws IOException {
-		String s = "This is a senseless text to test readers.\n";
-		for (int i = 0; i < 10; i++) s = s + s; //repeated 16 times 
-		char[] bytes = s.toCharArray();
-		
-		FastBufferWriter output = new FastBufferWriter(16);
-		//write it several times.
-		for (int i = 0; i < 4; i++) output.write(bytes);
-		//write it one more time by one byte
-		for (int i = 0; i < bytes.length; i++) {
-			output.write(bytes[i]);
-		}
-		FastBufferReader input = new FastBufferReader(output);
-		StringBuffer sb = new StringBuffer();
-		//use for reading unconvenient array length.
-		char[] bs = new char[ARRAY_LENGTH];
-		int l = 0;
-		while((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
-			if(BUILD_STRING) sb.append(new String(bs, READ_OFF, l));
-		}
-		if(BUILD_STRING && OUT_STRING) System.out.println(sb);
-	}
-
-	static void testStandardReaders() throws IOException {
-		String s = "This is a senseless text to test readers.\n";
-		for (int i = 0; i < 10; i++) s = s + s; //repeated 16 times 
-		char[] bytes = s.toCharArray();
-		
-		StringWriter output = new StringWriter(16);
-		//write it several times.
-		for (int i = 0; i < 4; i++) output.write(bytes);
-		//write it one more time by one byte
-		for (int i = 0; i < bytes.length; i++) {
-			output.write(bytes[i]);
-		}
-		StringReader input = new StringReader(output.toString());
-		StringBuffer sb = new StringBuffer();
-		//use for reading unconvenient array length.
-		char[] bs = new char[ARRAY_LENGTH];
-		int l = 0;
-		while((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
-			if(BUILD_STRING) sb.append(new String(bs, READ_OFF, l));
-		}
-		if(BUILD_STRING && OUT_STRING) System.out.println(sb);
-	}
-
-	static void testTransitionFromWriterToStream() throws IOException {
-		String s = "This is a senseless text to test transform from writer to stream.\n";
-		for (int i = 0; i < 10; i++) s = s + s; //repeated 16 times 
-		char[] bytes = s.toCharArray();
-		
-		FastBufferWriter output = new FastBufferWriter(16);
-		//write it several times.
-		for (int i = 0; i < 4; i++) output.write(bytes);
-		//write it one more time by one byte
-		for (int i = 0; i < bytes.length; i++) {
-			output.write(bytes[i]);
-		}
-		FastBufferOutputStream output2 = output.convertToOutputStream("UTF-8");
-		FastBufferInputStream input = new FastBufferInputStream(output2);
-		StringBuffer sb = new StringBuffer();
-		//use for reading unconvenient array length.
-		byte[] bs = new byte[ARRAY_LENGTH];
-		int l = 0;
-		while((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
-			if(BUILD_STRING) sb.append(new String(bs, READ_OFF, l));
-		}
-		if(BUILD_STRING && OUT_STRING) System.out.println(sb);
-	}
-
-	static void testStandardTransitionFromWriterToStream() throws IOException {
-		String s = "This is a senseless text to test transform from writer to stream.\n";
-		for (int i = 0; i < 10; i++) s = s + s; //repeated 16 times 
-		char[] bytes = s.toCharArray();
-		
-		StringWriter output = new StringWriter(16);
-		//write it several times.
-		for (int i = 0; i < 4; i++) output.write(bytes);
-		//write it one more time by one byte
-		for (int i = 0; i < bytes.length; i++) {
-			output.write(bytes[i]);
-		}
-		String str = output.toString();
-		ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes());
-		StringBuffer sb = new StringBuffer();
-		//use for reading unconvenient array length.
-		byte[] bs = new byte[ARRAY_LENGTH];
-		int l = 0;
-		while((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
-			if(BUILD_STRING) sb.append(new String(bs, READ_OFF, l));
-		}
-		if(BUILD_STRING && OUT_STRING) System.out.println(sb);
-	}
-
-	static void testTransitionFromStreamToWriter() throws IOException {
-		String s = "This is a senseless text to test transform from stream to writer.\n";
-		for (int i = 0; i < 10; i++) s = s + s; //repeated 16 times 
-		byte[] bytes = s.getBytes();
-		
-		FastBufferOutputStream output = new FastBufferOutputStream(16);
-		//write it several times.
-		for (int i = 0; i < 4; i++) output.write(bytes);
-		//write it one more time by one byte
-		for (int i = 0; i < bytes.length; i++) {
-			output.write(bytes[i]);
-		}
-		FastBufferWriter output2 = output.convertToWriter("UTF-8");
-		FastBufferReader input = new FastBufferReader(output2);
-		StringBuffer sb = new StringBuffer();
-		//use for reading unconvenient array length.
-		char[] bs = new char[ARRAY_LENGTH];
-		int l = 0;
-		while((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
-			if(BUILD_STRING) sb.append(new String(bs, READ_OFF, l));
-		}
-		if(BUILD_STRING && OUT_STRING) System.out.println(sb);
-	}
-	/**
-	 * @param args
-	 */
-	public static void main(String[] args) {
-		long t = System.currentTimeMillis();
-		try {
-			for (int i = 0; i < 10; i++) {
-//			testStreams();
-//			testStandardStreams();
-
-//			testReaders();
-//				testStandardReaders();
-				
-//			testTransitionFromWriterToStream();
-			testStandardTransitionFromWriterToStream();
-			
-//			testTransitionFromStreamToWriter();
-			}
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		long dt = System.currentTimeMillis() - t;
-		System.out.println(dt);
-
-	}
-
-}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/XMLResponseWriterState.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/XMLResponseWriterState.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/XMLResponseWriterState.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,6 +18,9 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.io;
 
 import java.io.IOException;
@@ -28,10 +31,12 @@
  * @author shura Class to implement state pattern for
  *         <code>ResponseWriter</code> Real states must extend this. By
  *         default, block any events, ignore output.
- *  
+ *
  */
 class XMLResponseWriterState {
+
     // private ResponseWriter writer;
+
     /**
      * @throws java.io.IOException
      */
@@ -69,8 +74,7 @@
      * @param property
      * @throws java.io.IOException
      */
-    void writeAttribute(String name, Object value, String property)
-            throws IOException {
+    void writeAttribute(String name, Object value, String property) throws IOException {
         throw new IOException("Illegal state for this method");
     }
 
@@ -107,23 +111,22 @@
      * @param property
      * @throws java.io.IOException
      */
-    void writeURIAttribute(String name, Object value, String property)
-            throws IOException {
+    void writeURIAttribute(String name, Object value, String property) throws IOException {
         throw new IOException("Illegal state for this method");
     }
 
     /**
-     * 
+     *
      * Main hook for realise <code>Writer</code>. In document writed as
      * comment, outside of document do nothing ....
-     * 
+     *
      * @param cbuf
      * @param off
      * @param len
      * @throws IOException
      */
     void write(char[] cbuf, int off, int len) throws IOException {
+
         // DO NOTHING
-
     }
-}
\ No newline at end of file
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/io/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,4 +1,5 @@
+
 /**
- * Implementation of I/O streams based on buffers 
+ * Implementation of I/O streams based on buffers
  */
 package org.ajax4jsf.io;

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/javascript/JSMin.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/javascript/JSMin.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/javascript/JSMin.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,32 +1,32 @@
 /*
  * JSMin.java 2006-02-13
- * 
+ *
  * Copyright (c) 2006 John Reilly (www.inconspicuous.org)
- * 
+ *
  * This work is a translation from C to Java of jsmin.c published by
- * Douglas Crockford.  Permission is hereby granted to use the Java 
+ * Douglas Crockford.  Permission is hereby granted to use the Java
  * version under the same conditions as the jsmin.c on which it is
- * based.  
- * 
- * 
- * 
- * 
+ * based.
+ *
+ *
+ *
+ *
  * jsmin.c 2003-04-21
- * 
+ *
  * Copyright (c) 2002 Douglas Crockford (www.crockford.com)
- * 
+ *
  * Permission is hereby granted, free of charge, to any person obtaining a copy
  * of this software and associated documentation files (the "Software"), to deal
  * in the Software without restriction, including without limitation the rights
  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  * copies of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
- * 
+ *
  * The above copyright notice and this permission notice shall be included in
  * all copies or substantial portions of the Software.
- * 
+ *
  * The Software shall be used for Good, not Evil.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,7 +35,11 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
+
+
+
 package org.ajax4jsf.javascript;
+
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
@@ -43,297 +47,341 @@
 import java.io.OutputStream;
 import java.io.PushbackInputStream;
 
-
 public class JSMin {
-	private static final int EOF = -1;
+    private static final int EOF = -1;
 
-	private PushbackInputStream in;
-	private OutputStream out;
+    private int column;
+    private PushbackInputStream in;
+    private int line;
+    private OutputStream out;
+    private int theA;
+    private int theB;
 
-	private int theA;
-	private int theB;
-	
-	private int line;
-	
-	private int column;
-	
-	public JSMin(InputStream in, OutputStream out) {
-		this.in = new PushbackInputStream(in,2);
-		this.out = out;
-		this.line = 0;
-		this.column = 0;
-	}
+    public JSMin(InputStream in, OutputStream out) {
+        this.in = new PushbackInputStream(in, 2);
+        this.out = out;
+        this.line = 0;
+        this.column = 0;
+    }
 
-	/**
-	 * isAlphanum -- return true if the character is a letter, digit,
-	 * underscore, dollar sign, or non-ASCII character.
-	 */
-	static boolean isAlphanum(int c) {
-		return ( (c >= 'a' && c <= 'z') || 
-				 (c >= '0' && c <= '9') || 
-				 (c >= 'A' && c <= 'Z') || 
-				 c == '_' || 
-				 c == '$' || 
-				 c == '\\' || 
-				 c > 126);
-	}
+    /**
+     * isAlphanum -- return true if the character is a letter, digit,
+     * underscore, dollar sign, or non-ASCII character.
+     */
+    static boolean isAlphanum(int c) {
+        return c >= 'a' && c <= 'z' || ((c >= '0') && (c <= '9')) || ((c >= 'A') && (c <= 'Z')) || (c == '_')
+               || (c == '$') || (c == '\\') || (c > 126);
+    }
 
-	/**
-	 * get -- return the next character from stdin. Watch out for lookahead. If
-	 * the character is a control character, translate it to a space or
-	 * linefeed.
-	 */
-	int get() throws IOException {
-		int c = in.read();
-		
-		if(c == '\n'){
-			line++;
-			column = 0;
-		} else {
-			column++;
-		}
+    /**
+     * get -- return the next character from stdin. Watch out for lookahead. If
+     * the character is a control character, translate it to a space or
+     * linefeed.
+     */
+    int get() throws IOException {
+        int c = in.read();
 
-		if (c >= ' ' || c == '\n' || c == EOF) {
-			return c;
-		}
+        if (c == '\n') {
+            line++;
+            column = 0;
+        } else {
+            column++;
+        }
 
-		if (c == '\r') {
-			column = 0;
-			return '\n';
-		}
-		
-		return ' ';
-	}
+        if ((c >= ' ') || (c == '\n') || (c == EOF)) {
+            return c;
+        }
 
-	
-	
-	/**
-	 * Get the next character without getting it.
-	 */
-	int peek() throws IOException {
-		int lookaheadChar = in.read();
-		in.unread(lookaheadChar);
-		return lookaheadChar;
-	}
-	
-	void back(int c) throws IOException {
-		in.unread(c);
-	}
+        if (c == '\r') {
+            column = 0;
 
-	/**
-	 * next -- get the next character, excluding comments. peek() is used to see
-	 * if a '/' is followed by a '/' or '*'.
-	 */
-	int next() throws IOException, UnterminatedCommentException {
-		int c = get();
-		if (c == '/') {
-			switch (peek()) {
-			case '/':
-				for (;;) {
-					c = get();
-					if (c <= '\n') {
-						return c;
-					}
-				}
-			case '*':
-				get();
-				if (peek()=='@') {
-					// TODO: add spaces skipping
-					back('*');
-					return c;
-				} else {
-					for (;;) {
-						switch (get()) {
-						case '*':
-							if (peek() == '/') {
-								get();
-								return ' ';
-							}
-							break;
-						case EOF:
-							throw new UnterminatedCommentException(line,column);
-						}
-					}					
-				}
+            return '\n';
+        }
 
-			default:
-				return c;
-			}
+        return ' ';
+    }
 
-		}
-		return c;
-	}
+    /**
+     * Get the next character without getting it.
+     */
+    int peek() throws IOException {
+        int lookaheadChar = in.read();
 
-	/**
-	 * action -- do something! What you do is determined by the argument: 1
-	 * Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B.
-	 * (Delete A). 3 Get the next B. (Delete B). action treats a string as a
-	 * single character. Wow! action recognizes a regular expression if it is
-	 * preceded by ( or , or =.
-	 */
+        in.unread(lookaheadChar);
 
-	void action(int d) throws IOException, UnterminatedRegExpLiteralException,
-			UnterminatedCommentException, UnterminatedStringLiteralException {
-		switch (d) {
-		case 1:
-			out.write(theA);
-		case 2:
-			theA = theB;
+        return lookaheadChar;
+    }
 
-			if (theA == '\'' || theA == '"') {
-				for (;;) {
-					out.write(theA);
-					theA = get();
-					if (theA == theB) {
-						break;
-					}
-					if (theA <= '\n') {
-						throw new UnterminatedStringLiteralException(line,column);
-					}
-					if (theA == '\\') {
-						out.write(theA);
-						theA = get();
-					}
-				}
-			}
-			
-		case 3:
-			theB = next();
-			if (theB == '/' && (theA == '(' || theA == '!' || theA == '&' || theA == '|' || theA == ',' || theA == '='|| theA == ':' || theA == '[')) {
-				out.write(theA);
-				out.write(theB);
-				for (;;) {
-					theA = get();
-					if (theA == '/') {
-						break;
-					} else if (theA == '\\') {
-						out.write(theA);
-						theA = get();
-					} else if (theA <= '\n') {
-						throw new UnterminatedRegExpLiteralException(line,column);
-					}
-					out.write(theA);
-				}
-				theB = next();
-			}
-		}
-	}
+    void back(int c) throws IOException {
+        in.unread(c);
+    }
 
-	/**
-	 * jsmin -- Copy the input to the output, deleting the characters which are
-	 * insignificant to JavaScript. Comments will be removed. Tabs will be
-	 * replaced with spaces. Carriage returns will be replaced with linefeeds.
-	 * Most spaces and linefeeds will be removed.
-	 */
-	public void jsmin() throws IOException, UnterminatedRegExpLiteralException, UnterminatedCommentException, UnterminatedStringLiteralException{
-		theA = '\n';
-		action(3);
-		while (theA != EOF) {
-			switch (theA) {
-			case ' ':
-				if (isAlphanum(theB)) {
-					action(1);
-				} else {
-					action(2);
-				}
-				break;
-			case '\n':
-				switch (theB) {
-				case '{':
-				case '[':
-				case '(':
-				case '+':
-				case '-':
-					action(1);
-					break;
-				case ' ':
-					action(3);
-					break;
-				default:
-					if (isAlphanum(theB)) {
-						action(1);
-					} else {
-						action(2);
-					}
-				}
-				break;
-			default:
-				switch (theB) {
-				case ' ':
-					if (isAlphanum(theA)) {
-						action(1);
-						break;
-					}
-					action(3);
-					break;
-				case '\n':
-					switch (theA) {
-					case '}':
-					case ']':
-					case ')':
-					case '+':
-					case '-':
-					case '"':
-					case '\'':
-						action(1);
-						break;
-					default:
-						if (isAlphanum(theA)) {
-							action(1);
-						} else {
-							action(3);
-						}
-					}
-					break;
-				default:
-					action(1);
-					break;
-				}
-			}
-		}
-		out.flush();
-	}
+    /**
+     * next -- get the next character, excluding comments. peek() is used to see
+     * if a '/' is followed by a '/' or '*'.
+     */
+    int next() throws IOException, UnterminatedCommentException {
+        int c = get();
 
-	@SuppressWarnings("serial")
-	static class UnterminatedCommentException extends Exception {
-		public UnterminatedCommentException(int line,int column) {
-			super("Unterminated comment at line "+line+" and column "+column);
-		}
-	}
+        if (c == '/') {
+            switch (peek()) {
+                case '/' :
+                    for (;;) {
+                        c = get();
 
-	@SuppressWarnings("serial")
-	static class UnterminatedStringLiteralException extends Exception {
-		public UnterminatedStringLiteralException(int line,int column) {
-			super("Unterminated string literal at line "+line+" and column "+column);
-		}
-	}
+                        if (c <= '\n') {
+                            return c;
+                        }
+                    }
+                case '*' :
+                    get();
 
-	@SuppressWarnings("serial")
-	static class UnterminatedRegExpLiteralException extends Exception {
-		public UnterminatedRegExpLiteralException(int line,int column) {
-			super("Unterminated regular expression at line "+line+" and column "+column);
-		}
-	}
+                    if (peek() == '@') {
 
-	public static void main(String arg[]) {
-		try {
-			JSMin jsmin = new JSMin(new FileInputStream(arg[0]), System.out);
-			jsmin.jsmin();
-		} catch (FileNotFoundException e) {
-			e.printStackTrace();
-		} catch (ArrayIndexOutOfBoundsException e) {
-			e.printStackTrace();			
-		} catch (IOException e) {
-			e.printStackTrace();
-		} catch (UnterminatedRegExpLiteralException e) {
-			e.printStackTrace();
-		} catch (UnterminatedCommentException e) {
-			e.printStackTrace();
-		} catch (UnterminatedStringLiteralException e) {
-			e.printStackTrace();
-		}
-	}
+                        // TODO: add spaces skipping
+                        back('*');
 
+                        return c;
+                    } else {
+                        for (;;) {
+                            switch (get()) {
+                                case '*' :
+                                    if (peek() == '/') {
+                                        get();
 
+                                        return ' ';
+                                    }
 
+                                    break;
+
+                                case EOF :
+                                    throw new UnterminatedCommentException(line, column);
+
+                                default :
+                                    throw new IllegalStateException();
+                            }
+                        }
+                    }
+                default :
+                    return c;
+            }
+        }
+
+        return c;
+    }
+
+    /**
+     * action -- do something! What you do is determined by the argument: 1
+     * Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B.
+     * (Delete A). 3 Get the next B. (Delete B). action treats a string as a
+     * single character. Wow! action recognizes a regular expression if it is
+     * preceded by ( or , or =.
+     */
+    void action(int d) throws IOException, UnterminatedRegExpLiteralException, UnterminatedCommentException,
+           UnterminatedStringLiteralException {
+        
+        switch (d) {
+            case 1 :
+                out.write(theA);
+            case 2 :
+                theA = theB;
+
+                if ((theA == '\'') || (theA == '"')) {
+                    for (;;) {
+                        out.write(theA);
+                        theA = get();
+
+                        if (theA == theB) {
+                            break;
+                        }
+
+                        if (theA <= '\n') {
+                            throw new UnterminatedStringLiteralException(line, column);
+                        }
+
+                        if (theA == '\\') {
+                            out.write(theA);
+                            theA = get();
+                        }
+                    }
+                }
+            case 3 :
+                theB = next();
+
+                if ((theB == '/')
+                        && ((theA == '(') || (theA == '!') || (theA == '&') || (theA == '|') || (theA == ',')
+                            || (theA == '=') || (theA == ':') || (theA == '['))) {
+                    out.write(theA);
+                    out.write(theB);
+
+                    for (;;) {
+                        theA = get();
+
+                        if (theA == '/') {
+                            break;
+                        } else if (theA == '\\') {
+                            out.write(theA);
+                            theA = get();
+                        } else if (theA <= '\n') {
+                            throw new UnterminatedRegExpLiteralException(line, column);
+                        }
+
+                        out.write(theA);
+                    }
+
+                    theB = next();
+                }
+            default :
+
+            // Do nothink.
+        }
+    }
+
+    /**
+     * jsmin -- Copy the input to the output, deleting the characters which are
+     * insignificant to JavaScript. Comments will be removed. Tabs will be
+     * replaced with spaces. Carriage returns will be replaced with linefeeds.
+     * Most spaces and linefeeds will be removed.
+     */
+    public void jsmin()
+            throws IOException, UnterminatedRegExpLiteralException, UnterminatedCommentException,
+                   UnterminatedStringLiteralException {
+        theA = '\n';
+        action(3);
+
+        while (theA != EOF) {
+            switch (theA) {
+                case ' ' :
+                    if (isAlphanum(theB)) {
+                        action(1);
+                    } else {
+                        action(2);
+                    }
+
+                    break;
+
+                case '\n' :
+                    switch (theB) {
+                        case '{' :
+                        case '[' :
+                        case '(' :
+                        case '+' :
+                        case '-' :
+                            action(1);
+
+                            break;
+
+                        case ' ' :
+                            action(3);
+
+                            break;
+
+                        default :
+                            if (isAlphanum(theB)) {
+                                action(1);
+                            } else {
+                                action(2);
+                            }
+                    }
+
+                    break;
+
+                default :
+                    switch (theB) {
+                        case ' ' :
+                            if (isAlphanum(theA)) {
+                                action(1);
+
+                                break;
+                            }
+
+                            action(3);
+
+                            break;
+
+                        case '\n' :
+                            switch (theA) {
+                                case '}' :
+                                case ']' :
+                                case ')' :
+                                case '+' :
+                                case '-' :
+                                case '"' :
+                                case '\'' :
+                                    action(1);
+
+                                    break;
+
+                                default :
+                                    if (isAlphanum(theA)) {
+                                        action(1);
+                                    } else {
+                                        action(3);
+                                    }
+                            }
+
+                            break;
+
+                        default :
+                            action(1);
+
+                            break;
+                    }
+            }
+        }
+
+        out.flush();
+    }
+
+    /**
+     * Run JSMin
+     *
+     * Get the first param on file name and
+     * output on console compressed file
+     */
+    public static void main(String[] arg) {
+        try {
+            JSMin jsmin = new JSMin(new FileInputStream(arg[0]), System.out);
+
+            jsmin.jsmin();
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (ArrayIndexOutOfBoundsException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } catch (UnterminatedRegExpLiteralException e) {
+            e.printStackTrace();
+        } catch (UnterminatedCommentException e) {
+            e.printStackTrace();
+        } catch (UnterminatedStringLiteralException e) {
+            e.printStackTrace();
+        }
+    }
+
+    static class UnterminatedCommentException extends Exception {
+        private static final long serialVersionUID = -5847720072617372584L;
+
+        UnterminatedCommentException(int line, int column) {
+            super("Unterminated comment at line " + line + " and column " + column);
+        }
+    }
+
+
+    static class UnterminatedRegExpLiteralException extends Exception {
+        private static final long serialVersionUID = 8791439031230079257L;
+
+        UnterminatedRegExpLiteralException(int line, int column) {
+            super("Unterminated regular expression at line " + line + " and column " + column);
+        }
+    }
+
+
+    static class UnterminatedStringLiteralException extends Exception {
+        private static final long serialVersionUID = 5256369791002619999L;
+
+        UnterminatedStringLiteralException(int line, int column) {
+            super("Unterminated string literal at line " + line + " and column " + column);
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/javascript/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/javascript/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/javascript/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Javascript resource classes either as classes handling various aspects of Javascript processing
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Base package for AJAX classes
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AJAXDataSerializer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AJAXDataSerializer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AJAXDataSerializer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,27 +19,28 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.renderkit;
 
 
+package org.ajax4jsf.renderkit;
 
 import org.ajax4jsf.javascript.ScriptUtils;
 
 /**
  * @author shura
- * 
+ *
  */
 public class AJAXDataSerializer {
+    public static final String SERVICE = AJAXDataSerializer.class.getName();
 
-	public static final String SERVICE = AJAXDataSerializer.class.getName();
+    public String asString(Object data) {
+        StringBuffer result = new StringBuffer();
 
-	public String asString(Object data) {
-		StringBuffer result = new StringBuffer();
-		if(null != data){
-			result.append("<![CDATA[ ");
-			result.append(ScriptUtils.toScript(data));
-			result.append(" ]]>");
-		}
-		return result.toString();
-	}
+        if (null != data) {
+            result.append("<![CDATA[ ");
+            result.append(ScriptUtils.toScript(data));
+            result.append(" ]]>");
+        }
+
+        return result.toString();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxChildrenRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxChildrenRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxChildrenRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,9 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.component.AjaxChildrenEncoder;
+import org.ajax4jsf.component.AjaxOutput;
+import org.ajax4jsf.context.AjaxContext;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
+
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Set;
@@ -30,183 +42,186 @@
 import javax.faces.component.UIComponent;
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.component.AjaxChildrenEncoder;
-import org.ajax4jsf.component.AjaxOutput;
-import org.ajax4jsf.context.AjaxContext;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * @author shura
- * 
+ *
  */
-public abstract class AjaxChildrenRenderer extends AjaxComponentRendererBase
-		implements AjaxRenderer {
+public abstract class AjaxChildrenRenderer extends AjaxComponentRendererBase implements AjaxRenderer {
+    public static final String[] SPECIAL_COMPONENTS_TYPES = {"org.ajax4jsf.Bundle" /* UILoadBundle.COMPONENT_TYPE */,
+        "org.apache.myfaces.AliasBean", "org.apache.myfaces.AliasBeansScope"};
 
-	private static final Logger log = RichfacesLogger.RENDERKIT.getLogger();
+    private static final String SPECIAL_TYPES_PARAMETER = "org.ajax4jsf.CONTROL_COMPONENTS";
+    private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
 
-	public static final String[] SPECIAL_COMPONENTS_TYPES = {
-			"org.ajax4jsf.Bundle"/* UILoadBundle.COMPONENT_TYPE */,
-			"org.apache.myfaces.AliasBean",
-			"org.apache.myfaces.AliasBeansScope" };
-	private static final String SPECIAL_TYPES_PARAMETER = "org.ajax4jsf.CONTROL_COMPONENTS";
+    private Set<String> specialComponentTypes = null;
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see
-	 * org.ajax4jsf.renderkit.AjaxRenderer#encodeAjaxChildren(javax.faces.context
-	 * .FacesContext, javax.faces.component.UIComponent, java.lang.String,
-	 * java.util.Set, java.util.Set)
-	 */
-	public void encodeAjaxChildren(FacesContext context, UIComponent component,
-			String path, Set<String> ids, Set<String> renderedAreas)
-			throws IOException {
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.ENCODE_CHILD_AJAX_INFO,
-					path, component.getId()));
-		}
-		String currentPath = path;
-		if (component instanceof NamingContainer) {
-			currentPath += component.getId() + NamingContainer.SEPARATOR_CHAR;
-			// Do not check children if we have no id to render under naming
-			// container.
-			if (AjaxContext.getCurrentInstance(context).isLimitToList()
-					&& noIdUnderPath(path, ids)) {
-				return;
-			}
-		}
-		for (Iterator<UIComponent> it = component.getFacetsAndChildren(); it
-				.hasNext();) {
-			UIComponent element = (UIComponent) it.next();
-			encodeAjaxComponent(context, element, currentPath, ids,
-					renderedAreas);
-		}
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see
+     * org.ajax4jsf.renderkit.AjaxRenderer#encodeAjaxChildren(javax.faces.context
+     * .FacesContext, javax.faces.component.UIComponent, java.lang.String,
+     * java.util.Set, java.util.Set)
+     */
+    public void encodeAjaxChildren(FacesContext context, UIComponent component, String path, Set<String> ids,
+            Set<String> renderedAreas) throws IOException {
 
-	private boolean noIdUnderPath(String path, Set<String> ids) {
-		// Do we have an any component for the rendering under that container ?
-		boolean noSuchId = true;
-		for (String id : ids) {
-			if (null != id && id.startsWith(path)) {
-				noSuchId = false;
-				break;
-			}
-		}
-		return noSuchId;
-	}
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.ENCODE_CHILD_AJAX_INFO, path, component.getId()));
+        }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see
-	 * org.ajax4jsf.renderkit.AjaxRenderer#encodeAjaxComponent(javax.faces.context
-	 * .FacesContext, javax.faces.component.UIComponent, java.lang.String,
-	 * java.util.Set, java.util.Set)
-	 */
-	public void encodeAjaxComponent(FacesContext context,
-			UIComponent component, String currentPath, Set<String> ids,
-			Set<String> renderedAreas) throws IOException {
-		if (component.isRendered()) { // skip not-rendered components.
-			boolean found = false;
-			boolean limitToList = AjaxContext.getCurrentInstance(context).isLimitToList();
-			String elementId = component.getId();
-			String absoluteId = currentPath + elementId;
-			if (!ids.isEmpty()) {
-				// list for rendering may contains absolute id ( best ),
-				// component Id or client ID
-				// String clientId = element.getClientId(context);
-				if (ids.contains(absoluteId) || ids.contains(elementId)) {
-					if (log.isDebugEnabled()) {
-						log.debug(Messages.getMessage(
-								Messages.RENDER_AJAX_AREA_INFO, absoluteId));
-					}
-					// renderChild(context, element);
-					found = true;
-				}
-			}
-			// 
-			if (!found && limitToList
-					&& component instanceof NamingContainer
-					&& noIdUnderPath(absoluteId
-							+ NamingContainer.SEPARATOR_CHAR, ids)) {
-				return;
-			}
-			if (!found && !limitToList && component instanceof AjaxOutput) {
-				if (((AjaxOutput) component).isAjaxRendered()) {
-					// renderChild(context, element);
-					found = true;
-				}
+        String currentPath = path;
 
-			}
+        if (component instanceof NamingContainer) {
+            currentPath += component.getId() + NamingContainer.SEPARATOR_CHAR;
 
-			if (!found) {
-				if (component instanceof AjaxChildrenEncoder) {
-					((AjaxChildrenEncoder) component).encodeAjaxChild(context,
-							currentPath, ids, renderedAreas);
-				} else {
-					// Special case - for control components, not produced
-					// html code - such as message bundles loaders,
-					// MyFaces aliases etc. we call encodeBegin/end methods
-					// even if components not in rendered areas.
-					boolean special = isSpecialElement(context, component);
-					if (special) {
-						component.encodeBegin(context);
-					}
-					encodeAjaxChildren(context, component, currentPath, ids,
-							renderedAreas);
-					if (special) {
-						component.encodeEnd(context);
-					}
+            // Do not check children if we have no id to render under naming
+            // container.
+            if (AjaxContext.getCurrentInstance(context).isLimitToList() && noIdUnderPath(path, ids)) {
+                return;
+            }
+        }
 
-				}
-			} else {
-				renderedAreas.add(component.getClientId(context));
-				renderChild(context, component);
-			}
-		}
-	}
+        for (Iterator<UIComponent> it = component.getFacetsAndChildren(); it.hasNext(); ) {
+            UIComponent element = (UIComponent) it.next();
 
-	private Set<String> _specialComponentTypes = null;
+            encodeAjaxComponent(context, element, currentPath, ids, renderedAreas);
+        }
+    }
 
-	/**
-	 * Detect component as special control case - such as messages bundle
-	 * loader, alias bean components etc. Type of component get by reflection
-	 * from static field COMPONENT_TYPE
-	 * 
-	 * @param context
-	 * @param component
-	 * @return true if encode methods must be called for this component even in
-	 *         not-rendered parts.
-	 */
-	private boolean isSpecialElement(FacesContext context, UIComponent component) {
-		if (_specialComponentTypes == null) {
-			_specialComponentTypes = new HashSet<String>(10);
-			for (int i = 0; i < SPECIAL_COMPONENTS_TYPES.length; i++) {
-				_specialComponentTypes.add(SPECIAL_COMPONENTS_TYPES[i]);
-			}
-			String special = context.getExternalContext().getInitParameter(
-					SPECIAL_TYPES_PARAMETER);
-			if (null != special) {
-				String[] split = special.split(",");
-				for (int i = 0; i < split.length; i++) {
-					_specialComponentTypes.add(split[i]);
-				}
-			}
-		}
-		boolean result;
-		try {
-			String componentType = (String) component.getClass().getField(
-					"COMPONENT_TYPE").get(null);
-			result = _specialComponentTypes.contains(componentType);
-		} catch (Exception e) {
-			// exception occurs if component not have accesible COMPONENT_TYPE
-			// constant
-			// we assume that component not in special types.
-			result = false;
-		}
-		return result;
-	}
+    private boolean noIdUnderPath(String path, Set<String> ids) {
 
+        // Do we have an any component for the rendering under that container ?
+        boolean noSuchId = true;
+
+        for (String id : ids) {
+            if ((null != id) && id.startsWith(path)) {
+                noSuchId = false;
+
+                break;
+            }
+        }
+
+        return noSuchId;
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see
+     * org.ajax4jsf.renderkit.AjaxRenderer#encodeAjaxComponent(javax.faces.context
+     * .FacesContext, javax.faces.component.UIComponent, java.lang.String,
+     * java.util.Set, java.util.Set)
+     */
+    public void encodeAjaxComponent(FacesContext context, UIComponent component, String currentPath, Set<String> ids,
+            Set<String> renderedAreas) throws IOException {
+        
+        if (component.isRendered()) { // skip not-rendered components.
+            boolean found = false;
+            boolean limitToList = AjaxContext.getCurrentInstance(context).isLimitToList();
+            String elementId = component.getId();
+            String absoluteId = currentPath + elementId;
+
+            if (!ids.isEmpty()) {
+
+                // list for rendering may contains absolute id ( best ),
+                // component Id or client ID
+                // String clientId = element.getClientId(context);
+                if (ids.contains(absoluteId) || ids.contains(elementId)) {
+                    if (LOG.isDebugEnabled()) {
+                        LOG.debug(Messages.getMessage(Messages.RENDER_AJAX_AREA_INFO, absoluteId));
+                    }
+
+                    // renderChild(context, element);
+                    found = true;
+                }
+            }
+
+            //
+            if (!found && limitToList && (component instanceof NamingContainer)
+                    && noIdUnderPath(absoluteId + NamingContainer.SEPARATOR_CHAR, ids)) {
+                return;
+            }
+
+            if (!found && !limitToList && (component instanceof AjaxOutput)) {
+                if (((AjaxOutput) component).isAjaxRendered()) {
+
+                    // renderChild(context, element);
+                    found = true;
+                }
+            }
+
+            if (!found) {
+                if (component instanceof AjaxChildrenEncoder) {
+                    ((AjaxChildrenEncoder) component).encodeAjaxChild(context, currentPath, ids, renderedAreas);
+                } else {
+
+                    // Special case - for control components, not produced
+                    // html code - such as message bundles loaders,
+                    // MyFaces aliases etc. we call encodeBegin/end methods
+                    // even if components not in rendered areas.
+                    boolean special = isSpecialElement(context, component);
+
+                    if (special) {
+                        component.encodeBegin(context);
+                    }
+
+                    encodeAjaxChildren(context, component, currentPath, ids, renderedAreas);
+
+                    if (special) {
+                        component.encodeEnd(context);
+                    }
+                }
+            } else {
+                renderedAreas.add(component.getClientId(context));
+                renderChild(context, component);
+            }
+        }
+    }
+
+    /**
+     * Detect component as special control case - such as messages bundle
+     * loader, alias bean components etc. Type of component get by reflection
+     * from static field COMPONENT_TYPE
+     *
+     * @param context
+     * @param component
+     * @return true if encode methods must be called for this component even in
+     *         not-rendered parts.
+     */
+    private boolean isSpecialElement(FacesContext context, UIComponent component) {
+        if (specialComponentTypes == null) {
+            specialComponentTypes = new HashSet<String>(10);
+
+            for (int i = 0; i < SPECIAL_COMPONENTS_TYPES.length; i++) {
+                specialComponentTypes.add(SPECIAL_COMPONENTS_TYPES[i]);
+            }
+
+            String special = context.getExternalContext().getInitParameter(SPECIAL_TYPES_PARAMETER);
+
+            if (null != special) {
+                String[] split = special.split(",");
+
+                for (int i = 0; i < split.length; i++) {
+                    specialComponentTypes.add(split[i]);
+                }
+            }
+        }
+
+        boolean result;
+
+        try {
+            String componentType = (String) component.getClass().getField("COMPONENT_TYPE").get(null);
+
+            result = specialComponentTypes.contains(componentType);
+        } catch (Exception e) {
+
+            // exception occurs if component not have accesible COMPONENT_TYPE
+            // constant
+            // we assume that component not in special types.
+            result = false;
+        }
+
+        return result;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxComponentRendererBase.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxComponentRendererBase.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxComponentRendererBase.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,9 +19,9 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.renderkit;
 
 
+package org.ajax4jsf.renderkit;
 
 /**
  * Base class for all Ajax enabled components. Perform common task -
@@ -30,7 +30,4 @@
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:49 $
  *
  */
-public abstract class AjaxComponentRendererBase extends RendererBase {
-
-
-}
+public abstract class AjaxComponentRendererBase extends RendererBase {}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxContainerRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxContainerRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxContainerRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,9 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.component.AjaxContainer;
+import org.ajax4jsf.context.AjaxContext;
+import org.ajax4jsf.event.AjaxEvent;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
+
 import java.util.Map;
 import java.util.Set;
 
@@ -29,155 +41,150 @@
 import javax.faces.component.UIComponent;
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.component.AjaxContainer;
-import org.ajax4jsf.context.AjaxContext;
-import org.ajax4jsf.event.AjaxEvent;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * Base renderer for all AJAX - subview components.
- * 
+ *
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.3 $ $Date: 2007/02/08 15:02:02 $
- * 
+ *
  */
 public class AjaxContainerRenderer extends AjaxChildrenRenderer {
+    public static final String AJAX_FLAG_HEADER = "Ajax-Response";
+    public static final String AJAX_JSF_SCRIPT = "AJAX.js";
+    public static final String AJAX_LOCATION_HEADER = "Location";
+    public static final String AJAX_PARAMETER_NAME = "AJAXREQUEST";
+    public static final String AJAX_RESULT_GROUP_ATTR = "content";
+    public static final String AJAX_RESULT_GROUP_TAG = "meta";
+    public static final String AJAX_RESULT_STYLE = "display: none";
+    public static final String AJAX_UPDATE_HEADER = "Ajax-Update-Ids";
+    public static final String AJAX_VIEW_STATE_ID = "ajax-view-state";
+    public static final String AJAX_VIEW_STATE_TAG = "span";
+    public static final String JSDOM_SCRIPT = "JSDOM_sarissa.js";
+    public static final String SARISSA_SCRIPT = "sarissa.js";
+    private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
 
-	public static final String AJAX_PARAMETER_NAME = "AJAXREQUEST";
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.renderkit.RendererBase#getComponentClass()
+     */
+    @Override
+    @SuppressWarnings("unchecked")
+    protected Class getComponentClass() {
 
-	public static final String AJAX_JSF_SCRIPT = "AJAX.js";
+        // TODO Auto-generated method stub
+        return AjaxContainer.class;
+    }
 
-	public static final String SARISSA_SCRIPT = "sarissa.js";
+    /**
+     *
+     *
+     * @see javax.faces.component.UIComponent#encodeChildren(javax.faces.context.FacesContext)
+     *      Since main function of component - render subset of components, for
+     *      update on page,don't delegate this for renderer.
+     *
+     */
+    @Override
+    public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
 
-	public static final String JSDOM_SCRIPT = "JSDOM_sarissa.js";
+        // Normal request - render all ...
+        LOG.debug(Messages.getMessage(Messages.RENDER_CHILDREN_NON_AJAX_INFO));
+        renderChildren(context, component);
+    }
 
-	public static final String AJAX_VIEW_STATE_TAG = "span";
+    /**
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    public void encodeAjax(FacesContext context, UIComponent component) throws IOException {
+        UIComponent root;
 
-	public static final String AJAX_VIEW_STATE_ID = "ajax-view-state";
+        // Iterate over all childrens, render it if nessesary...
+        LOG.debug(Messages.getMessage(Messages.RENDER_CHILDREN_AJAX_INFO));
 
-	public static final String AJAX_RESULT_GROUP_TAG = "meta";
+        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
+        Set<String> ids = ajaxContext.getAjaxAreasToRender();
+        Set<String> renderedAreas = ajaxContext.getAjaxRenderedAreas();
 
-	public static final String AJAX_RESULT_GROUP_ATTR = "content";
+        if (((AjaxContainer) component).isRenderRegionOnly()) {
+            root = component;
+        } else {
+            root = context.getViewRoot();
+        }
 
-	public static final String AJAX_RESULT_STYLE = "display: none";
+        String path = AjaxRendererUtils.getAbsoluteId(root);
 
-	public static final String AJAX_UPDATE_HEADER = "Ajax-Update-Ids";
+        // if(! (component instanceof NamingContainer)){
+        path = path.substring(0, path.lastIndexOf(NamingContainer.SEPARATOR_CHAR) + 1);
 
-	private static final Logger log = RichfacesLogger.RENDERKIT.getLogger();
+        if (isParentRendered(root)) {
+            encodeAjaxComponent(context, root, path, ids, renderedAreas);
+        }
 
-	public static final String AJAX_FLAG_HEADER = "Ajax-Response";
+        // Write information about encoded areas after submission.
+        AjaxRendererUtils.encodeAreas(context, component);
+    }
 
-	public static final String AJAX_LOCATION_HEADER = "Location";
+    public boolean isParentRendered(UIComponent target) {
+        UIComponent component = target;
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.renderkit.RendererBase#getComponentClass()
-	 */
-	@SuppressWarnings("unchecked")
-	protected Class getComponentClass() {
-		// TODO Auto-generated method stub
-		return AjaxContainer.class;
-	}
+        while (component != null) {
+            if (!component.isRendered()) {
+                return false;
+            }
 
-	/**
-	 * 
-	 * 
-	 * @see javax.faces.component.UIComponent#encodeChildren(javax.faces.context.FacesContext)
-	 *      Since main function of component - render subset of components, for
-	 *      update on page,don't delegate this for renderer.
-	 * 
-	 */
-	public void encodeChildren(FacesContext context, UIComponent component)
-			throws IOException {
-		// Normal request - render all ...
-		log.debug(Messages.getMessage(Messages.RENDER_CHILDREN_NON_AJAX_INFO));
-		renderChildren(context, component);
-	}
+            component = component.getParent();
+        }
 
-	/**
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	public void encodeAjax(FacesContext context, UIComponent component)
-			throws IOException {
-		UIComponent root;
-		// Iterate over all childrens, render it if nessesary...
-		log.debug(Messages.getMessage(Messages.RENDER_CHILDREN_AJAX_INFO));
-		AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-		Set<String> ids = ajaxContext.getAjaxAreasToRender();
-		Set<String> renderedAreas = ajaxContext.getAjaxRenderedAreas();
-		if (((AjaxContainer) component).isRenderRegionOnly()) {
-			root = component;
-		} else {
-			root = context.getViewRoot();
-		}
-		String path = AjaxRendererUtils.getAbsoluteId(root);
-		// if(! (component instanceof NamingContainer)){
-		path = path.substring(0, path
-				.lastIndexOf(NamingContainer.SEPARATOR_CHAR) + 1);
-		if (isParentRendered(root)) {
-			encodeAjaxComponent(context, root, path, ids, renderedAreas);
-		} 
-		// Write information about encoded areas after submission.
-		AjaxRendererUtils.encodeAreas(context, component);
-	}
+        return true;
+    }
 
-	public boolean isParentRendered(UIComponent target) {
-		UIComponent component = target;
+    /*
+     * always return true, since component must maintain set of rendered
+     * components.
+     *
+     * @see javax.faces.component.UIComponent#getRendersChildren()
+     */
+    @Override
+    public boolean getRendersChildren() {
+        return false;
+    }
 
-		while (component != null) {
-			if (!component.isRendered()) {
-				return false;
-			}
-			component = component.getParent();
-		}
-		return true;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see
+     * org.ajax4jsf.renderkit.RendererBase#doDecode(javax.faces.context.FacesContext
+     * , javax.faces.component.UIComponent)
+     */
+    @Override
+    protected void doDecode(FacesContext context, UIComponent component) {
+        String clientId = component.getClientId(context);
+        Map<String, String> paramMap = context.getExternalContext().getRequestParameterMap();
 
-	/*
-	 * always return true, since component must maintain set of rendered
-	 * components.
-	 * 
-	 * @see javax.faces.component.UIComponent#getRendersChildren()
-	 */
-	public boolean getRendersChildren() {
-		return false;
-	}
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.DECODE_AJAX_REQUEST_STATUS_INFO, clientId));
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see
-	 * org.ajax4jsf.renderkit.RendererBase#doDecode(javax.faces.context.FacesContext
-	 * , javax.faces.component.UIComponent)
-	 */
-	protected void doDecode(FacesContext context, UIComponent component) {
-		String clientId = component.getClientId(context);
-		Map<String, String> paramMap = context.getExternalContext()
-				.getRequestParameterMap();
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(
-					Messages.DECODE_AJAX_REQUEST_STATUS_INFO, clientId));
-			// log.debug(Messages.getMessage(Messages.REQUEST_PARAMETERS_MAP,
-			// paramMap.toString()));
-		}
-		Object ajaxParameter = paramMap.get(AJAX_PARAMETER_NAME);
-		AjaxContainer ajaxContainer = (AjaxContainer) component;
-		if (null != ajaxParameter && ajaxParameter.equals(clientId)) {
-			ajaxContainer.setSubmitted(true);
-			if (ajaxContainer.isSelfRendered()) {
-				AjaxContext.getCurrentInstance(context).setSelfRender(true);
-			}
-			AjaxEvent event = new AjaxEvent(component);
-			component.queueEvent(event);
-		} else {
-			ajaxContainer.setSubmitted(false);
-		}
+            // log.debug(Messages.getMessage(Messages.REQUEST_PARAMETERS_MAP,
+            // paramMap.toString()));
+        }
 
-	}
+        Object ajaxParameter = paramMap.get(AJAX_PARAMETER_NAME);
+        AjaxContainer ajaxContainer = (AjaxContainer) component;
 
+        if ((null != ajaxParameter) && ajaxParameter.equals(clientId)) {
+            ajaxContainer.setSubmitted(true);
+
+            if (ajaxContainer.isSelfRendered()) {
+                AjaxContext.getCurrentInstance(context).setSelfRender(true);
+            }
+
+            AjaxEvent event = new AjaxEvent(component);
+
+            component.queueEvent(event);
+        } else {
+            ajaxContainer.setSubmitted(false);
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxEventOptions.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxEventOptions.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxEventOptions.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,86 +19,87 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
+import org.ajax4jsf.javascript.ScriptStringBase;
+import org.ajax4jsf.javascript.ScriptUtils;
+
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
 
-import org.ajax4jsf.javascript.ScriptStringBase;
-import org.ajax4jsf.javascript.ScriptUtils;
-
 /**
  * @author Nick Belaevski
  * @since 4.0
  */
 public class AjaxEventOptions extends ScriptStringBase {
 
-	/**
-	 * 
-	 */
-	public static final String PARAMETERS = "parameters";
-	
-	private Map<String, Object> options = new HashMap<String, Object>();
+    /**
+     *
+     */
+    public static final String PARAMETERS = "parameters";
+    private Map<String, Object> options = new HashMap<String, Object>();
 
-	public void appendScript(StringBuffer functionString) {
-		functionString.append(ScriptUtils.toScript(options));
-	}
-	
-	public boolean isEmpty() {
-		return options.isEmpty();
-	}
-	
-	public Object get(String optionName) {
-		return options.get(optionName); 
-	}
-	
-	public void set(String optionName, Object optionValue) {
-		options.put(optionName, optionValue);
-	}
-	
-	public void remove(String optionName) {
-		options.remove(optionName);
-	}
-	
-	public boolean hasParameters() {
-		@SuppressWarnings("unchecked")
-		Map<String, Object> parameters = (Map<String, Object>) options.get(PARAMETERS);
-		return parameters != null && !parameters.isEmpty();
-	}
-	
-	//TODO: optimize rendered data
-	public Map<String, Object> getParameters() {
-		@SuppressWarnings("unchecked")
-		Map<String, Object> parameters = (Map<String, Object>) options.get(PARAMETERS);
-		if (parameters == null) {
-			parameters = new LinkedHashMap<String, Object>();
-			options.put(PARAMETERS, parameters);
-		}
-		
-		return parameters;
-	}
-	
-	public Object getParameter(String parameterName) {
-		Object result = null;
-		@SuppressWarnings("unchecked")
-		Map<String, Object> parameters = (Map<String, Object>) options.get(PARAMETERS);
-		if (parameters != null) {
-			result = parameters.get(parameterName);
-		}
-		
-		return result;
-	}
-	
-	public void setParameter(String parameterName, Object parameterValue) {
-		getParameters().put(parameterName, parameterValue);
-	}
-	
-	public void removeParameter(String parameterName) {
-		@SuppressWarnings("unchecked")
-		Map<String, Object> parameters = (Map<String, Object>) options.get(PARAMETERS);
-		if (parameters != null) {
-			parameters.remove(parameterName);
-		}
-	}
+    public void appendScript(StringBuffer functionString) {
+        functionString.append(ScriptUtils.toScript(options));
+    }
+
+    public boolean isEmpty() {
+        return options.isEmpty();
+    }
+
+    public Object get(String optionName) {
+        return options.get(optionName);
+    }
+
+    public void set(String optionName, Object optionValue) {
+        options.put(optionName, optionValue);
+    }
+
+    public void remove(String optionName) {
+        options.remove(optionName);
+    }
+
+    public boolean hasParameters() {
+        @SuppressWarnings("unchecked") Map<String, Object> parameters = (Map<String, Object>) options.get(PARAMETERS);
+
+        return (parameters != null) && !parameters.isEmpty();
+    }
+
+    // TODO: optimize rendered data
+    public Map<String, Object> getParameters() {
+        @SuppressWarnings("unchecked") Map<String, Object> parameters = (Map<String, Object>) options.get(PARAMETERS);
+
+        if (parameters == null) {
+            parameters = new LinkedHashMap<String, Object>();
+            options.put(PARAMETERS, parameters);
+        }
+
+        return parameters;
+    }
+
+    public Object getParameter(String parameterName) {
+        Object result = null;
+        @SuppressWarnings("unchecked") Map<String, Object> parameters = (Map<String, Object>) options.get(PARAMETERS);
+
+        if (parameters != null) {
+            result = parameters.get(parameterName);
+        }
+
+        return result;
+    }
+
+    public void setParameter(String parameterName, Object parameterValue) {
+        getParameters().put(parameterName, parameterValue);
+    }
+
+    public void removeParameter(String parameterName) {
+        @SuppressWarnings("unchecked") Map<String, Object> parameters = (Map<String, Object>) options.get(PARAMETERS);
+
+        if (parameters != null) {
+            parameters.remove(parameterName);
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxRendererUtils.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxRendererUtils.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxRendererUtils.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,10 +19,31 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.component.AjaxClientBehavior;
+import org.ajax4jsf.component.AjaxComponent;
+import org.ajax4jsf.component.AjaxContainer;
+import org.ajax4jsf.component.AjaxLoadBundleComponent;
+import org.ajax4jsf.component.AjaxViewRoot;
+import org.ajax4jsf.context.AjaxContext;
+import org.ajax4jsf.javascript.JSFunction;
+import org.ajax4jsf.javascript.JSFunctionDefinition;
+import org.ajax4jsf.javascript.JSReference;
+import org.ajax4jsf.renderkit.RendererUtils.HTML;
+import org.ajax4jsf.util.ServicesUtils;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
+
 import java.lang.reflect.Method;
+
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
@@ -38,1095 +59,1068 @@
 import javax.faces.context.ExternalContext;
 import javax.faces.context.FacesContext;
 import javax.faces.context.ResponseWriter;
+
 import javax.servlet.http.HttpServletResponse;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.component.AjaxClientBehavior;
-import org.ajax4jsf.component.AjaxComponent;
-import org.ajax4jsf.component.AjaxContainer;
-import org.ajax4jsf.component.AjaxLoadBundleComponent;
-import org.ajax4jsf.component.AjaxViewRoot;
-import org.ajax4jsf.context.AjaxContext;
-import org.ajax4jsf.javascript.JSFunction;
-import org.ajax4jsf.javascript.JSFunctionDefinition;
-import org.ajax4jsf.javascript.JSReference;
-import org.ajax4jsf.renderkit.RendererUtils.HTML;
-import org.ajax4jsf.util.ServicesUtils;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * @author shura
- * 
+ *
  * Some utilites for render AJAX components.
  */
 public final class AjaxRendererUtils {
+    public static final String AJAX_ABORT_ATTR = "ignoreDupResponses";
+    public static final String AJAX_AREAS_RENDERED = "org.ajax4jsf.areas.rendered";
+    public static final String AJAX_DELAY_ATTR = "requestDelay";
 
-	/**
-	 * Name Javasript function for submit AJAX request
-	 */
-	public static final String AJAX_FUNCTION_NAME = "RichFaces.ajax";
+    /**
+     * Name Javasript function for submit AJAX request
+     */
+    public static final String AJAX_FUNCTION_NAME = "RichFaces.ajax";
 
-	/**
-	 * Attribute for keep clientId of status component
-	 */
-	public static final String STATUS_ATTR_NAME = "status";
+    /**
+     * @since 3.3.0
+     */
+    public static final String AJAX_PROCESS_ATTRIBUTE = "process";
+    public static final String AJAX_QUEUE_ATTR = "eventsQueue";
+    public static final String AJAX_REGIONS_ATTRIBUTE = "reRender";
+    public static final String AJAX_SINGLE_ATTR = "ajaxSingle";
+    public static final String AJAX_SINGLE_PARAMETER_NAME = "ajaxSingle";
+    public static final String ALL = "@all";
+    public static final String FORM = "@form";
 
-	/**
-	 * Attribute for keep JavaScript function name for call after complete
-	 * request.
-	 */
-	public static final String ONCOMPLETE_ATTR_NAME = "oncomplete";
-	
-	/**
-	 * Attribute for keep JavaScript function name for call after complete
-	 * request.
-	 */
-	public static final String ONCOMPLETE_CONTENT_ID = "org.ajax4jsf.oncomplete";
-	
-	/**
-	 * Attribute for keep JavaScript function name for call before updating
-	 * DOM tree.
-	 */
-	public static final String ONBEFOREDOMUPDATE_ATTR_NAME = "onbeforedomupdate";
-	
-	public static final String ONBEGIN_ATTR_NAME = "onbegin";
+    /**
+     * Attribute to keep
+     */
+    public static final String LIMITRENDER_ATTR_NAME = "limitRender";
+    public static final String NONE = "@none";
 
-	/**
-	 * Attribute to keep
-	 */
-	public static final String LIMITRENDER_ATTR_NAME = "limitRender";
+    /**
+     * Attribute for keep JavaScript function name for call before updating
+     * DOM tree.
+     */
+    public static final String ONBEFOREDOMUPDATE_ATTR_NAME = "onbeforedomupdate";
+    public static final String ONBEGIN_ATTR_NAME = "onbegin";
 
-	private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
+    /**
+     * Attribute for keep JavaScript function name for call after complete
+     * request.
+     */
+    public static final String ONCOMPLETE_ATTR_NAME = "oncomplete";
 
-	public static final String AJAX_REGIONS_ATTRIBUTE = "reRender";
+    /**
+     * Attribute for keep JavaScript function name for call after complete
+     * request.
+     */
+    public static final String ONCOMPLETE_CONTENT_ID = "org.ajax4jsf.oncomplete";
+    public static final String SIMILARITY_GROUPING_ID_ATTR = "similarityGroupingId";
 
-	/**
-	 * @since 3.3.0
-	 */
-	public static final String AJAX_PROCESS_ATTRIBUTE = "process";
-	
-	private static final Class<?> OBJECT_ARRAY_CLASS = (new Object[0]).getClass();
+    /**
+     * Attribute for keep clientId of status component
+     */
+    public static final String STATUS_ATTR_NAME = "status";
+    public static final String THIS = "@this";
+    public static final String VALUE_ATTR = "value";
+    public static final Collection<String> NONE_SET = Collections.singleton(NONE);
+    public static final Collection<String> ALL_SET = Collections.singleton(ALL);
 
-	public static final String VALUE_ATTR = "value";
+    private static final RendererUtils RENDERER_UTILS = RendererUtils.getInstance();
+    private static final Class<?> OBJECT_ARRAY_CLASS = (new Object[0]).getClass();
+    private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
 
-	public static final String AJAX_AREAS_RENDERED = "org.ajax4jsf.areas.rendered";
+    /**
+     * Static class - protect constructor
+     *
+     */
+    private AjaxRendererUtils() {}
 
-	public static final String AJAX_SINGLE_ATTR = "ajaxSingle";
+    private static enum BehaviorEventOptionsData {
+        begin {
+            @Override
+            public String getAttributeValue(AjaxClientBehavior behavior) {
+                return behavior.getOnbegin();
+            }
+        },
+        beforedomupdate {
+            @Override
+            public String getAttributeValue(AjaxClientBehavior behavior) {
+                return behavior.getOnbeforedomupdate();
+            }
+        },
+        complete {
+            @Override
+            public String getAttributeValue(AjaxClientBehavior behavior) {
+                return behavior.getOncomplete();
+            }
+        },
+        error {
+            @Override
+            public String getAttributeValue(AjaxClientBehavior behavior) {
+                return behavior.getOnerror();
+            }
+        },
+        event {
+            @Override
+            public String getAttributeValue(AjaxClientBehavior behavior) {
+                return behavior.getOnevent();
+            }
+        };
 
-	public static final String AJAX_QUEUE_ATTR = "eventsQueue";
+        public abstract String getAttributeValue(AjaxClientBehavior behavior);
+    }
 
-	public static final String AJAX_DELAY_ATTR = "requestDelay";
+    private static enum EventOptionsData {
+        begin {
+            @Override
+            public String getAttributeValue(UIComponent component) {
+                return getAjaxOnBegin(component);
+            }
+        },
+        beforedomupdate {
+            @Override
+            public String getAttributeValue(UIComponent component) {
+                return getAjaxOnBeforeDomUpdate(component);
+            }
+        },
+        complete {
+            @Override
+            public String getAttributeValue(UIComponent component) {
+                return getAjaxOncomplete(component);
+            }
+        };
 
-	public static final String AJAX_ABORT_ATTR = "ignoreDupResponses";
-	
-	public static final String AJAX_SINGLE_PARAMETER_NAME = "ajaxSingle";
-	
-	public static final String SIMILARITY_GROUPING_ID_ATTR = "similarityGroupingId";
+        public abstract String getAttributeValue(UIComponent component);
+    }
 
-	private static final RendererUtils RENDERER_UTILS = RendererUtils.getInstance();
+    /**
+     * Build JavaScript onclick event for given component
+     *
+     * @param uiComponent -
+     *            component for build event
+     * @param facesContext
+     * @return <code>StringBuffer</code> with Javascript code
+     */
+    public static StringBuffer buildOnClick(UIComponent uiComponent, FacesContext facesContext) {
+        return buildOnClick(uiComponent, facesContext, false);
+    }
 
-    public static final String ALL = "@all";
+    /**
+     * Build JavaScript onclick event for given component
+     *
+     * @param uiComponent -
+     *            component for build event
+     * @param facesContext
+     * @param omitDefaultActionUrl - default action URL is not encoded if parameter is true
+     *
+     * @return <code>StringBuffer</code> with Javascript code
+     */
+    public static StringBuffer buildOnClick(UIComponent uiComponent, FacesContext facesContext,
+            boolean omitDefaultActionUrl) {
+        return buildOnEvent(uiComponent, facesContext, HTML.ONCLICK_ATTRIBUTE, omitDefaultActionUrl);
+    }
 
-    public static final Collection<String> ALL_SET = Collections.singleton(ALL);
-    
-    public static final String FORM = "@form";
-    
-    public static final String THIS = "@this";
-    
-    public static final String NONE = "@none";
+    /**
+     * Build JavaScript event for component
+     *
+     * @param uiComponent -
+     *            component for build event
+     * @param facesContext
+     * @param eventName -
+     *            name of event
+     * @return <code>StringBuffer</code> with Javascript code
+     */
+    public static StringBuffer buildOnEvent(UIComponent uiComponent, FacesContext facesContext, String eventName) {
+        return buildOnEvent(uiComponent, facesContext, eventName, false);
+    }
 
-    public static final Collection<String> NONE_SET = Collections.singleton(NONE);
-
     /**
-	 * Static class - protect constructor 
-	 * 
-	 */
-	private AjaxRendererUtils() {
+     * Build JavaScript event for component
+     *
+     * @param uiComponent -
+     *            component for build event
+     * @param facesContext
+     * @param eventName -
+     *            name of event
+     * @param omitDefaultActionUrl - default action URL is not encoded if parameter is true
+     *
+     * @return <code>StringBuffer</code> with Javascript code
+     */
+    public static StringBuffer buildOnEvent(UIComponent uiComponent, FacesContext facesContext, String eventName,
+            boolean omitDefaultActionUrl) {
+        StringBuffer onEvent = new StringBuffer();
 
-	}
+//      if (null != eventName) {
+//          String commandOnEvent = (String) uiComponent.getAttributes().get(
+//                  eventName);
+//          if (commandOnEvent != null) {
+//              onEvent.append(commandOnEvent);
+//              onEvent.append(';');
+//          }
+//      }
+//      JSFunction ajaxFunction = buildAjaxFunction(uiComponent, facesContext);
+//      // Create formal parameter for non-input elements ???
+//      // Link Control pseudo-object
+//      // Options map. Possible options for function call :
+//      // control - name of form control for submit.
+//      // name - name for link control \
+//      // value - value of control. - possible replace by parameters ?
+//      // single true/false - submit all form or only one control.
+//      // affected - array of element's ID for update on responce.
+//      // oncomplete - function for call after complete request.
+//      // status - id of request status component.
+//      // parameters - map of parameters name/value for append on request.
+//      // ..........
+//      ajaxFunction.addParameter(buildEventOptions(facesContext, uiComponent,  omitDefaultActionUrl));
+//
+//      // appendAjaxSubmitParameters(facesContext, uiComponent, onEvent);
+//      ajaxFunction.appendScript(onEvent);
+//      if (uiComponent instanceof AjaxSupport) {
+//          AjaxSupport support = (AjaxSupport) uiComponent;
+//          if (support.isDisableDefault()) {
+//              onEvent.append("; return false;");
+//          }
+//      }
+//      LOG.debug(Messages.getMessage(Messages.BUILD_ONCLICK_INFO, uiComponent
+//              .getId(), onEvent.toString()));
+        return onEvent;
+    }
 
-	/**
-	 * Build JavaScript onclick event for given component
-	 * 
-	 * @param uiComponent -
-	 *            component for build event
-	 * @param facesContext
-	 * @return <code>StringBuffer</code> with Javascript code
-	 */
-	public static StringBuffer buildOnClick(UIComponent uiComponent,
-			FacesContext facesContext) {
-		
-		return buildOnClick(uiComponent, facesContext, false);
-	}
-	
-	/**
-	 * Build JavaScript onclick event for given component
-	 * 
-	 * @param uiComponent -
-	 *            component for build event
-	 * @param facesContext
-	 * @param omitDefaultActionUrl - default action URL is not encoded if parameter is true     
-	 *       
-	 * @return <code>StringBuffer</code> with Javascript code
-	 */
-	public static StringBuffer buildOnClick(UIComponent uiComponent,
-			FacesContext facesContext, boolean omitDefaultActionUrl) {
-		return buildOnEvent(uiComponent, facesContext, HTML.onclick_ATTRIBUTE, omitDefaultActionUrl);
-	}
+    public static AjaxEventOptions buildEventOptions(FacesContext facesContext, UIComponent component) {
+        return buildEventOptions(facesContext, component, null);
+    }
 
-	/**
-	 * Build JavaScript event for component
-	 * 
-	 * @param uiComponent -
-	 *            component for build event
-	 * @param facesContext
-	 * @param eventName -
-	 *            name of event
-	 * @return <code>StringBuffer</code> with Javascript code 
-	 */
-	public static StringBuffer buildOnEvent(UIComponent uiComponent,
-			FacesContext facesContext, String eventName) {
-	
-		return buildOnEvent(uiComponent, facesContext, eventName, false);
-	}
-	
-	/**
-	 * Build JavaScript event for component
-	 * 
-	 * @param uiComponent -
-	 *            component for build event
-	 * @param facesContext
-	 * @param eventName -
-	 *            name of event
-	 * @param omitDefaultActionUrl - default action URL is not encoded if parameter is true           
-	 *           
-	 * @return <code>StringBuffer</code> with Javascript code 
-	 */
-	public static StringBuffer buildOnEvent(UIComponent uiComponent,
-			FacesContext facesContext, String eventName, boolean omitDefaultActionUrl) {
-		StringBuffer onEvent = new StringBuffer();
-//		if (null != eventName) {
-//			String commandOnEvent = (String) uiComponent.getAttributes().get(
-//					eventName);
-//			if (commandOnEvent != null) {
-//				onEvent.append(commandOnEvent);
-//				onEvent.append(';');
-//			}
-//		}
-//		JSFunction ajaxFunction = buildAjaxFunction(uiComponent, facesContext);
-//		// Create formal parameter for non-input elements ???
-//		// Link Control pseudo-object
-//		// Options map. Possible options for function call :
-//		// control - name of form control for submit.
-//		// name - name for link control \
-//		// value - value of control. - possible replace by parameters ?
-//		// single true/false - submit all form or only one control.
-//		// affected - array of element's ID for update on responce.
-//		// oncomplete - function for call after complete request.
-//		// status - id of request status component.
-//		// parameters - map of parameters name/value for append on request.
-//		// ..........
-//		ajaxFunction.addParameter(buildEventOptions(facesContext, uiComponent,  omitDefaultActionUrl));
-//
-//		// appendAjaxSubmitParameters(facesContext, uiComponent, onEvent);
-//		ajaxFunction.appendScript(onEvent);
-//		if (uiComponent instanceof AjaxSupport) {
-//			AjaxSupport support = (AjaxSupport) uiComponent;
-//			if (support.isDisableDefault()) {
-//				onEvent.append("; return false;");
-//			}
-//		}
-//		LOG.debug(Messages.getMessage(Messages.BUILD_ONCLICK_INFO, uiComponent
-//				.getId(), onEvent.toString()));
-		return onEvent;
+    public static AjaxEventOptions buildEventOptions(FacesContext facesContext, UIComponent component,
+            AjaxClientBehavior ajaxBehavior) {
+        AjaxEventOptions ajaxEventOptions = new AjaxEventOptions();
+        Map<String, Object> parametersMap = RENDERER_UTILS.createParametersMap(facesContext, component);
+        String ajaxStatusName = getAjaxStatus(component);
 
-	}
+        if (ajaxBehavior != null) {
+            ajaxStatusName = (ajaxBehavior.getStatus() != null) ? ajaxBehavior.getStatus() : ajaxStatusName;
+            appenAjaxBehaviorOptions(ajaxBehavior, ajaxEventOptions);
+        } else {
+            appendComponentOptions(facesContext, component, ajaxEventOptions);
+        }
 
-	private static enum EventOptionsData  {
-		begin {
-			@Override
-			public String getAttributeValue(UIComponent component) {
-				return getAjaxOnBegin(component);
-			}
-		}, 
-		
-		beforedomupdate {
-			@Override
-			public String getAttributeValue(UIComponent component) {
-				return getAjaxOnBeforeDomUpdate(component);
-			}
-		}, 
-		
-		complete {
-			@Override
-			public String getAttributeValue(UIComponent component) {
-				return getAjaxOncomplete(component);
-			}
-		};
-		
-		public abstract String getAttributeValue(UIComponent component);
-	}
-	
-	private static enum BehaviorEventOptionsData  {
-		begin {
-			@Override
-			public String getAttributeValue(AjaxClientBehavior behavior) {
-				return behavior.getOnbegin();
-			}
-		}, 
-		
-		beforedomupdate {
-			@Override
-			public String getAttributeValue(AjaxClientBehavior behavior) {
-				return behavior.getOnbeforedomupdate();
-			}
-		}, 
-		
-		complete {
-			@Override
-			public String getAttributeValue(AjaxClientBehavior behavior) {
-				return behavior.getOncomplete();
-			}
-		}, 
-		
-		error {
-			@Override
-			public String getAttributeValue(AjaxClientBehavior behavior) {
-				return behavior.getOnerror();
-			}
-		},
-		
-		event {
-			@Override
-			public String getAttributeValue(AjaxClientBehavior behavior) {
-				return behavior.getOnevent();
-			}
-		}; 
-		public abstract String getAttributeValue(AjaxClientBehavior behavior);
-	}
-	
-	public static AjaxEventOptions buildEventOptions(FacesContext facesContext, UIComponent component) {
-		return buildEventOptions(facesContext, component, null);
-	}
+        if ((ajaxStatusName != null) && (ajaxStatusName.length() != 0)) {
+            ajaxEventOptions.set(STATUS_ATTR_NAME, ajaxStatusName);
+        }
 
-	public static AjaxEventOptions buildEventOptions(FacesContext facesContext, UIComponent component, AjaxClientBehavior ajaxBehavior) {
-		
-		AjaxEventOptions ajaxEventOptions = new AjaxEventOptions();
-		Map<String, Object> parametersMap = RENDERER_UTILS.createParametersMap(facesContext, component);
-		
-		String ajaxStatusName = getAjaxStatus(component);
-		
-		if(ajaxBehavior != null) {
-			ajaxStatusName = ajaxBehavior.getStatus() != null ? ajaxBehavior.getStatus() : ajaxStatusName;
-			appenAjaxBehaviorOptions(ajaxBehavior, ajaxEventOptions);
-		} else {
-			appendComponentOptions(facesContext, component, ajaxEventOptions);
-		}
-		
-		if (ajaxStatusName != null && ajaxStatusName.length() != 0) {
-			ajaxEventOptions.set(STATUS_ATTR_NAME, ajaxStatusName);
-		}
-		
-		if (!parametersMap.isEmpty()) {
-			ajaxEventOptions.getParameters().putAll(parametersMap);
-		}
-		
-		return ajaxEventOptions;
-	}
-	
-	private static boolean isNotEmpty(String value) {
-		return value != null && value.length() != 0;
-	}
+        if (!parametersMap.isEmpty()) {
+            ajaxEventOptions.getParameters().putAll(parametersMap);
+        }
 
-	private static void appenAjaxBehaviorOptions(AjaxClientBehavior behavior, AjaxEventOptions ajaxEventOptions) {
-		for(BehaviorEventOptionsData optionsData : BehaviorEventOptionsData.values()) {
-			String eventHandlerValue = optionsData.getAttributeValue(behavior);
-			if (isNotEmpty(eventHandlerValue)) {
-				ajaxEventOptions.set(optionsData.toString(), eventHandlerValue);
-			}
-		}
-	}
-	
-	private static void appendComponentOptions(FacesContext facesContext, UIComponent component,
-                                               AjaxEventOptions ajaxEventOptions)  {
-		
-		for (EventOptionsData eventOptionsData : EventOptionsData.values()) {
-			String behaviorName = eventOptionsData.toString();
-			
-			HandlersChain handlersChain = new HandlersChain(component);
-			String inlineHandler = eventOptionsData.getAttributeValue(component);
-			handlersChain.addInlineHandlerAsValue(facesContext, inlineHandler);
-			handlersChain.addBehaviors(facesContext, behaviorName);
-			String handlerScript = handlersChain.toScript();
-			
-			if (isNotEmpty(handlerScript)) {
-				ajaxEventOptions.set(behaviorName, handlerScript);
-			}
-		}
-	}
-	
-//	public static AjaxEventOptions buildEventOptions(FacesContext facesContext,
-//			UIComponent uiComponent, Map<String, Object> params) {
-//		
-//		return buildEventOptions(facesContext, uiComponent, params, false);
-//	}
-	
-	/**
-	 * @param facesContext
-	 * @param uiComponent
-	 * @return
-	 */
-//	public static Map<String, Object> buildEventOptions(FacesContext facesContext,
-//			UIComponent uiComponent, Map<String, Object> params, boolean omitDefaultActionUrl) {
-//		String clientId = uiComponent.getClientId(facesContext);
-//		Map<String, Object> componentAttributes = uiComponent.getAttributes();
-//		Map<String, Object> options = new HashMap<String, Object>();
+        return ajaxEventOptions;
+    }
+
+    private static boolean isNotEmpty(String value) {
+        return (value != null) && (value.length() != 0);
+    }
+
+    private static void appenAjaxBehaviorOptions(AjaxClientBehavior behavior, AjaxEventOptions ajaxEventOptions) {
+        for (BehaviorEventOptionsData optionsData : BehaviorEventOptionsData.values()) {
+            String eventHandlerValue = optionsData.getAttributeValue(behavior);
+
+            if (isNotEmpty(eventHandlerValue)) {
+                ajaxEventOptions.set(optionsData.toString(), eventHandlerValue);
+            }
+        }
+    }
+
+    private static void appendComponentOptions(FacesContext facesContext, UIComponent component,
+            AjaxEventOptions ajaxEventOptions) {
+        for (EventOptionsData eventOptionsData : EventOptionsData.values()) {
+            String behaviorName = eventOptionsData.toString();
+            HandlersChain handlersChain = new HandlersChain(component);
+            String inlineHandler = eventOptionsData.getAttributeValue(component);
+
+            handlersChain.addInlineHandlerAsValue(facesContext, inlineHandler);
+            handlersChain.addBehaviors(facesContext, behaviorName);
+
+            String handlerScript = handlersChain.toScript();
+
+            if (isNotEmpty(handlerScript)) {
+                ajaxEventOptions.set(behaviorName, handlerScript);
+            }
+        }
+    }
+
+//  public static AjaxEventOptions buildEventOptions(FacesContext facesContext,
+//          UIComponent uiComponent, Map<String, Object> params) {
+//      
+//      return buildEventOptions(facesContext, uiComponent, params, false);
+//  }
+
+    /**
+     * @param facesContext
+     * @param uiComponent
+     * @return
+     */
+//  public static Map<String, Object> buildEventOptions(FacesContext facesContext,
+//          UIComponent uiComponent, Map<String, Object> params, boolean omitDefaultActionUrl) {
+//      String clientId = uiComponent.getClientId(facesContext);
+//      Map<String, Object> componentAttributes = uiComponent.getAttributes();
+//      Map<String, Object> options = new HashMap<String, Object>();
 //
-//		UIComponent nestingContainer = (UIComponent) findAjaxContainer(
-//				facesContext, uiComponent);
-//		String containerClientId = nestingContainer.getClientId(facesContext);
-//		if (containerClientId != null && !AjaxViewRoot.ROOT_ID.equals(containerClientId)) {
-//			options.put("containerId", containerClientId);
-//		}
+//      UIComponent nestingContainer = (UIComponent) findAjaxContainer(
+//              facesContext, uiComponent);
+//      String containerClientId = nestingContainer.getClientId(facesContext);
+//      if (containerClientId != null && !AjaxViewRoot.ROOT_ID.equals(containerClientId)) {
+//          options.put("containerId", containerClientId);
+//      }
 //
-//		Map<String, Object> parameters = new HashMap<String, Object>();
-//		UIComponent targetComponent = (uiComponent instanceof AjaxSupport)?uiComponent.getParent():uiComponent;
-//		// UIForm form = getNestingForm(uiComponent);
-//		// "input" - if assigned to html input element.
-//		boolean input = targetComponent instanceof EditableValueHolder;
-//		// Action component - button etc.
-////		boolean action = targetComponent instanceof ActionSource;
+//      Map<String, Object> parameters = new HashMap<String, Object>();
+//      UIComponent targetComponent = (uiComponent instanceof AjaxSupport)?uiComponent.getParent():uiComponent;
+//      // UIForm form = getNestingForm(uiComponent);
+//      // "input" - if assigned to html input element.
+//      boolean input = targetComponent instanceof EditableValueHolder;
+//      // Action component - button etc.
+////        boolean action = targetComponent instanceof ActionSource;
 //
-//		boolean ajaxSingle = Boolean.TRUE.equals(componentAttributes
-//				.get(AJAX_SINGLE_ATTR));
-//		// For input components in single mode or without form submit input
-//		// control )
-//		if (ajaxSingle ) {
-//			parameters.put(AJAX_SINGLE_PARAMETER_NAME, targetComponent.getClientId(facesContext));
-//			// options.put("single", JSReference.TRUE);
-//			if (input) {
-//				options.put("control", JSReference.THIS);
-//			}
-//		}
-//		// Control value for submit
-//		String controlName;
-//		Object controlValue;
-//		// TODO - make compatible with JSF RI/MyFaces ? use submittedValue ( if
-//		// any ) for UIInput, converted value for ValueHolder.
-//		controlName = clientId;
-//		controlValue = clientId;
-//		parameters.put(controlName, controlValue);
-//		AjaxContext ajaxContext = AjaxContext.getCurrentInstance(facesContext);
-//		
-//		String ajaxActionURL = ajaxContext.getAjaxActionURL(facesContext);
-//		if (omitDefaultActionUrl) {
-//			UIComponent form = getNestingForm(uiComponent);
-//			if (form != null && !RENDERER_UTILS.isBooleanAttribute(form, "ajaxSubmit")) {
-//				if (RENDERER_UTILS.getActionUrl(facesContext).equals(ajaxActionURL)) {
-//					ajaxActionURL = null;
-//				}
-//			}
-//		}
+//      boolean ajaxSingle = Boolean.TRUE.equals(componentAttributes
+//              .get(AJAX_SINGLE_ATTR));
+//      // For input components in single mode or without form submit input
+//      // control )
+//      if (ajaxSingle ) {
+//          parameters.put(AJAX_SINGLE_PARAMETER_NAME, targetComponent.getClientId(facesContext));
+//          // options.put("single", JSReference.TRUE);
+//          if (input) {
+//              options.put("control", JSReference.THIS);
+//          }
+//      }
+//      // Control value for submit
+//      String controlName;
+//      Object controlValue;
+//      // TODO - make compatible with JSF RI/MyFaces ? use submittedValue ( if
+//      // any ) for UIInput, converted value for ValueHolder.
+//      controlName = clientId;
+//      controlValue = clientId;
+//      parameters.put(controlName, controlValue);
+//      AjaxContext ajaxContext = AjaxContext.getCurrentInstance(facesContext);
+//      
+//      String ajaxActionURL = ajaxContext.getAjaxActionURL(facesContext);
+//      if (omitDefaultActionUrl) {
+//          UIComponent form = getNestingForm(uiComponent);
+//          if (form != null && !RENDERER_UTILS.isBooleanAttribute(form, "ajaxSubmit")) {
+//              if (RENDERER_UTILS.getActionUrl(facesContext).equals(ajaxActionURL)) {
+//                  ajaxActionURL = null;
+//              }
+//          }
+//      }
 //
-//		if (ajaxActionURL != null) {
-//			// Setup action URL. For portlet environment, it will be different from
-//			// page. 
-//			options.put("actionUrl", ajaxActionURL);
-//		}
-//		
-//		// Add application-wide Ajax parameters
-//		parameters.putAll(ajaxContext.getCommonAjaxParameters());
-//		// add child parameters
-//		appendParameters(facesContext, uiComponent, parameters);
-//		
-//		if (params != null) {
-//			parameters.putAll(params);
-//		}
-//		
-//		if (!parameters.isEmpty()) {
-//			options.put("parameters", parameters);
-//		}
-//		// parameter to render only current list of areas.
-////		if (isAjaxLimitToList(uiComponent)) {
-////			Set<? extends Object> ajaxAreas = getAjaxAreas(uiComponent);
-////			Set<String> areasIds = new HashSet<String>();
-////			if (null != ajaxAreas) {
-////				for (Iterator<? extends Object> iter = ajaxAreas.iterator(); iter.hasNext();) {
-////					String id = (String) iter.next();
-////					UIComponent comp = RendererUtils.getInstance().
-////						findComponentFor(uiComponent, id);
-////					if (null != comp) {
-////						areasIds.add(comp.getClientId(facesContext));
-////					} else {
-////						areasIds.add(id);
-////					}
-////				}
-////			}
-////			options.put("affected", areasIds);
-////		}
-//		String oncomplete = getAjaxOncomplete(uiComponent);
-//		if (null != oncomplete) {
-//			options.put(ONCOMPLETE_ATTR_NAME, buildAjaxOncomplete(oncomplete));
-//		}
-//		
-//		String beforeupdate = getAjaxOnBeforeDomUpdate(uiComponent);
-//		if (null != beforeupdate) {
-//			options.put(ONBEFOREDOMUPDATE_ATTR_NAME, buildAjaxOnBeforeDomUpdate(beforeupdate));
-//		}
-//		
-//		
-//		String status = getAjaxStatus(uiComponent);
-//		if (null != status) {
-//			options.put("status", status);
-//		}
-//		String queue = (String) componentAttributes.get(AJAX_QUEUE_ATTR);
-//		String implicitQueue = null;
-//		
-//		Integer requestDelay = (Integer) componentAttributes
-//				.get(AJAX_DELAY_ATTR);
-//		if (null != requestDelay && requestDelay.intValue() > 0) {
-//			options.put(AJAX_DELAY_ATTR, requestDelay);
-//			if (null == queue) {
-//				implicitQueue = clientId;
-//			}
-//		}
-//		Boolean ignoreDupResponses = (Boolean) componentAttributes
-//				.get(AJAX_ABORT_ATTR);
-//		if (null != ignoreDupResponses && ignoreDupResponses.booleanValue()) {
-//			options.put(AJAX_ABORT_ATTR, JSReference.TRUE);
-//			if (null == queue) {
-//				implicitQueue = clientId;
-//			}
-//		}
+//      if (ajaxActionURL != null) {
+//          // Setup action URL. For portlet environment, it will be different from
+//          // page. 
+//          options.put("actionUrl", ajaxActionURL);
+//      }
+//      
+//      // Add application-wide Ajax parameters
+//      parameters.putAll(ajaxContext.getCommonAjaxParameters());
+//      // add child parameters
+//      appendParameters(facesContext, uiComponent, parameters);
+//      
+//      if (params != null) {
+//          parameters.putAll(params);
+//      }
+//      
+//      if (!parameters.isEmpty()) {
+//          options.put("parameters", parameters);
+//      }
+//      // parameter to render only current list of areas.
+////        if (isAjaxLimitToList(uiComponent)) {
+////            Set<? extends Object> ajaxAreas = getAjaxAreas(uiComponent);
+////            Set<String> areasIds = new HashSet<String>();
+////            if (null != ajaxAreas) {
+////                for (Iterator<? extends Object> iter = ajaxAreas.iterator(); iter.hasNext();) {
+////                    String id = (String) iter.next();
+////                    UIComponent comp = RendererUtils.getInstance().
+////                        findComponentFor(uiComponent, id);
+////                    if (null != comp) {
+////                        areasIds.add(comp.getClientId(facesContext));
+////                    } else {
+////                        areasIds.add(id);
+////                    }
+////                }
+////            }
+////            options.put("affected", areasIds);
+////        }
+//      String oncomplete = getAjaxOncomplete(uiComponent);
+//      if (null != oncomplete) {
+//          options.put(ONCOMPLETE_ATTR_NAME, buildAjaxOncomplete(oncomplete));
+//      }
+//      
+//      String beforeupdate = getAjaxOnBeforeDomUpdate(uiComponent);
+//      if (null != beforeupdate) {
+//          options.put(ONBEFOREDOMUPDATE_ATTR_NAME, buildAjaxOnBeforeDomUpdate(beforeupdate));
+//      }
+//      
+//      
+//      String status = getAjaxStatus(uiComponent);
+//      if (null != status) {
+//          options.put("status", status);
+//      }
+//      String queue = (String) componentAttributes.get(AJAX_QUEUE_ATTR);
+//      String implicitQueue = null;
+//      
+//      Integer requestDelay = (Integer) componentAttributes
+//              .get(AJAX_DELAY_ATTR);
+//      if (null != requestDelay && requestDelay.intValue() > 0) {
+//          options.put(AJAX_DELAY_ATTR, requestDelay);
+//          if (null == queue) {
+//              implicitQueue = clientId;
+//          }
+//      }
+//      Boolean ignoreDupResponses = (Boolean) componentAttributes
+//              .get(AJAX_ABORT_ATTR);
+//      if (null != ignoreDupResponses && ignoreDupResponses.booleanValue()) {
+//          options.put(AJAX_ABORT_ATTR, JSReference.TRUE);
+//          if (null == queue) {
+//              implicitQueue = clientId;
+//          }
+//      }
 //
-//		if (null != queue) {
-//			options.put(AJAX_QUEUE_ATTR, queue);
-//		} else if (implicitQueue != null) {
-//			options.put("implicitEventsQueue", clientId);
-//		}
+//      if (null != queue) {
+//          options.put(AJAX_QUEUE_ATTR, queue);
+//      } else if (implicitQueue != null) {
+//          options.put("implicitEventsQueue", clientId);
+//      }
 //
-//		ExternalContext externalContext = facesContext.getExternalContext();
-//		String namespace = externalContext.encodeNamespace("");
-//		if (namespace != null && namespace.length() != 0) {
-//			options.put("namespace", namespace);
-//		}
-//		
-//		String similarityGroupingId = (String) componentAttributes.get(SIMILARITY_GROUPING_ID_ATTR);
-//		if (similarityGroupingId == null || similarityGroupingId.length() == 0) {
-//			similarityGroupingId = clientId;
-//		} else {
-//			similarityGroupingId = externalContext.encodeNamespace(similarityGroupingId);
-//		}
-//		
-//		options.put(SIMILARITY_GROUPING_ID_ATTR, similarityGroupingId);
+//      ExternalContext externalContext = facesContext.getExternalContext();
+//      String namespace = externalContext.encodeNamespace("");
+//      if (namespace != null && namespace.length() != 0) {
+//          options.put("namespace", namespace);
+//      }
+//      
+//      String similarityGroupingId = (String) componentAttributes.get(SIMILARITY_GROUPING_ID_ATTR);
+//      if (similarityGroupingId == null || similarityGroupingId.length() == 0) {
+//          similarityGroupingId = clientId;
+//      } else {
+//          similarityGroupingId = externalContext.encodeNamespace(similarityGroupingId);
+//      }
+//      
+//      options.put(SIMILARITY_GROUPING_ID_ATTR, similarityGroupingId);
 //
-//		// request timeout.
-//		Integer timeout = (Integer) componentAttributes.get("timeout");
-//		if (null != timeout && timeout.intValue() > 0) {
-//			options.put("timeout", timeout);
-//		}
-//		// Encoding for requests
-//		String encoding = (String) componentAttributes.get("encoding");
-//		if (null != encoding) {
-//			options.put("encoding", encoding);
-//		}
-//		return options;
-//	}
+//      // request timeout.
+//      Integer timeout = (Integer) componentAttributes.get("timeout");
+//      if (null != timeout && timeout.intValue() > 0) {
+//          options.put("timeout", timeout);
+//      }
+//      // Encoding for requests
+//      String encoding = (String) componentAttributes.get("encoding");
+//      if (null != encoding) {
+//          options.put("encoding", encoding);
+//      }
+//      return options;
+//  }
+//  /**
+//   * Create call to Ajax Submit function with first two parameters
+//   * 
+//   * @param uiComponent
+//   * @param facesContext
+//   * @param functionName
+//   * @return
+//   */
+//  public static JSFunction buildAjaxFunction(UIComponent uiComponent,
+//          FacesContext facesContext) {
+//      JSFunction ajaxFunction = buildAjaxFunction(uiComponent, facesContext,
+//              AJAX_FUNCTION_NAME);
+//      // client-side script must have reference to event-enabled object.
+//      ajaxFunction.addParameter(new JSReference("event"));
+//      return ajaxFunction;
+//  }
 
-//	/**
-//	 * Create call to Ajax Submit function with first two parameters
-//	 * 
-//	 * @param uiComponent
-//	 * @param facesContext
-//	 * @param functionName
-//	 * @return
-//	 */
-//	public static JSFunction buildAjaxFunction(UIComponent uiComponent,
-//			FacesContext facesContext) {
-//		JSFunction ajaxFunction = buildAjaxFunction(uiComponent, facesContext,
-//				AJAX_FUNCTION_NAME);
-//		// client-side script must have reference to event-enabled object.
-//		ajaxFunction.addParameter(new JSReference("event"));
-//		return ajaxFunction;
-//	}
+    /**
+     * Create call to Ajax Submit function with first two parameters
+     * @param facesContext
+     * @param uiComponent
+     * @param functionName
+     *
+     * @return
+     */
+    public static JSFunction buildAjaxFunction(FacesContext facesContext, UIComponent uiComponent,
+            String functionName) {
+        JSFunction ajaxFunction = new JSFunction(functionName);
 
-	/**
-	 * Create call to Ajax Submit function with first two parameters
-	 * @param facesContext
-	 * @param uiComponent
-	 * @param functionName
-	 * 
-	 * @return
-	 */
-	public static JSFunction buildAjaxFunction(FacesContext facesContext,
-			UIComponent uiComponent, String functionName) {
-		JSFunction ajaxFunction = new JSFunction(functionName);
-		ajaxFunction.addParameter(uiComponent.getClientId(facesContext));
-		ajaxFunction.addParameter(JSReference.EVENT);
-		return ajaxFunction;
-	}
+        ajaxFunction.addParameter(uiComponent.getClientId(facesContext));
+        ajaxFunction.addParameter(JSReference.EVENT);
 
-	/**
-	 * Append common parameters ( array of affected areas, status area id, on
-	 * complete function ) to JavaScript event string.
-	 * 
-	 * @param uiComponent
-	 * @param onClick -
-	 *            buffer with JavaScript code eg... AJAX.Submit(form,this
-	 */
-	// public static void appendAjaxSubmitParameters(FacesContext facesContext,
-	// UIComponent uiComponent, StringBuffer onClick)
-	// {
-	// Set ajaxAreas = getAjaxAreas(uiComponent);
-	// onClick.append(',');
-	// // parameter to render only current list of areas.
-	// if (isAjaxLimitToList(uiComponent) && ajaxAreas != null &&
-	// ajaxAreas.size() > 0)
-	// {
-	// onClick.append('[');
-	// Iterator areas = ajaxAreas.iterator();
-	// boolean first = true;
-	// while (areas.hasNext())
-	// {
-	// String element = (String) areas.next();
-	// UIComponent component = uiComponent.findComponent(element);
-	// if (null != component)
-	// {
-	// if (!first)
-	// {
-	// onClick.append(',');
-	// }
-	// else
-	// {
-	// first = false;
-	// }
-	// onClick.append('\'');
-	// onClick.append(component.getClientId(facesContext));
-	// onClick.append('\'');
-	// }
-	// }
-	// onClick.append("]");
-	// }
-	// else
-	// {
-	// onClick.append("null");
-	// }
-	// // insert id of request status element.
-	// onClick.append(',');
-	// String status = getAjaxStatus(uiComponent);
-	// if (null != status)
-	// {
-	// onClick.append('\'').append(status).append('\'');
-	// }
-	// else
-	// {
-	// onClick.append("null");
-	// }
-	// // insert function name for call after completed request
-	// onClick.append(',');
-	// String oncomplete = getAjaxOncomplete(uiComponent);
-	// if (null != oncomplete)
-	// {
-	// onClick.append(oncomplete);
-	// }
-	// else
-	// {
-	// onClick.append("null");
-	// }
-	//
-	// }
-	/**
-	 * Get list of clientId's for given component
-	 * 
-	 * @param uiComponent
-	 * @return List of areas Id's , updated by this component.
-	 */
-	public static Set<String> getAjaxAreas(UIComponent uiComponent) {
-		Object areas;
-		if (uiComponent instanceof AjaxComponent) {
-			areas = ((AjaxComponent) uiComponent).getReRender();
+        return ajaxFunction;
+    }
 
-		} else {
-			areas = uiComponent.getAttributes().get(
-					AjaxRendererUtils.AJAX_REGIONS_ATTRIBUTE);
-		}
-		return asSet(areas);
-	}
+    /**
+     * Append common parameters ( array of affected areas, status area id, on
+     * complete function ) to JavaScript event string.
+     *
+     * @param uiComponent
+     * @param onClick -
+     *            buffer with JavaScript code eg... AJAX.Submit(form,this
+     */
 
-	/**
-	 * Returns set of areas to be processed as a result of this component action invocation
-	 * 
-	 * @param component
-	 * @return set of IDs that should be processed as a 
-	 * @since 3.3.0
-	 */
-	public static Set<String> getAjaxAreasToProcess(UIComponent component) {
-		Object areas;
-		
-		if (component instanceof AjaxComponent) {
-			areas = ((AjaxComponent) component).getProcess();
-		} else {
-			areas = component.getAttributes().get(AjaxRendererUtils.AJAX_PROCESS_ATTRIBUTE);
-		}
-		
-		return asSet(areas);
-	}
-	
-	/**
-	 * Convert parameter ( Collection, List, array, String, comma-separated
-	 * String ) to list of srings. 
-	 * 
-	 * @param valueToSet -
-	 *            obect for convert to List.
-	 * @return - list of strings.
-	 */
-	@SuppressWarnings("unchecked")
-	public static Set<String> asSet(Object valueToSet) {
+    // public static void appendAjaxSubmitParameters(FacesContext facesContext,
+    // UIComponent uiComponent, StringBuffer onClick)
+    // {
+    // Set ajaxAreas = getAjaxAreas(uiComponent);
+    // onClick.append(',');
+    // // parameter to render only current list of areas.
+    // if (isAjaxLimitToList(uiComponent) && ajaxAreas != null &&
+    // ajaxAreas.size() > 0)
+    // {
+    // onClick.append('[');
+    // Iterator areas = ajaxAreas.iterator();
+    // boolean first = true;
+    // while (areas.hasNext())
+    // {
+    // String element = (String) areas.next();
+    // UIComponent component = uiComponent.findComponent(element);
+    // if (null != component)
+    // {
+    // if (!first)
+    // {
+    // onClick.append(',');
+    // }
+    // else
+    // {
+    // first = false;
+    // }
+    // onClick.append('\'');
+    // onClick.append(component.getClientId(facesContext));
+    // onClick.append('\'');
+    // }
+    // }
+    // onClick.append("]");
+    // }
+    // else
+    // {
+    // onClick.append("null");
+    // }
+    // // insert id of request status element.
+    // onClick.append(',');
+    // String status = getAjaxStatus(uiComponent);
+    // if (null != status)
+    // {
+    // onClick.append('\'').append(status).append('\'');
+    // }
+    // else
+    // {
+    // onClick.append("null");
+    // }
+    // // insert function name for call after completed request
+    // onClick.append(',');
+    // String oncomplete = getAjaxOncomplete(uiComponent);
+    // if (null != oncomplete)
+    // {
+    // onClick.append(oncomplete);
+    // }
+    // else
+    // {
+    // onClick.append("null");
+    // }
+    //
+    // }
 
-		if (null != valueToSet) {
-			// Simplest case - set.
-			if (valueToSet instanceof Set) {
-				return new LinkedHashSet<String>((Set<String>)valueToSet);
-			}
-			// Other collections.
-			else if (valueToSet instanceof Collection) {
-				return new LinkedHashSet<String>((Collection<String>) valueToSet);
-			}
-			// Array
-			else if (OBJECT_ARRAY_CLASS.isAssignableFrom(valueToSet.getClass())) {
-				return new LinkedHashSet<String>(Arrays.asList((String[]) valueToSet));
-			}
-			// Tokenize string.
-			else if (valueToSet instanceof String) {
-				String areasString = ((String) valueToSet).trim();
-				if (areasString.contains(",") || areasString.contains(" ")) {
-					return new LinkedHashSet<String>(Arrays.asList(areasString.split(
-							"(\\s*,\\s*)|(\\s+)")));
-				} else {
-					Set<String> areasSet = new LinkedHashSet<String>(5);
-					areasSet.add(areasString);
-					return areasSet;
-				}
+    /**
+     * Get list of clientId's for given component
+     *
+     * @param uiComponent
+     * @return List of areas Id's , updated by this component.
+     */
+    public static Set<String> getAjaxAreas(UIComponent uiComponent) {
+        Object areas;
 
-			}
-		}
-		return null;
-	}
-	
-	/**
-	 * Get status area Id for given component.
-	 * 
-	 * @param component
-	 * @return clientId of status area, or <code>null</code>
-	 */
-	public static String getAjaxStatus(UIComponent component) {
-		String statusId;
-		if (component instanceof AjaxComponent) {
-			statusId = ((AjaxComponent) component).getStatus();
+        if (uiComponent instanceof AjaxComponent) {
+            areas = ((AjaxComponent) uiComponent).getReRender();
+        } else {
+            areas = uiComponent.getAttributes().get(AjaxRendererUtils.AJAX_REGIONS_ATTRIBUTE);
+        }
 
-		} else {
-			statusId = (String) component.getAttributes().get(STATUS_ATTR_NAME);
-		}
-		
-		return statusId;
-		
-//		if (null != statusId) {
-//			UIComponent status = RendererUtils.getInstance().
-//				findComponentFor(component, statusId);
+        return asSet(areas);
+    }
+
+    /**
+     * Returns set of areas to be processed as a result of this component action invocation
+     *
+     * @param component
+     * @return set of IDs that should be processed as a
+     * @since 3.3.0
+     */
+    public static Set<String> getAjaxAreasToProcess(UIComponent component) {
+        Object areas;
+
+        if (component instanceof AjaxComponent) {
+            areas = ((AjaxComponent) component).getProcess();
+        } else {
+            areas = component.getAttributes().get(AjaxRendererUtils.AJAX_PROCESS_ATTRIBUTE);
+        }
+
+        return asSet(areas);
+    }
+
+    /**
+     * Convert parameter ( Collection, List, array, String, comma-separated
+     * String ) to list of srings.
+     *
+     * @param valueToSet -
+     *            obect for convert to List.
+     * @return - list of strings.
+     */
+    @SuppressWarnings("unchecked")
+    public static Set<String> asSet(Object valueToSet) {
+        if (null != valueToSet) {
+
+            // Simplest case - set.
+            if (valueToSet instanceof Set) {
+                return new LinkedHashSet<String>((Set<String>) valueToSet);
+            } else if (valueToSet instanceof Collection) { // Other collections.
+                return new LinkedHashSet<String>((Collection<String>) valueToSet);
+            } else if (OBJECT_ARRAY_CLASS.isAssignableFrom(valueToSet.getClass())) { // Array
+                return new LinkedHashSet<String>(Arrays.asList((String[]) valueToSet));
+            } else if (valueToSet instanceof String) { // Tokenize string.
+                String areasString = ((String) valueToSet).trim();
+
+                if (areasString.contains(",") || areasString.contains(" ")) {
+                    return new LinkedHashSet<String>(Arrays.asList(areasString.split("(\\s*,\\s*)|(\\s+)")));
+                } else {
+                    Set<String> areasSet = new LinkedHashSet<String>(5);
+
+                    areasSet.add(areasString);
+
+                    return areasSet;
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Get status area Id for given component.
+     *
+     * @param component
+     * @return clientId of status area, or <code>null</code>
+     */
+    public static String getAjaxStatus(UIComponent component) {
+        String statusId;
+
+        if (component instanceof AjaxComponent) {
+            statusId = ((AjaxComponent) component).getStatus();
+        } else {
+            statusId = (String) component.getAttributes().get(STATUS_ATTR_NAME);
+        }
+
+        return statusId;
+
+//      if (null != statusId) {
+//          UIComponent status = RendererUtils.getInstance().
+//              findComponentFor(component, statusId);
 //
-//			if (null != status) {
-//				statusId = status
-//						.getClientId(FacesContext.getCurrentInstance());
-//			} else {
-//				LOG.warn(Messages.getMessage(
-//						Messages.AJAX_STATUS_COMPONENT_NOT_FOWND_WARNING,
-//						component.getId()));
-//			}
-//		}
-//		return statusId;
-	}
+//          if (null != status) {
+//              statusId = status
+//                      .getClientId(FacesContext.getCurrentInstance());
+//          } else {
+//              LOG.warn(Messages.getMessage(
+//                      Messages.AJAX_STATUS_COMPONENT_NOT_FOWND_WARNING,
+//                      component.getId()));
+//          }
+//      }
+//      return statusId;
+    }
 
-	public static JSFunctionDefinition buildAjaxOncomplete(String body) {
-		JSFunctionDefinition function = new JSFunctionDefinition("request", "event", "data");
-		function.addToBody(body);
+    public static JSFunctionDefinition buildAjaxOncomplete(String body) {
+        JSFunctionDefinition function = new JSFunctionDefinition("request", "event", "data");
 
-		return function;
-	}
-	
-	public static JSFunctionDefinition buildAjaxOnBeforeDomUpdate(String body) {
-		JSFunctionDefinition function = new JSFunctionDefinition("request", "event", "data");
-		function.addToBody(body);
+        function.addToBody(body);
 
-		return function;
-	}
+        return function;
+    }
 
-	/**
-	 * Get function name for call on completed ajax request.
-	 * 
-	 * @param component
-	 *            for wich calculate function name
-	 * @return name of JavaScript function or <code>null</code>
-	 */
-	public static String getAjaxOncomplete(UIComponent component) {
-		if (component instanceof AjaxComponent) {
-			return ((AjaxComponent) component).getOncomplete();
+    public static JSFunctionDefinition buildAjaxOnBeforeDomUpdate(String body) {
+        JSFunctionDefinition function = new JSFunctionDefinition("request", "event", "data");
 
-		}
-		return (String) component.getAttributes().get(ONCOMPLETE_ATTR_NAME);
-	}
+        function.addToBody(body);
 
-	/**
-	 * Get function name for call before update DOM.
-	 * 
-	 * @param component
-	 *            for wich calculate function name
-	 * @return name of JavaScript function or <code>null</code>
-	 */
-	public static String getAjaxOnBeforeDomUpdate(UIComponent component) {
-		if (component instanceof AjaxComponent) {
-			return ((AjaxComponent) component).getOnbeforedomupdate();
+        return function;
+    }
 
-		}
-		return (String) component.getAttributes().get(ONBEFOREDOMUPDATE_ATTR_NAME);
-	}
-	
-	public static String getAjaxOnBegin(UIComponent component) {
-		if (component instanceof AjaxComponent) {
-			return ((AjaxComponent) component).getOnbegin();
-		}
+    /**
+     * Get function name for call on completed ajax request.
+     *
+     * @param component
+     *            for wich calculate function name
+     * @return name of JavaScript function or <code>null</code>
+     */
+    public static String getAjaxOncomplete(UIComponent component) {
+        if (component instanceof AjaxComponent) {
+            return ((AjaxComponent) component).getOncomplete();
+        }
 
-		return (String) component.getAttributes().get(ONBEGIN_ATTR_NAME);
-	}
-	
-	/**
-	 * Calculate, must be component render only given areas, or all sended from
-	 * server.
-	 * 
-	 * @param component
-	 * @return <code>true</code> if client must render ONLY given areas.
-	 */
-	public static boolean isAjaxLimitRender(UIComponent component) {
-		boolean result = false;
-		if (component instanceof AjaxComponent) {
-			result = ((AjaxComponent) component).isLimitRender();
+        return (String) component.getAttributes().get(ONCOMPLETE_ATTR_NAME);
+    }
 
-		} else {
-			try {
-				result = ((Boolean) component.getAttributes().get(
-						LIMITRENDER_ATTR_NAME)).booleanValue();
-			} catch (NullPointerException e) {
-				// NullPointer - ignore ...
-			} catch (ClassCastException e1) {
-				// not Boolean - false ...
-			}
-		}
-		return result;
-	}
+    /**
+     * Get function name for call before update DOM.
+     *
+     * @param component
+     *            for wich calculate function name
+     * @return name of JavaScript function or <code>null</code>
+     */
+    public static String getAjaxOnBeforeDomUpdate(UIComponent component) {
+        if (component instanceof AjaxComponent) {
+            return ((AjaxComponent) component).getOnbeforedomupdate();
+        }
 
-	/**
-	 * Replacement for buggy in MyFaces <code>RendererUtils</code>
-	 * 
-	 * @param component
-	 * @return
-	 */
-	public static String getAbsoluteId(UIComponent component) {
-		if (component == null) {
-			throw new NullPointerException(Messages
-					.getMessage(Messages.COMPONENT_NULL_ERROR_2));
+        return (String) component.getAttributes().get(ONBEFOREDOMUPDATE_ATTR_NAME);
+    }
+
+    public static String getAjaxOnBegin(UIComponent component) {
+        if (component instanceof AjaxComponent) {
+            return ((AjaxComponent) component).getOnbegin();
         }
 
-		StringBuffer idBuf = new StringBuffer();
+        return (String) component.getAttributes().get(ONBEGIN_ATTR_NAME);
+    }
 
-		idBuf.append(component.getId());
+    /**
+     * Calculate, must be component render only given areas, or all sended from
+     * server.
+     *
+     * @param component
+     * @return <code>true</code> if client must render ONLY given areas.
+     */
+    public static boolean isAjaxLimitRender(UIComponent component) {
+        boolean result = false;
 
-		UIComponent parent = component;
+        if (component instanceof AjaxComponent) {
+            result = ((AjaxComponent) component).isLimitRender();
+        } else {
+            try {
+                result = ((Boolean) component.getAttributes().get(LIMITRENDER_ATTR_NAME)).booleanValue();
+            } catch (NullPointerException e) {
 
-		while ((parent = parent.getParent()) != null) {
-			if (parent instanceof NamingContainer) {
-				idBuf.insert(0, NamingContainer.SEPARATOR_CHAR);
-				idBuf.insert(0, parent.getId());
-			}
-		}
-		idBuf.insert(0, NamingContainer.SEPARATOR_CHAR);
-		LOG.debug(Messages.getMessage(Messages.CALCULATE_COMPONENT_ID_INFO,
-				component.getId(), idBuf.toString()));
-		return idBuf.toString();
-	}
+                // NullPointer - ignore ...
+            } catch (ClassCastException e1) {
 
-	/**
-	 * Find nested form for given component
-	 * 
-	 * @param component
-	 * @return nested <code>UIForm</code> component, or <code>null</code>
-	 */
-	public static UIComponent getNestingForm(UIComponent component) {
-		UIComponent parent = component;
-		// Search enclosed UIForm or ADF UIXForm component
-		while (parent != null
-				&& !(parent instanceof UIForm)
-				&& !("org.apache.myfaces.trinidad.Form".equals(parent
-						.getFamily()))
-				&& !("oracle.adf.Form".equals(parent.getFamily()))) {
-			parent = parent.getParent();
-		}
+                // not Boolean - false ...
+            }
+        }
 
-		return parent;
-	}
+        return result;
+    }
 
-	protected static String getAjaxActionUrl(FacesContext facesContext) {
-	    	return AjaxContext.getCurrentInstance(facesContext).getAjaxActionURL(facesContext);
-	}
+    /**
+     * Replacement for buggy in MyFaces <code>RendererUtils</code>
+     *
+     * @param component
+     * @return
+     */
+    public static String getAbsoluteId(UIComponent component) {
+        if (component == null) {
+            throw new NullPointerException(Messages.getMessage(Messages.COMPONENT_NULL_ERROR_2));
+        }
 
-	/**
-	 * @param facesContext
-	 * @param uiComponent
-	 * @return
-	 */
-	public static org.ajax4jsf.component.AjaxContainer findAjaxContainer(
-			FacesContext facesContext, UIComponent uiComponent) {
-		UIComponent parent = uiComponent.getParent();
-		while (parent != null
-				&& !(parent instanceof org.ajax4jsf.component.AjaxContainer)) {
-			parent = parent.getParent();
-		}
+        StringBuffer idBuf = new StringBuffer();
 
-		org.ajax4jsf.component.AjaxContainer nestingContainer = null;
-		if (parent != null) {
-			// link is nested inside a form
-			nestingContainer = (org.ajax4jsf.component.AjaxContainer) parent;
-		} else if (facesContext.getViewRoot() instanceof AjaxViewRoot) {
-			nestingContainer = (AjaxContainer) facesContext.getViewRoot();
-		}
-		return nestingContainer;
-	}
+        idBuf.append(component.getId());
 
-	/**
-	 * Encode rendered areas as special HTML tag ( span in current release )
-	 * 
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	public static void encodeAreas(FacesContext context,
-			UIComponent component) throws IOException {
-		AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
-		ExternalContext externalContext = context.getExternalContext();
-		Map<String, Object> requestMap = externalContext.getRequestMap();
-		Set<String> rendered = ajaxContext.getAjaxRenderedAreas();
+        UIComponent parent = component;
 
-		// write special area for list of rendered elements. Client-side
-		// Java
-		// Script
-		// read this structure for update areas of DOM tree.
-		ResponseWriter out = context.getResponseWriter();
-		// Create <span> element to keep list rendered aread ( in title
-		// attribute )
-		// More right will create special namespace for such
-		// information,
-		// but I want to keep simple html ( xhtml ) document - on case
-		// I have troubles with microsoft XMLHTTP validations.
-		out.startElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG, component);
-		out.writeAttribute(HTML.NAME_ATTRIBUTE, AjaxContainerRenderer.AJAX_UPDATE_HEADER, null);
+        while ((parent = parent.getParent()) != null) {
+            if (parent instanceof NamingContainer) {
+                idBuf.insert(0, NamingContainer.SEPARATOR_CHAR);
+                idBuf.insert(0, parent.getId());
+            }
+        }
 
+        idBuf.insert(0, NamingContainer.SEPARATOR_CHAR);
+        LOG.debug(Messages.getMessage(Messages.CALCULATE_COMPONENT_ID_INFO, component.getId(), idBuf.toString()));
+
+        return idBuf.toString();
+    }
+
+    /**
+     * Find nested form for given component
+     *
+     * @param component
+     * @return nested <code>UIForm</code> component, or <code>null</code>
+     */
+    public static UIComponent getNestingForm(UIComponent component) {
+        UIComponent parent = component;
+
+        // Search enclosed UIForm or ADF UIXForm component
+        while ((parent != null) && !(parent instanceof UIForm)
+                && !("org.apache.myfaces.trinidad.Form".equals(parent.getFamily()))
+                && !("oracle.adf.Form".equals(parent.getFamily()))) {
+            parent = parent.getParent();
+        }
+
+        return parent;
+    }
+
+    protected static String getAjaxActionUrl(FacesContext facesContext) {
+        return AjaxContext.getCurrentInstance(facesContext).getAjaxActionURL(facesContext);
+    }
+
+    /**
+     * @param facesContext
+     * @param uiComponent
+     * @return
+     */
+    public static org.ajax4jsf.component.AjaxContainer findAjaxContainer(FacesContext facesContext,
+            UIComponent uiComponent) {
+        UIComponent parent = uiComponent.getParent();
+
+        while ((parent != null) && !(parent instanceof org.ajax4jsf.component.AjaxContainer)) {
+            parent = parent.getParent();
+        }
+
+        org.ajax4jsf.component.AjaxContainer nestingContainer = null;
+
+        if (parent != null) {
+
+            // link is nested inside a form
+            nestingContainer = (org.ajax4jsf.component.AjaxContainer) parent;
+        } else if (facesContext.getViewRoot() instanceof AjaxViewRoot) {
+            nestingContainer = (AjaxContainer) facesContext.getViewRoot();
+        }
+
+        return nestingContainer;
+    }
+
+    /**
+     * Encode rendered areas as special HTML tag ( span in current release )
+     *
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    public static void encodeAreas(FacesContext context, UIComponent component) throws IOException {
+        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
+        ExternalContext externalContext = context.getExternalContext();
+        Map<String, Object> requestMap = externalContext.getRequestMap();
+        Set<String> rendered = ajaxContext.getAjaxRenderedAreas();
+
+        // write special area for list of rendered elements. Client-side
+        // Java
+        // Script
+        // read this structure for update areas of DOM tree.
+        ResponseWriter out = context.getResponseWriter();
+
+        // Create <span> element to keep list rendered aread ( in title
+        // attribute )
+        // More right will create special namespace for such
+        // information,
+        // but I want to keep simple html ( xhtml ) document - on case
+        // I have troubles with microsoft XMLHTTP validations.
+        out.startElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG, component);
+        out.writeAttribute(HTML.NAME_ATTRIBUTE, AjaxContainerRenderer.AJAX_UPDATE_HEADER, null);
+
         StringBuffer senderString = new StringBuffer();
-		for (Iterator<String> it = rendered.iterator(); it.hasNext();) {
-			String id = it.next();
-			senderString.append(id);
-			if (it.hasNext()) {
-				senderString.append(',');
-			}
-		}
-		out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR, senderString, null);
-		out.endElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG);
-		// For sequences and client-saved states.
 
-		out.startElement(AjaxContainerRenderer.AJAX_VIEW_STATE_TAG, component);
-		out.writeAttribute(HTML.id_ATTRIBUTE,
-				AjaxContainerRenderer.AJAX_VIEW_STATE_ID, null);
-		writeState(context);
-		out.endElement(AjaxContainerRenderer.AJAX_VIEW_STATE_TAG);
-		// Write rendered flag to html <meta>
-		out
-				.startElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG,
-						component);
-		out.writeAttribute(HTML.id_ATTRIBUTE,
-				AjaxContainerRenderer.AJAX_FLAG_HEADER, null);
-		out.writeAttribute(HTML.NAME_ATTRIBUTE,
-				AjaxContainerRenderer.AJAX_FLAG_HEADER, null);
-		out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR, "true", null);
-		out.endElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG);
-		// set response header with list of rendered ID's
-		Object response = externalContext.getResponse();
-		// Use reflection for send responce headers - we can get
-		// different responces classes
-		// for different environment ( portal, cocoon etc )
-		if (response instanceof HttpServletResponse) {
-			HttpServletResponse httpResponse = (HttpServletResponse) response;
-//			httpResponse.setHeader(AjaxContainerRenderer.AJAX_UPDATE_HEADER,
-//					senderString.toString());
-			httpResponse.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER, "true");
-		} else {
-			try {
-				Method setHeadergMethod = response.getClass()
-						.getMethod("setHeader", new Class[] { String.class, String.class });
-//				setHeadergMethod.invoke(response, new Object[] {
-//						AjaxContainerRenderer.AJAX_UPDATE_HEADER,
-//						senderString.toString() });
-				setHeadergMethod.invoke(response, AjaxContainerRenderer.AJAX_FLAG_HEADER, "true");
-			} catch (Exception e) {
-				LOG.error(Messages.getMessage(Messages.DETECTING_ENCODING_DISABLED_ERROR));
-				LOG.error(Messages.getMessage(Messages.OBTAIN_RESPONSE_SET_HEADER_ERROR, e));
-			}
-		}
-		Map<String, Object> responseDataMap = ajaxContext.getResponseDataMap();
-		// Get data serializer instance
-		AJAXDataSerializer serializer = (AJAXDataSerializer) ServicesUtils
-				.getServiceInstance(AJAXDataSerializer.SERVICE);
-		// Put data to JavaScript handlers, inside <span> elements.
-		for (Map.Entry<String, Object> entry : responseDataMap.entrySet()) {
-			out.startElement(HTML.SPAN_ELEM, component);
-			out.writeAttribute(HTML.id_ATTRIBUTE, entry.getKey(), null);
-			String dataString = serializer.asString(entry.getValue());
-			out.write(dataString);
-			out.endElement(HTML.SPAN_ELEM);
-		}
-		// Include active 'oncomplete' function content :
-		Object oncomplete = ajaxContext.getOncomplete();
-		if(null != oncomplete){
-			out.startElement(HTML.SPAN_ELEM, component);
-			out.writeAttribute(HTML.id_ATTRIBUTE, ONCOMPLETE_CONTENT_ID, null);
-			out.writeText(oncomplete,null);
-			out.endElement(HTML.SPAN_ELEM);
-		}
-		// For self-rendered case, we use own methods for replace stateKey by
-		// real value in XML filter.
-		// if(ajaxContext.isSelfRender()){
-		// saveViewState(context, out);
-		// }
-		requestMap.put(AJAX_AREAS_RENDERED, "true");
-	}
+        for (Iterator<String> it = rendered.iterator(); it.hasNext(); ) {
+            String id = it.next();
 
-	/**
-	 * Write state saving markers to context, include MyFaces view sequence.
-	 * 
-	 * @param context
-	 * @throws IOException
-	 */
-	public static void writeState(FacesContext context) throws IOException {
-		context.getApplication().getViewHandler().writeState(context);
-	}
+            senderString.append(id);
 
-	/**
-	 * Encode declaration for AJAX response. Render &lt;html&gt;&lt;body&gt;
-	 * 
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	public static void encodeAjaxBegin(FacesContext context,
-			UIComponent component) throws IOException {
-		// AjaxContainer ajax = (AjaxContainer) component;
-		ResponseWriter out = context.getResponseWriter();
-		// DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
-		out.startElement("html", component);
-		Locale locale = context.getViewRoot().getLocale();
-		out.writeAttribute(HTML.lang_ATTRIBUTE, locale.toString(), "lang");
-		out.startElement("body", component);
-	}
+            if (it.hasNext()) {
+                senderString.append(',');
+            }
+        }
 
-	/**
-	 * End encoding of AJAX response. Render tag with included areas and close
-	 * &lt;/body&gt;&lt;/html&gt;
-	 * 
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	public static void encodeAjaxEnd(FacesContext context, UIComponent component)
-			throws IOException {
-		// AjaxContainer ajax = (AjaxContainer) component;
-		ResponseWriter out = context.getResponseWriter();
-		// DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
+        out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR, senderString, null);
+        out.endElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG);
 
-		encodeAreas(context, component);
-			out.endElement("body");
-			out.endElement("html");
-	}
+        // For sequences and client-saved states.
+        out.startElement(AjaxContainerRenderer.AJAX_VIEW_STATE_TAG, component);
+        out.writeAttribute(HTML.ID_ATTRIBUTE, AjaxContainerRenderer.AJAX_VIEW_STATE_ID, null);
+        writeState(context);
+        out.endElement(AjaxContainerRenderer.AJAX_VIEW_STATE_TAG);
 
-	/**
-	 * Find all instances of {@link UILoadBundle} in view tree and load bundles
-	 * to request-scope map.
-	 * 
-	 * @param context
-	 * @throws IOException
-	 */
-	public static void loadBundles(FacesContext context) {
-		// TODO - performanse improove - don't seek by all components tree.
-		loadBundles(context, context.getViewRoot());
+        // Write rendered flag to html <meta>
+        out.startElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG, component);
+        out.writeAttribute(HTML.ID_ATTRIBUTE, AjaxContainerRenderer.AJAX_FLAG_HEADER, null);
+        out.writeAttribute(HTML.NAME_ATTRIBUTE, AjaxContainerRenderer.AJAX_FLAG_HEADER, null);
+        out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR, "true", null);
+        out.endElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG);
 
-	}
+        // set response header with list of rendered ID's
+        Object response = externalContext.getResponse();
 
-	/**
-	 * Recursive helper for {@link #loadBundles(FacesContext)}
-	 * 
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	private static void loadBundles(FacesContext context, UIComponent component) {
-		// Iterate over cildrens
-		for (UIComponent child : component.getChildren()) {
-			loadCildBundles(context, child);
-		}
-		// Iterate over facets
-		for (UIComponent child : component.getFacets().values()) {
-			loadCildBundles(context, child);
-		}
-	}
+        // Use reflection for send responce headers - we can get
+        // different responces classes
+        // for different environment ( portal, cocoon etc )
+        if (response instanceof HttpServletResponse) {
+            HttpServletResponse httpResponse = (HttpServletResponse) response;
 
-	/**
-	 * @param context
-	 * @param child
-	 */
-	private static void loadCildBundles(FacesContext context, UIComponent child) {
-		if (child instanceof AjaxLoadBundleComponent) {
-			try {
-				child.encodeBegin(context);
-			} catch (IOException e) {
-				// DO nothing - really, LoadBundle don't can throw exceptions.
-			}
-		} else {
-			loadBundles(context, child);
-		}
-	}
+            httpResponse.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER, "true");
+        } else {
+            try {
+                Method setHeadergMethod = response.getClass().getMethod("setHeader",
+                        new Class[] {String.class, String.class});
 
-	/**
-	 * @param facesContext
-	 * @return
-	 */
-	public static boolean isAjaxRequest(FacesContext facesContext) {
-		
-		return AjaxContext.getCurrentInstance(facesContext).isAjaxRequest();
-	}
+                setHeadergMethod.invoke(response, AjaxContainerRenderer.AJAX_FLAG_HEADER, "true");
+            } catch (Exception e) {
+                LOG.error(Messages.getMessage(Messages.DETECTING_ENCODING_DISABLED_ERROR));
+                LOG.error(Messages.getMessage(Messages.OBTAIN_RESPONSE_SET_HEADER_ERROR, e));
+            }
+        }
 
-	/**
-	 * TODO: add deprecation
-	 * 
-	 * @param facesContext
-	 * @param component
-	 * @param id
-	 */
-	public static void addRegionByName(FacesContext facesContext, UIComponent component, String id) {
+        Map<String, Object> responseDataMap = ajaxContext.getResponseDataMap();
 
-		AjaxContext.getCurrentInstance(facesContext).addComponentToAjaxRender(component, id);
-	}
-	/**
-	 * @param facesContext
-	 * @param component
-	 */
-	public static void addRegionsFromComponent(UIComponent component, FacesContext facesContext) {
+        // Get data serializer instance
+        AJAXDataSerializer serializer =
+            (AJAXDataSerializer) ServicesUtils.getServiceInstance(AJAXDataSerializer.SERVICE);
 
-		AjaxContext.getCurrentInstance(facesContext).addRegionsFromComponent(component);
-	}
+        // Put data to JavaScript handlers, inside <span> elements.
+        for (Map.Entry<String, Object> entry : responseDataMap.entrySet()) {
+            out.startElement(HTML.SPAN_ELEM, component);
+            out.writeAttribute(HTML.ID_ATTRIBUTE, entry.getKey(), null);
+
+            String dataString = serializer.asString(entry.getValue());
+
+            out.write(dataString);
+            out.endElement(HTML.SPAN_ELEM);
+        }
+
+        // Include active 'oncomplete' function content :
+        Object oncomplete = ajaxContext.getOncomplete();
+
+        if (null != oncomplete) {
+            out.startElement(HTML.SPAN_ELEM, component);
+            out.writeAttribute(HTML.ID_ATTRIBUTE, ONCOMPLETE_CONTENT_ID, null);
+            out.writeText(oncomplete, null);
+            out.endElement(HTML.SPAN_ELEM);
+        }
+
+        // For self-rendered case, we use own methods for replace stateKey by
+        // real value in XML filter.
+        // if(ajaxContext.isSelfRender()){
+        // saveViewState(context, out);
+        // }
+        requestMap.put(AJAX_AREAS_RENDERED, "true");
+    }
+
+    /**
+     * Write state saving markers to context, include MyFaces view sequence.
+     *
+     * @param context
+     * @throws IOException
+     */
+    public static void writeState(FacesContext context) throws IOException {
+        context.getApplication().getViewHandler().writeState(context);
+    }
+
+    /**
+     * Encode declaration for AJAX response. Render &lt;html&gt;&lt;body&gt;
+     *
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    public static void encodeAjaxBegin(FacesContext context, UIComponent component) throws IOException {
+
+        // AjaxContainer ajax = (AjaxContainer) component;
+        ResponseWriter out = context.getResponseWriter();
+
+        // DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
+        out.startElement("html", component);
+
+        Locale locale = context.getViewRoot().getLocale();
+
+        out.writeAttribute(HTML.LANG_ATTRIBUTE, locale.toString(), "lang");
+        out.startElement("body", component);
+    }
+
+    /**
+     * End encoding of AJAX response. Render tag with included areas and close
+     * &lt;/body&gt;&lt;/html&gt;
+     *
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    public static void encodeAjaxEnd(FacesContext context, UIComponent component) throws IOException {
+
+        // AjaxContainer ajax = (AjaxContainer) component;
+        ResponseWriter out = context.getResponseWriter();
+
+        // DebugUtils.traceView("ViewRoot in AJAX Page encode begin");
+        encodeAreas(context, component);
+        out.endElement("body");
+        out.endElement("html");
+    }
+
+    /**
+     * Find all instances of {@link UILoadBundle} in view tree and load bundles
+     * to request-scope map.
+     *
+     * @param context
+     * @throws IOException
+     */
+    public static void loadBundles(FacesContext context) {
+
+        // TODO - performanse improove - don't seek by all components tree.
+        loadBundles(context, context.getViewRoot());
+    }
+
+    /**
+     * Recursive helper for {@link #loadBundles(FacesContext)}
+     *
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    private static void loadBundles(FacesContext context, UIComponent component) {
+
+        // Iterate over cildrens
+        for (UIComponent child : component.getChildren()) {
+            loadCildBundles(context, child);
+        }
+
+        // Iterate over facets
+        for (UIComponent child : component.getFacets().values()) {
+            loadCildBundles(context, child);
+        }
+    }
+
+    /**
+     * @param context
+     * @param child
+     */
+    private static void loadCildBundles(FacesContext context, UIComponent child) {
+        if (child instanceof AjaxLoadBundleComponent) {
+            try {
+                child.encodeBegin(context);
+            } catch (IOException e) {
+
+                // DO nothing - really, LoadBundle don't can throw exceptions.
+            }
+        } else {
+            loadBundles(context, child);
+        }
+    }
+
+    /**
+     * @param facesContext
+     * @return
+     */
+    public static boolean isAjaxRequest(FacesContext facesContext) {
+        return AjaxContext.getCurrentInstance(facesContext).isAjaxRequest();
+    }
+
+    /**
+     * TODO: add deprecation
+     *
+     * @param facesContext
+     * @param component
+     * @param id
+     */
+    public static void addRegionByName(FacesContext facesContext, UIComponent component, String id) {
+        AjaxContext.getCurrentInstance(facesContext).addComponentToAjaxRender(component, id);
+    }
+
+    /**
+     * @param facesContext
+     * @param component
+     */
+    public static void addRegionsFromComponent(UIComponent component, FacesContext facesContext) {
+        AjaxContext.getCurrentInstance(facesContext).addRegionsFromComponent(component);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxViewRootRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxViewRootRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxViewRootRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,42 +19,39 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.renderkit;
 
-import javax.faces.component.UIComponent;
 
+package org.ajax4jsf.renderkit;
+
 import org.ajax4jsf.component.AjaxViewRoot;
 import org.ajax4jsf.resource.InternetResource;
 
+import javax.faces.component.UIComponent;
+
 /**
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.3 $ $Date: 2007/02/08 15:02:03 $
- * 
+ *
  */
 public class AjaxViewRootRenderer extends AjaxContainerRenderer {
 
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.renderkit.AjaxComponentRendererBase#getScripts()
+     */
+    protected InternetResource[] getScripts() {
 
-	
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.renderkit.AjaxComponentRendererBase#getScripts()
-	 */
-	protected InternetResource[] getScripts() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+        // TODO Auto-generated method stub
+        return null;
+    }
 
-
-
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.renderkit.AjaxContainerRenderer#getComponentClass()
-	 */
-	protected Class<? extends UIComponent> getComponentClass() {
-		return AjaxViewRoot.class;
-	}
-
-
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.renderkit.AjaxContainerRenderer#getComponentClass()
+     */
+    protected Class<? extends UIComponent> getComponentClass() {
+        return AjaxViewRoot.class;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKit.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKit.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKit.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
 import javax.faces.render.RenderKit;
@@ -30,11 +32,8 @@
  */
 public interface ChameleonRenderKit {
 
-
-
-	/**
-	 * @param renderKit
-	 */
-	void setDefaultRenderKit(RenderKit renderKit);
-
+    /**
+     * @param renderKit
+     */
+    void setDefaultRenderKit(RenderKit renderKit);
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitFactory.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitFactory.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitFactory.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
+import org.ajax4jsf.Messages;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.util.Iterator;
 
 import javax.faces.FactoryFinder;
@@ -29,99 +37,104 @@
 import javax.faces.render.RenderKit;
 import javax.faces.render.RenderKitFactory;
 
-import org.ajax4jsf.Messages;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * @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";
+    // "AJAX_BASE_RENDERKIT_ID";
     // private static final String AJAX_RENDER_KIT_PARAMETER =
-        // "AJAX_RENDER_KIT_ID";
+    // "AJAX_RENDER_KIT_ID";
+    private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
+    RenderKitFactory defaultFactory;
 
-	private static final Logger _log = RichfacesLogger.RENDERKIT.getLogger();
-
     /**
-         * @param defaultFactory
-         */
+     *     @param defaultFactory
+     */
     public ChameleonRenderKitFactory(RenderKitFactory defaultFactory) {
-	if (_log.isDebugEnabled()) {
-	    _log.debug("ChameleonRenderKitFactory(RenderKitFactory) - Chameleon RenderKit factory instantiated"); //$NON-NLS-1$
-	}
-	this.defaultFactory = defaultFactory;
+        if (LOG.isDebugEnabled()) {
+
+            // $NON-NLS-1$
+            LOG.debug("ChameleonRenderKitFactory(RenderKitFactory) - Chameleon RenderKit factory instantiated");
+        }
+
+        this.defaultFactory = defaultFactory;
     }
 
     /**
-         * @param renderKitId
-         * @param renderKit
-         */
+     *     @param renderKitId
+     *     @param renderKit
+     */
     public void addRenderKit(String renderKitId, RenderKit 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);
+        if (LOG.isDebugEnabled()) {
+
+            // $NON-NLS-1$
+            LOG.debug("addRenderKit(String, RenderKit) - Added RenderKit with id - renderKitId=" + renderKitId);
+        }
+
+        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<String> getRenderKitIds() {
-	return defaultFactory.getRenderKitIds();
+        return defaultFactory.getRenderKitIds();
     }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitImpl.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitImpl.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitImpl.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,10 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
 import java.io.OutputStream;
 import java.io.Writer;
+
 import java.util.HashMap;
 import java.util.Map;
 
@@ -39,52 +42,43 @@
 /**
  * Wrapper for default applikation render kit. Only can append any
  * custom renderers , all other methods delegate to default render kit.
- * 
- * @see javax.faces.render.RenderKit 
+ *
+ * @see javax.faces.render.RenderKit
  * @author shura
  *
  */
 public class ChameleonRenderKitImpl extends RenderKit implements ChameleonRenderKit {
-    
-    private RenderKit defaultRenderKit = null;
     public static final String RENDER_KIT_ID = "AJAX_HTML_BASIC";
-
+    private RenderKit defaultRenderKit = null;
     private Map<String, Renderer> renderers;
 
-
-    //~ Constructors -------------------------------------------------------------------------------
-
-    public ChameleonRenderKitImpl()
-    {
+    public ChameleonRenderKitImpl() {
         renderers = new HashMap<String, Renderer>();
     }
 
-    //~ Methods ------------------------------------------------------------------------------------
-
-    private String key(String componentFamily, String rendererType)
-    {
+    private String key(String componentFamily, String rendererType) {
         return componentFamily + "." + rendererType;
-    }    
+    }
+
     /**
      * @param family
      * @param rendererType
      * @param renderer
      */
-    public void addRenderer(String family, String rendererType,
-            Renderer renderer) {
+    public void addRenderer(String family, String rendererType, Renderer renderer) {
         renderers.put(key(family, rendererType), renderer);
     }
+
     /**
      * @param writer
      * @param contentTypeList
      * @param characterEncoding
      * @return
      */
-    public ResponseWriter createResponseWriter(Writer writer,
-            String contentTypeList, String characterEncoding) {
-        return getDefaultRenderKit().createResponseWriter(writer, contentTypeList,
-                characterEncoding);
+    public ResponseWriter createResponseWriter(Writer writer, String contentTypeList, String characterEncoding) {
+        return getDefaultRenderKit().createResponseWriter(writer, contentTypeList, characterEncoding);
     }
+
     /**
      * @param family
      * @param rendererType
@@ -92,24 +86,26 @@
      */
     public Renderer getRenderer(String family, String rendererType) {
         Renderer renderer = (Renderer) renderers.get(key(family, rendererType));
+
         if (renderer != null) {
             return renderer;
         }
+
         return getDefaultRenderKit().getRenderer(family, rendererType);
     }
+
     /**
      * @return
      */
     public ResponseStateManager getResponseStateManager() {
         return getDefaultRenderKit().getResponseStateManager();
     }
-    
-    
-    /* (non-Javadoc)
+
+    /*
+     *  (non-Javadoc)
      * @see javax.faces.render.RenderKit#createResponseStream(java.io.OutputStream)
      */
-    public ResponseStream createResponseStream(OutputStream out)
-    {
+    public ResponseStream createResponseStream(OutputStream out) {
         return getDefaultRenderKit().createResponseStream(out);
     }
 
@@ -121,38 +117,41 @@
      * @return Returns the defaultRenderer.
      */
     protected RenderKit getDefaultRenderKit() {
-        if (defaultRenderKit == null)
-        {
-        	String defaultRenderkitId = null;
-        	FacesContext context = null;
+        if (defaultRenderKit == null) {
+            String defaultRenderkitId = null;
+            FacesContext context = null;
             RenderKitFactory rdf = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
+
             try {
-				context = FacesContext.getCurrentInstance();
-            	// IN JSF-RI verifications, context may be null !
-            	if(null != context) {
-				defaultRenderkitId = context.getApplication()
-						.getDefaultRenderKitId();
-            	} else {
-                	ApplicationFactory appFactory =(ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
-                	defaultRenderkitId = appFactory.getApplication().getDefaultRenderKitId();
-				}
-			} catch (Exception e) {
-				// TODO: handle exception
-			}
-            if(defaultRenderkitId == null ){
+                context = FacesContext.getCurrentInstance();
+
+                // IN JSF-RI verifications, context may be null !
+                if (null != context) {
+                    defaultRenderkitId = context.getApplication().getDefaultRenderKitId();
+                } else {
+                    ApplicationFactory appFactory =
+                        (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
+
+                    defaultRenderkitId = appFactory.getApplication().getDefaultRenderKitId();
+                }
+            } catch (Exception e) {
+
+                // TODO: handle exception
+            }
+
+            if (defaultRenderkitId == null) {
                 defaultRenderkitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
             }
+
             defaultRenderKit = rdf.getRenderKit(context, defaultRenderkitId);
-            
         }
 
         return defaultRenderKit;
     }
 
-	public void setDefaultRenderKit(RenderKit renderKit) {
-		// TODO Auto-generated method stub
-        this.defaultRenderKit = renderKit;
-		
-	}
+    public void setDefaultRenderKit(RenderKit renderKit) {
 
+        // TODO Auto-generated method stub
+        this.defaultRenderKit = renderKit;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentRendererBase.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentRendererBase.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentRendererBase.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
 import java.util.HashMap;
@@ -26,83 +28,72 @@
 
 import javax.faces.component.UIComponent;
 
-
-
 /**
  * Components Base Renderer for all chameleon Skin's and components.
- * At most, make all common procedures and realise concrete work in "template" methods. 
+ * At most, make all common procedures and realise concrete work in "template" methods.
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:52 $
  *
  */
-public abstract class ComponentRendererBase extends RendererBase{
-	
-	/**
-	 * logger for common cases. 
-	 */
-	protected static final String COMPONENT_RENDERER_BASE = ComponentRendererBase.class.getName();
+public abstract class ComponentRendererBase extends RendererBase {
 
+    /**
+     * logger for common cases.
+     */
+    protected static final String COMPONENT_RENDERER_BASE = ComponentRendererBase.class.getName();
 
-	public ComponentVariables  getVariables(UIComponent component) {
-		HashMap components;
-		Stack stackComponentsVariables;		
-		ComponentVariables variables;
-		
-		
-		
-		components = (HashMap)component.getAttributes().get( COMPONENT_RENDERER_BASE );
-		
-		if ( components == null ) {
-			components = new HashMap();
-			component.getAttributes().put( COMPONENT_RENDERER_BASE, components );
-		}
+    public ComponentVariables getVariables(UIComponent component) {
+        HashMap components;
+        Stack stackComponentsVariables;
+        ComponentVariables variables;
 
-		stackComponentsVariables = (Stack)components.get( this.getClass().getName() );
+        components = (HashMap) component.getAttributes().get(COMPONENT_RENDERER_BASE);
 
-		if ( stackComponentsVariables == null ) {
-			stackComponentsVariables = new Stack();
-			components.put( COMPONENT_RENDERER_BASE, stackComponentsVariables );	
-		}
+        if (components == null) {
+            components = new HashMap();
+            component.getAttributes().put(COMPONENT_RENDERER_BASE, components);
+        }
 
-		if ( stackComponentsVariables.empty() ) {
-			variables = new ComponentVariables();
-			stackComponentsVariables.push( variables );
-		} else {
-			variables = (ComponentVariables)stackComponentsVariables.peek();
-		}
+        stackComponentsVariables = (Stack) components.get(this.getClass().getName());
 
-		return variables;
-	}
+        if (stackComponentsVariables == null) {
+            stackComponentsVariables = new Stack();
+            components.put(COMPONENT_RENDERER_BASE, stackComponentsVariables);
+        }
 
-	public void removeVariables(UIComponent component) {
-	        HashMap components;
-                Stack stackComponentsVariables;
-                ComponentVariables variables;
+        if (stackComponentsVariables.empty()) {
+            variables = new ComponentVariables();
+            stackComponentsVariables.push(variables);
+        } else {
+            variables = (ComponentVariables) stackComponentsVariables.peek();
+        }
 
+        return variables;
+    }
 
+    public void removeVariables(UIComponent component) {
+        HashMap components;
+        Stack stackComponentsVariables;
+        ComponentVariables variables;
 
-                components = (HashMap)component.getAttributes().get( COMPONENT_RENDERER_BASE );
+        components = (HashMap) component.getAttributes().get(COMPONENT_RENDERER_BASE);
 
-                if ( components != null ) {
-	
-        	        stackComponentsVariables = (Stack)component.getAttributes().get( this.getClass().getName() );
+        if (components != null) {
+            stackComponentsVariables = (Stack) component.getAttributes().get(this.getClass().getName());
 
-                	if ( stackComponentsVariables != null ) {
-                		if ( !stackComponentsVariables.empty() ) {
-                			stackComponentsVariables.pop();
-				}
-				
-				if ( stackComponentsVariables.empty()  ) {
-					components.remove( this.getClass().getName() );
-				}
-			}
+            if (stackComponentsVariables != null) {
+                if (!stackComponentsVariables.empty()) {
+                    stackComponentsVariables.pop();
+                }
 
-			if ( components.isEmpty()  ) {
-                                component.getAttributes().remove( COMPONENT_RENDERER_BASE  );
-                        }
-				
-					
-                } 
+                if (stackComponentsVariables.empty()) {
+                    components.remove(this.getClass().getName());
+                }
+            }
 
-	}
+            if (components.isEmpty()) {
+                component.getAttributes().remove(COMPONENT_RENDERER_BASE);
+            }
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentVariables.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentVariables.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentVariables.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,80 +19,85 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
 import java.io.IOException;
 import java.io.Serializable;
+
 import java.util.HashMap;
 import java.util.Map;
 
 /**
- * 	storing tempates variables
+ *  storing tempates variables
  *  @author ayukhovich at exadel.com (latest modification by $Author: alexsmirnov $)
  *  @version $Revision: 1.1.2.2 $ $Date: 2007/02/28 17:01:01 $
  */
 public class ComponentVariables implements Serializable {
-	
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = 4310787278096026676L;
-	private transient Map<String, Object> variablesMap = new HashMap<String, Object>();
-	
-	/**
-	 * setting variable 
-	 * @param variableName
-	 * @param variable
-	 */
-	public void setVariable(final String variableName, final Object variable ) {
-		variablesMap.put(variableName, variable);	
-	}
-	
-	/**
-	 * 
-	 * @param variableName
-	 * @return
-	 */
-	public Object getVariable(final String variableName ) {
-		return variablesMap.get(variableName);
-	}
-	
-	
-	/**
-	 *
-	 * @param variableName
-	 * @param addValue
-	 */
-	public void addValueToVariable(final String variableName, final Object addValue) {
-		Object variable = getVariable(variableName);
-		if ( variable == null )
-			return;
-		
-		if (variable instanceof Integer) {
-			addToValue( variableName,(Integer) variable,  addValue);
-		}
-	}
-	
-	/**
-	 * 
-	 * @param variableName
-	 * @param variable
-	 * @param addValue
-	 */
-	protected void addToValue(final String variableName, Integer variable, final Object addValue ) {
-		Integer retultValue;
-		if ( addValue instanceof Integer )	{
-			Integer intAddValue =(Integer)addValue; 
-			retultValue = new Integer(variable.intValue() + intAddValue.intValue());
-		} else {
-			retultValue = variable;
-		}
-		
-		setVariable(variableName, retultValue);
-	}
-	
-	private void readObject(java.io.ObjectInputStream in)
-    throws IOException, ClassNotFoundException{
-		variablesMap = new HashMap<String, Object>();
-	}
+
+    /**
+     *
+     */
+    private static final long serialVersionUID = 4310787278096026676L;
+    private transient Map<String, Object> variablesMap = new HashMap<String, Object>();
+
+    /**
+     * setting variable
+     * @param variableName
+     * @param variable
+     */
+    public void setVariable(final String variableName, final Object variable) {
+        variablesMap.put(variableName, variable);
+    }
+
+    /**
+     *
+     * @param variableName
+     * @return
+     */
+    public Object getVariable(final String variableName) {
+        return variablesMap.get(variableName);
+    }
+
+    /**
+     *
+     * @param variableName
+     * @param addValue
+     */
+    public void addValueToVariable(final String variableName, final Object addValue) {
+        Object variable = getVariable(variableName);
+
+        if (variable == null) {
+            return;
+        }
+
+        if (variable instanceof Integer) {
+            addToValue(variableName, (Integer) variable, addValue);
+        }
+    }
+
+    /**
+     *
+     * @param variableName
+     * @param variable
+     * @param addValue
+     */
+    protected void addToValue(final String variableName, Integer variable, final Object addValue) {
+        Integer retultValue;
+
+        if (addValue instanceof Integer) {
+            Integer intAddValue = (Integer) addValue;
+
+            retultValue = new Integer(variable.intValue() + intAddValue.intValue());
+        } else {
+            retultValue = variable;
+        }
+
+        setVariable(variableName, retultValue);
+    }
+
+    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
+        variablesMap = new HashMap<String, Object>();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentsVariableResolver.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentsVariableResolver.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/ComponentsVariableResolver.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,44 +19,43 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
 import javax.faces.component.UIComponent;
 
 /**
  * Resolve component variables
- * 
+ *
  * @author ayukhovich at exadel.com (latest modification by $Author:
  *         alexeyyukhovich $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:53 $
  */
-public class ComponentsVariableResolver {
-	private static String COMPONENTS_VARIABLE_RESOLVER = ComponentsVariableResolver.class
-			.getName();
+public final class ComponentsVariableResolver {
+    private static final String COMPONENTS_VARIABLE_RESOLVER = ComponentsVariableResolver.class.getName();
 
-	private static String getAttributeName(RendererBase renderer) {
-		return COMPONENTS_VARIABLE_RESOLVER + ":" + (renderer != null ? renderer.getClass().getName() : null);
-	}
-	
-	public static ComponentVariables getVariables(RendererBase renderer,
-			UIComponent component) {
-		ComponentVariables variables;
+    private ComponentsVariableResolver() {}
 
-		String attributeName = getAttributeName(renderer);
-		
-		variables = (ComponentVariables) component.getAttributes().get(attributeName);
+    private static String getAttributeName(RendererBase renderer) {
+        return COMPONENTS_VARIABLE_RESOLVER + ":" + ((renderer != null) ? renderer.getClass().getName() : null);
+    }
 
-		if (variables == null) {
-			variables = new ComponentVariables();
-		
-			component.getAttributes().put(attributeName, variables);
-		}
+    public static ComponentVariables getVariables(RendererBase renderer, UIComponent component) {
+        ComponentVariables variables;
+        String attributeName = getAttributeName(renderer);
 
-		return variables;
-	}
+        variables = (ComponentVariables) component.getAttributes().get(attributeName);
 
-	public static void removeVariables(RendererBase renderer,
-			UIComponent component) {
-		component.getAttributes().remove(getAttributeName(renderer));
-	}
+        if (variables == null) {
+            variables = new ComponentVariables();
+            component.getAttributes().put(attributeName, variables);
+        }
+
+        return variables;
+    }
+
+    public static void removeVariables(RendererBase renderer, UIComponent component) {
+        component.getAttributes().remove(getAttributeName(renderer));
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/HandlersChain.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/HandlersChain.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/HandlersChain.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,128 +19,130 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
+import org.ajax4jsf.javascript.JSFunction;
+import org.ajax4jsf.javascript.JSReference;
 
 import javax.faces.component.UIComponent;
 import javax.faces.component.behavior.ClientBehavior;
 import javax.faces.component.behavior.ClientBehaviorContext;
+import javax.faces.component.behavior.ClientBehaviorContext.Parameter;
 import javax.faces.component.behavior.ClientBehaviorHint;
 import javax.faces.component.behavior.ClientBehaviorHolder;
-import javax.faces.component.behavior.ClientBehaviorContext.Parameter;
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.javascript.JSFunction;
-import org.ajax4jsf.javascript.JSReference;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
 
 /**
  * @author Nick Belaevski
  * @since 4.0
  */
 public final class HandlersChain {
-	
-//	private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
-	
-	private boolean hasSubmittingBehavior = false;
 
-	private UIComponent component;
-	
-	private Collection<Parameter> parameters;
+//  private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
+    private boolean hasSubmittingBehavior = false;
+    private boolean includeClientId = false;
 
-	private boolean includeClientId = false;
-	
-	//TODO: review for optimization
-	private List<String> handlers = new ArrayList<String>(2);
+    // TODO: review for optimization
+    private List<String> handlers = new ArrayList<String>(2);
+    private UIComponent component;
+    private Collection<Parameter> parameters;
 
+    public HandlersChain(UIComponent component) {
+        this.component = component;
+    }
+
+    public HandlersChain(UIComponent component, boolean includeClientId) {
+        this.component = component;
+        this.includeClientId = includeClientId;
+    }
+
+    public HandlersChain(UIComponent component, Collection<Parameter> parameters) {
+        this.component = component;
+        this.parameters = parameters;
+    }
+
+    public HandlersChain(UIComponent component, Collection<Parameter> parameters, boolean includeClientId) {
+        this.component = component;
+        this.parameters = parameters;
+        this.includeClientId = includeClientId;
+    }
+
     private static boolean isNotEmpty(String s) {
-		return s != null && s.length() != 0;
-	}
+        return (s != null) && (s.length() != 0);
+    }
 
-	public HandlersChain(UIComponent component) {
-		this.component = component;
-	}
-	
-	public HandlersChain(UIComponent component, boolean includeClientId) {
-		this.component = component;
-		this.includeClientId = includeClientId;
-	}
+    private List<ClientBehavior> getBehaviorsList(String behaviorName) {
+        List<ClientBehavior> behaviors = null;
 
-	public HandlersChain(UIComponent component, Collection<Parameter> parameters) {
-		this.component = component;
-		this.parameters = parameters;
-	}
+        if (component instanceof ClientBehaviorHolder) {
+            ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
+            Map<String, List<ClientBehavior>> clientBehaviorsMap = clientBehaviorHolder.getClientBehaviors();
 
-	public HandlersChain(UIComponent component, Collection<Parameter> parameters, boolean includeClientId) {
-		this.component = component;
-		this.parameters = parameters;
-		this.includeClientId = includeClientId; 
-	}
+            if (clientBehaviorsMap != null) {
+                behaviors = clientBehaviorsMap.get(behaviorName);
+            }
+        }
 
-	private List<ClientBehavior> getBehaviorsList(String behaviorName) {		
-		List<ClientBehavior> behaviors = null;
-		if (component instanceof ClientBehaviorHolder) {
-			ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
-			Map<String, List<ClientBehavior>> clientBehaviorsMap = clientBehaviorHolder.getClientBehaviors();
-			if (clientBehaviorsMap != null) {
-				behaviors = clientBehaviorsMap.get(behaviorName);
-			}
-		}
-		
-		return behaviors;
-	}
+        return behaviors;
+    }
 
-	private Collection<Parameter> getParameters(FacesContext context) {
-		if (parameters == null) {
-			RendererUtils rendererUtils = RendererUtils.getInstance();
-			Map<String, Object> parametersMap = rendererUtils.createParametersMap(context, component);
-			parameters = createParametersList(parametersMap);
-		}
-		
-		return parameters;
-	}
+    private Collection<Parameter> getParameters(FacesContext context) {
+        if (parameters == null) {
+            RendererUtils rendererUtils = RendererUtils.getInstance();
+            Map<String, Object> parametersMap = rendererUtils.createParametersMap(context, component);
 
-	
-	public boolean hasSubmittingBehavior() {
-		return hasSubmittingBehavior;
-	}
+            parameters = createParametersList(parametersMap);
+        }
 
-	public void addInlineHandlerAsValue(FacesContext context, String handlerValue) {
-		if (isNotEmpty(handlerValue)) {
-			handlers.add(handlerValue);
-		}
-	}
+        return parameters;
+    }
 
-	public void addInlineHandlerFromAttribute(FacesContext context, String attributeName) {
-		addInlineHandlerAsValue(context, (String) component.getAttributes().get(attributeName));
-	}
-	
-	public void addBehaviors(FacesContext context, String evantName) {
-		addBehaviors(context, evantName, null);
-	}
-	public void addBehaviors(FacesContext context, String evantName, String defaultEventName) {
-		String name = evantName;
-		List<ClientBehavior> behaviorsList = getBehaviorsList(evantName);
-		if (behaviorsList == null && defaultEventName != null) {
-			behaviorsList = getBehaviorsList(defaultEventName);
-			name = defaultEventName;
-		}
+    public boolean hasSubmittingBehavior() {
+        return hasSubmittingBehavior;
+    }
+
+    public void addInlineHandlerAsValue(FacesContext context, String handlerValue) {
+        if (isNotEmpty(handlerValue)) {
+            handlers.add(handlerValue);
+        }
+    }
+
+    public void addInlineHandlerFromAttribute(FacesContext context, String attributeName) {
+        addInlineHandlerAsValue(context, (String) component.getAttributes().get(attributeName));
+    }
+
+    public void addBehaviors(FacesContext context, String evantName) {
+        addBehaviors(context, evantName, null);
+    }
+
+    public void addBehaviors(FacesContext context, String evantName, String defaultEventName) {
+        String name = evantName;
+        List<ClientBehavior> behaviorsList = getBehaviorsList(evantName);
+
+        if ((behaviorsList == null) && (defaultEventName != null)) {
+            behaviorsList = getBehaviorsList(defaultEventName);
+            name = defaultEventName;
+        }
+
         if (behaviorsList == null) {
             return;
         }
 
-        ClientBehaviorContext behaviorContext = ClientBehaviorContext.createClientBehaviorContext(
-            context, component, name, includeClientId ? component.getClientId(context) : null,
-            getParameters(context));
+        ClientBehaviorContext behaviorContext = ClientBehaviorContext.createClientBehaviorContext(context, component,
+                                                    name, includeClientId ? component.getClientId(context) : null,
+                                                    getParameters(context));
 
         for (ClientBehavior clientBehavior : behaviorsList) {
             String behaviorScript = clientBehavior.getScript(behaviorContext);
+
             if (isNotEmpty(behaviorScript)) {
                 if (clientBehavior.getHints().contains(ClientBehaviorHint.SUBMITTING)) {
                     hasSubmittingBehavior = true;
@@ -150,30 +152,34 @@
             }
         }
     }
-	
-	public String toScript() {
-		String result = null;
-		if (!handlers.isEmpty()) {
-			if (handlers.size() == 1) {
-				result = handlers.get(0);  
-			} else {
-				JSFunction jsFunction = new JSFunction("jsf.util.chain", JSReference.THIS, JSReference.EVENT);
-				for (String handler : handlers) {
-					jsFunction.addParameter(handler);
-				}
-				result = jsFunction.toScript();
-			}
-		}
-		
-		return result;
-	}
 
-	public static List<Parameter> createParametersList(Map<String, Object> parametersMap) {
-		List<Parameter> parameters = new ArrayList<Parameter>(parametersMap.size());
-		for (Entry<String, Object> entry: parametersMap.entrySet()) {
-			parameters.add(new Parameter(entry.getKey(), entry.getValue()));
-		}
+    public String toScript() {
+        String result = null;
 
-		return parameters;
-	}
-}
\ No newline at end of file
+        if (!handlers.isEmpty()) {
+            if (handlers.size() == 1) {
+                result = handlers.get(0);
+            } else {
+                JSFunction jsFunction = new JSFunction("jsf.util.chain", JSReference.THIS, JSReference.EVENT);
+
+                for (String handler : handlers) {
+                    jsFunction.addParameter(handler);
+                }
+
+                result = jsFunction.toScript();
+            }
+        }
+
+        return result;
+    }
+
+    public static List<Parameter> createParametersList(Map<String, Object> parametersMap) {
+        List<Parameter> parameters = new ArrayList<Parameter>(parametersMap.size());
+
+        for (Entry<String, Object> entry : parametersMap.entrySet()) {
+            parameters.add(new Parameter(entry.getKey(), entry.getValue()));
+        }
+
+        return parameters;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererBase.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererBase.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererBase.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,9 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.resource.InternetResource;
+
+import org.richfaces.log.RichfacesLogger;
+import org.richfaces.skin.Skin;
+import org.richfaces.skin.SkinFactory;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
+
 import java.util.List;
 import java.util.Map;
 
@@ -33,37 +45,32 @@
 import javax.faces.context.ResponseWriter;
 import javax.faces.render.Renderer;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.resource.InternetResource;
-import org.richfaces.log.RichfacesLogger;
-import org.richfaces.skin.Skin;
-import org.richfaces.skin.SkinFactory;
-import org.slf4j.Logger;
-
-
 /**
  * Base Renderer for all chameleon Skin's and components.
- * At most, make all common procedures and realise concrete work in "template" methods. 
+ * At most, make all common procedures and realise concrete work in "template" methods.
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:51 $
  *
  */
 public abstract class RendererBase extends Renderer {
-	
-	/**
-	 * logger for common cases. 
-	 */
-	protected static final String JAVASCRIPT_NAMESPACE = "Exadel";
-	private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
-	private static final RendererUtils UTILS = RendererUtils.getInstance();
 
-	private SkinFactory skinFactory = null;
+    /**
+     * logger for common cases.
+     */
+    protected static final String JAVASCRIPT_NAMESPACE = "Exadel";
 
-    /* (non-Javadoc)
-      * @see javax.faces.render.Renderer#decode(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
-      */
+    private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
+    private static final RendererUtils UTILS = RendererUtils.getInstance();
+
+    private SkinFactory skinFactory = null;
+
+    /*
+     *  (non-Javadoc)
+     *  @see javax.faces.render.Renderer#decode(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+     */
     @Override
     public void decode(FacesContext context, UIComponent component) {
+
         // Test for correct parameters.
         checkNull(context, component, "decode");
 
@@ -73,8 +80,10 @@
         }
 
         if (LOG.isDebugEnabled()) {
-            LOG.debug(Messages.getMessage(Messages.START_DECODING_COMPONENT_INFO, component.getClientId(context), component.getClass().getName()));
+            LOG.debug(Messages.getMessage(Messages.START_DECODING_COMPONENT_INFO, component.getClientId(context),
+                                          component.getClass().getName()));
         }
+
         preDecode(context, component);
 
         // TODO - create set od common decoders ( UIInput, ActionSource etc. ) for process decoding.
@@ -91,6 +100,7 @@
 
         ClientBehaviorHolder holder = (ClientBehaviorHolder) component;
         Map<String, List<ClientBehavior>> behaviors = holder.getClientBehaviors();
+
         if (behaviors.isEmpty()) {
             return;
         }
@@ -98,6 +108,7 @@
         ExternalContext external = context.getExternalContext();
         Map<String, String> params = external.getRequestParameterMap();
         String behaviorEvent = params.get("javax.faces.behavior.event");
+
         if (behaviorEvent == null) {
             return;
         }
@@ -105,43 +116,48 @@
         List<ClientBehavior> behaviorsForEvent = behaviors.get(behaviorEvent);
         String behaviorSource = params.get("javax.faces.source");
         String clientId = component.getClientId();
-        if (null != behaviorSource && behaviorSource.equals(clientId)) {
-            for (ClientBehavior behavior: behaviorsForEvent) {
+
+        if ((null != behaviorSource) && behaviorSource.equals(clientId)) {
+            for (ClientBehavior behavior : behaviorsForEvent) {
                 behavior.decode(context, component);
             }
         }
     }
 
-	protected void preDecode(FacesContext context, UIComponent component)   {
-	}
+    protected void preDecode(FacesContext context, UIComponent component) {}
 
-	protected void preEncodeBegin(FacesContext context, UIComponent component) throws IOException  {
-		
-	}
+    protected void preEncodeBegin(FacesContext context, UIComponent component) throws IOException {}
 
-	/* (non-Javadoc)
-	 * @see javax.faces.render.Renderer#encodeBegin(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
-	 */
-	@Override
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.render.Renderer#encodeBegin(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+     */
+    @Override
     public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
-		// Test for correct parameters.
+
+        // Test for correct parameters.
         checkForCorrectParams(context, component, "encodeBegin");
 
-        if(LOG.isDebugEnabled()){
-        	LOG.debug(Messages.getMessage(Messages.START_ENCODING_COMPONENT_INFO, component.getClientId(context), component.getClass().getName()));
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.START_ENCODING_COMPONENT_INFO, component.getClientId(context),
+                                          component.getClass().getName()));
         }
-		preEncodeBegin(context,component);
+
+        preEncodeBegin(context, component);
+
         if (component.isRendered()) {
-			ResponseWriter writer = context.getResponseWriter();
-			doEncodeBegin(writer, context, component);
-		}
-	}
+            ResponseWriter writer = context.getResponseWriter();
 
+            doEncodeBegin(writer, context, component);
+        }
+    }
+
     private void checkForCorrectParams(FacesContext context, UIComponent component, String exceptionMessageParam) {
         checkNull(context, component, exceptionMessageParam);
 
         if (!getComponentClass().isInstance(component)) {
-            throw new IllegalArgumentException(Messages.getMessage(Messages.COMPONENT_CLASS_ERROR, component.getClientId(context), getComponentClass().getName()));
+            throw new IllegalArgumentException(Messages.getMessage(Messages.COMPONENT_CLASS_ERROR,
+                    component.getClientId(context), getComponentClass().getName()));
         }
     }
 
@@ -155,123 +171,127 @@
         }
     }
 
+    /*
+     *  (non-Javadoc)
+     *  @see javax.faces.render.Renderer#encodeChildren(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+     */
+    @Override
+    public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
 
-    /* (non-Javadoc)
-      * @see javax.faces.render.Renderer#encodeChildren(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
-      */
-	@Override
-    public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
-		// Test for correct parameters.
+        // Test for correct parameters.
         checkForCorrectParams(context, component, "encodeBegin");
 
-        if(LOG.isDebugEnabled()){
-        	LOG.debug(Messages.getMessage(Messages.CHILDREN_ENCODING_COMPONENT_INFO, component.getClientId(context), component.getClass().getName()));
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.CHILDREN_ENCODING_COMPONENT_INFO, component.getClientId(context),
+                                          component.getClass().getName()));
         }
-		preEncodeBegin(context,component);
+
+        preEncodeBegin(context, component);
+
         if (component.isRendered()) {
-			ResponseWriter writer = context.getResponseWriter();
-			doEncodeChildren(writer, context, component);
-		}
-	}
+            ResponseWriter writer = context.getResponseWriter();
 
-	/* (non-Javadoc)
-	 * @see javax.faces.render.Renderer#encodeEnd(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
-	 */
-	@Override
+            doEncodeChildren(writer, context, component);
+        }
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see javax.faces.render.Renderer#encodeEnd(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
+     */
+    @Override
     public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
-		// Test for correct parameters.
+
+        // Test for correct parameters.
         checkForCorrectParams(context, component, "encodeEnd");
 
         if (component.isRendered()) {
-			ResponseWriter writer = context.getResponseWriter();
-			doEncodeEnd(writer, context, component);
-		}
-        if(LOG.isDebugEnabled()){
-        	LOG.debug(Messages.getMessage(Messages.FINISH_ENCODING_COMPONENT_INFO, component.getClientId(context), component.getClass().getName()));
+            ResponseWriter writer = context.getResponseWriter();
+
+            doEncodeEnd(writer, context, component);
         }
-	}
 
-	//==========================================================
-	// Protected common methods - for all Renderer's
-	
-	/**
-	 * Calculate current Skin for rendering.
-	 * @param context - current {@link FacesContext }
-	 * @return
-	 */
-	protected Skin getSkin(FacesContext context) {
-		if (skinFactory == null) {
-			skinFactory = SkinFactory.getInstance();
-			
-		}
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.FINISH_ENCODING_COMPONENT_INFO, component.getClientId(context),
+                                          component.getClass().getName()));
+        }
+    }
 
-		return skinFactory.getSkin(context);
-	}
-	
-	
-	/**
-	 * Due to big number of common utility methods, base renderer divide to 2 classes - renderer and utils.
-	 * since use static methods of utility class breack object paradigm, we use getter for concrete util instance.
-	 * Developer can override any utility metod in 2 stages :
-	 * 1) Create subclass of {@link RendererUtils} and override utility method.
-	 * 2) Override this method for return instance of such subclass.
-	 * 
-	 * @return Returns the utils.
-	 */
-	public RendererUtils getUtils() {
-		return UTILS;
-	}
+    // ==========================================================
+    // Protected common methods - for all Renderer's
 
+    /**
+     * Calculate current Skin for rendering.
+     * @param context - current {@link FacesContext }
+     * @return
+     */
+    protected Skin getSkin(FacesContext context) {
+        if (skinFactory == null) {
+            skinFactory = SkinFactory.getInstance();
+        }
 
-	/**
-	 * Get base component slass , targetted for this renderer. Used for check arguments in decode/encode.
-	 * @return
-	 */
-	protected abstract Class<? extends UIComponent> getComponentClass();
+        return skinFactory.getSkin(context);
+    }
 
+    /**
+     * Due to big number of common utility methods, base renderer divide to 2 classes - renderer and utils.
+     * since use static methods of utility class breack object paradigm, we use getter for concrete util instance.
+     * Developer can override any utility metod in 2 stages :
+     * 1) Create subclass of {@link RendererUtils} and override utility method.
+     * 2) Override this method for return instance of such subclass.
+     *
+     * @return Returns the utils.
+     */
+    public RendererUtils getUtils() {
+        return UTILS;
+    }
 
-	/**
-	 * Template method for custom decoding of concrete renderer.
-	 * All parameters checking if performed in original {@see decode } method.
-	 * @param context
-	 * @param component
-	 */
-	protected void doDecode(FacesContext context, UIComponent component) {
-		
-	}
+    /**
+     * Get base component slass , targetted for this renderer. Used for check arguments in decode/encode.
+     * @return
+     */
+    protected abstract Class<? extends UIComponent> getComponentClass();
 
-	/**
-	 * Template method for custom start encoding of concrete renderer.
-	 * All parameters checking and writer is performed in original {@link encodeBegin } method.
-	 * @param writer
-	 * @param context
-	 * @param component
-	 */
-	protected void doEncodeBegin(ResponseWriter writer,FacesContext context, UIComponent component) throws IOException {
-		
-	}
-	/**
-	 * @param writer
-	 * @param context
-	 * @param component
-	 */
-	protected void doEncodeChildren(ResponseWriter writer, FacesContext context, UIComponent component) throws IOException  {
-		// Hook method, must be overriden in renderers with special children processing
-	}
+    /**
+     * Template method for custom decoding of concrete renderer.
+     * All parameters checking if performed in original {@see decode } method.
+     * @param context
+     * @param component
+     */
+    protected void doDecode(FacesContext context, UIComponent component) {}
 
-	/**
-	 * Template method for custom finish encoding of concrete renderer.
-	 * All parameters checking and writer is performed in original {@link encodeEnd } method.
-	 * @param writer
-	 * @param context
-	 * @param component
-	 * @throws IOException 
-	 */
-	protected void doEncodeEnd(ResponseWriter writer, FacesContext context, UIComponent component) throws IOException {
-		
-	}
+    /**
+     * Template method for custom start encoding of concrete renderer.
+     * All parameters checking and writer is performed in original {@link encodeBegin } method.
+     * @param writer
+     * @param context
+     * @param component
+     */
+    protected void doEncodeBegin(ResponseWriter writer, FacesContext context, UIComponent component)
+        throws IOException { }
 
     /**
+     * @param writer
+     * @param context
+     * @param component
+     */
+    protected void doEncodeChildren(ResponseWriter writer, FacesContext context, UIComponent component)
+        throws IOException {
+
+        // Hook method, must be overriden in renderers with special children processing
+    }
+
+    /**
+     * Template method for custom finish encoding of concrete renderer.
+     * All parameters checking and writer is performed in original {@link encodeEnd } method.
+     * @param writer
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    protected void doEncodeEnd(ResponseWriter writer, FacesContext context, UIComponent component) throws IOException {}
+
+    /**
      * Render all children for given component.
      * @param facesContext
      * @param component
@@ -279,34 +299,34 @@
      */
     public void renderChildren(FacesContext facesContext, UIComponent component) throws IOException {
         for (UIComponent child : component.getChildren()) {
-            renderChild(facesContext, child);   
+            renderChild(facesContext, child);
         }
-	}
+    }
 
+    /**
+     * Render one component and it childrens
+     * @param facesContext
+     * @param child
+     * @throws IOException
+     */
+    public void renderChild(FacesContext facesContext, UIComponent child) throws IOException {
+        if (!child.isRendered()) {
+            return;
+        }
 
-	/**
-	 * Render one component and it childrens
-	 * @param facesContext
-	 * @param child
-	 * @throws IOException
-	 */
-	public void renderChild(FacesContext facesContext, UIComponent child)
-			throws IOException {
-		if (!child.isRendered()) {
-			return;
-		}
+        child.encodeBegin(facesContext);
 
-		child.encodeBegin(facesContext);
-		if (child.getRendersChildren()) {
-			child.encodeChildren(facesContext);
-		} else {
-			renderChildren(facesContext, child);
-		}
-		child.encodeEnd(facesContext);
-	}
+        if (child.getRendersChildren()) {
+            child.encodeChildren(facesContext);
+        } else {
+            renderChildren(facesContext, child);
+        }
 
-	//TODO method stub - replace with JSF 2.0 annotations
-	public InternetResource getResource(String name) {
-		return null;
-	}
+        child.encodeEnd(facesContext);
+    }
+
+    // TODO method stub - replace with JSF 2.0 annotations
+    public InternetResource getResource(String name) {
+        return null;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererUtils.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererUtils.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererUtils.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,10 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.renderkit;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.component.JavaScriptParameter;
+import org.ajax4jsf.javascript.JSEncoder;
+import org.ajax4jsf.javascript.JSFunctionDefinition;
+import org.ajax4jsf.javascript.JSReference;
+import org.ajax4jsf.util.HtmlDimensions;
+
 import java.io.IOException;
+
 import java.lang.reflect.Array;
+
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
@@ -42,1207 +53,1171 @@
 import javax.faces.component.UIParameter;
 import javax.faces.component.UIViewRoot;
 import javax.faces.component.ValueHolder;
-import javax.faces.component.behavior.ClientBehaviorHolder;
 import javax.faces.component.behavior.ClientBehaviorContext.Parameter;
+import javax.faces.component.behavior.ClientBehaviorHolder;
 import javax.faces.context.FacesContext;
 import javax.faces.context.ResponseWriter;
 import javax.faces.convert.Converter;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.component.JavaScriptParameter;
-import org.ajax4jsf.javascript.JSEncoder;
-import org.ajax4jsf.javascript.JSFunctionDefinition;
-import org.ajax4jsf.javascript.JSReference;
-import org.ajax4jsf.util.HtmlDimensions;
-
 /**
  * Util class for common render operations - render passthru html attributes,
  * iterate over child components etc.
- * 
+ *
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.6 $ $Date: 2007/02/08 19:07:16 $
- * 
+ *
  */
 public class RendererUtils {
-	
-	//we'd better use this instance multithreadly quickly
-	private static final RendererUtils instance = new RendererUtils();
-	
-	public static final String DUMMY_FORM_ID = ":_form";
-	/**
-	 * Substitutions for components properies names and HTML attributes names.
-	 */
-	private static Map<String, String> substitutions = new HashMap<String, String>();
-	
-	private static Set<String> requiredAttributes = new HashSet<String>();
+    public static final String DUMMY_FORM_ID = ":_form";
 
-	static {
-		substitutions.put(HTML.class_ATTRIBUTE, "styleClass");
-		requiredAttributes.add(HTML.alt_ATTRIBUTE);
-		Arrays.sort(HTML.PASS_THRU);
-		Arrays.sort(HTML.PASS_THRU_EVENTS);
-		Arrays.sort(HTML.PASS_THRU_BOOLEAN);
-		Arrays.sort(HTML.PASS_THRU_URI);
-	}
+    // we'd better use this instance multithreadly quickly
+    private static final RendererUtils INSTANCE = new RendererUtils();
 
-	//can be created by subclasses; 
-	//administratively restricted to be created by package members ;)
-	protected RendererUtils() {
-		super();
-	}
-	
-	/**
-	 * Use this method to get singleton instance of RendererUtils
-	 * @return singleton instance
-	 */
-	public static RendererUtils getInstance() {
-		return instance;
-	}
+    /**
+     * Substitutions for components properies names and HTML attributes names.
+     */
+    private static Map<String, String> substitutions = new HashMap<String, String>();
+    private static Set<String> requiredAttributes = new HashSet<String>();
 
-	/**
-	 * Common HTML elements and attributes names.
-	 * 
-	 * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
-	 * @version $Revision: 1.1.2.6 $ $Date: 2007/02/08 19:07:16 $
-	 * 
-	 */
-	public interface HTML {
-		// elements
-		public static final String BUTTON = "button";
-		// attributes
-		public static final String id_ATTRIBUTE = "id";
-		public static final String class_ATTRIBUTE = "class";
-		// public static final String STYLE_ATTRIBUTE = "style";
-		// public static final String dir_ATTRIBUTE = "dir";
-		// public static final String lang_ATTRIBUTE = "lang";
-		// public static final String title_ATTRIBUTE = "title";
-		public static final String accesskey_ATTRIBUTE = "accesskey";
-		public static final String alt_ATTRIBUTE = "alt";
-		public static final String autocomplete_ATTRIBUTE = "autocomplete";
-		public static final String cols_ATTRIBUTE = "cols";
+    static {
+        substitutions.put(HTML.CLASS_ATTRIBUTE, "styleClass");
+        requiredAttributes.add(HTML.ALT_ATTRIBUTE);
+        Arrays.sort(HTML.PASS_THRU);
+        Arrays.sort(HTML.PASS_THRU_EVENTS);
+        Arrays.sort(HTML.PASS_THRU_BOOLEAN);
+        Arrays.sort(HTML.PASS_THRU_URI);
+    }
 
-		public static final String height_ATTRIBUTE = "height";
+    // can be created by subclasses;
+    // administratively restricted to be created by package members ;)
+    protected RendererUtils() {
+        super();
+    }
 
-		public static final String lang_ATTRIBUTE = "lang";
+    /**
+     * Wrapper class around object value used to transform values into particular JS objects
+     *
+     * @author Nick Belaevski
+     * @since 3.3.2
+     */
+    public static enum ScriptHashVariableWrapper {
 
-		public static final String longdesc_ATTRIBUTE = "longdesc";
+        /**
+         * No-op default wrapper
+         */
+        DEFAULT {
+            @Override
+            Object wrap(Object o) {
+                return o;
+            }
+        },
 
-		public static final String maxlength_ATTRIBUTE = "maxlength";
+        /**
+         * Event handler functions wrapper. Wraps <pre>functionCode</pre> object into:
+         * <pre>function(event) {
+         *   functionCode
+         * }</pre>
+         */
+        EVENT_HANDLER {
+            @Override
+            Object wrap(Object o) {
+                return new JSFunctionDefinition("event").addToBody(o);
+            }
+        };
 
-		public static final String onblur_ATTRIBUTE = "onblur";
+        /**
+         * Method that does the wrapping
+         *
+         * @param o object to wrap
+         * @return wrapped object
+         */
+        abstract Object wrap(Object o);
+    }
 
-		public static final String onchange_ATTRIBUTE = "onchange";
+    /**
+     * Use this method to get singleton instance of RendererUtils
+     * @return singleton instance
+     */
+    public static RendererUtils getInstance() {
+        return INSTANCE;
+    }
 
-		public static final String onclick_ATTRIBUTE = "onclick";
+    /**
+     * Encode id attribute with clientId component property
+     *
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    public void encodeId(FacesContext context, UIComponent component) throws IOException {
+        encodeId(context, component, HTML.ID_ATTRIBUTE);
+    }
 
-		public static final String ondblclick_ATTRIBUTE = "ondblclick";
+    /**
+     * Encode clientId to custom attribute ( for example, to control name )
+     *
+     * @param context
+     * @param component
+     * @param attribute
+     * @throws IOException
+     */
+    public void encodeId(FacesContext context, UIComponent component, String attribute) throws IOException {
+        String clientId = null;
 
-		public static final String onfocus_ATTRIBUTE = "onfocus";
+        try {
+            clientId = component.getClientId(context);
+        } catch (Exception e) {
 
-		public static final String onkeydown_ATTRIBUTE = "onkeydown";
+            // just ignore if clientId wasn't inited yet
+        }
 
-		public static final String onkeypress_ATTRIBUTE = "onkeypress";
+        if (null != clientId) {
+            context.getResponseWriter().writeAttribute(attribute, clientId,
+                    (String) getComponentAttributeName(attribute));
+        }
+    }
 
-		public static final String onkeyup_ATTRIBUTE = "onkeyup";
+    /**
+     * Encode id attribute with clientId component property. Encoded only if id
+     * not auto generated.
+     *
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    public void encodeCustomId(FacesContext context, UIComponent component) throws IOException {
+        if ((component.getId() != null) && !component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
+            context.getResponseWriter().writeAttribute(HTML.ID_ATTRIBUTE, component.getClientId(context),
+                    HTML.ID_ATTRIBUTE);
+        }
+    }
 
-		public static final String onload_ATTRIBUTE = "onload";
+    public Map<String, Object> createParametersMap(FacesContext context, UIComponent component) {
+        Map<String, Object> parameters = new LinkedHashMap<String, Object>();
 
-		public static final String onmousedown_ATTRIBUTE = "onmousedown";
+        if (component.getChildCount() > 0) {
+            for (UIComponent child : component.getChildren()) {
+                if (child instanceof UIParameter) {
+                    UIParameter parameter = (UIParameter) child;
+                    String name = parameter.getName();
+                    Object value = parameter.getValue();
 
-		public static final String onmousemove_ATTRIBUTE = "onmousemove";
+                    if (null == name) {
+                        throw new IllegalArgumentException(Messages.getMessage(Messages.UNNAMED_PARAMETER_ERROR,
+                                component.getClientId(context)));
+                    }
 
-		public static final String onmouseout_ATTRIBUTE = "onmouseout";
+                    boolean escape = true;
 
-		public static final String onmouseover_ATTRIBUTE = "onmouseover";
+                    if (child instanceof JavaScriptParameter) {
+                        JavaScriptParameter actionParam = (JavaScriptParameter) child;
 
-		public static final String onmouseup_ATTRIBUTE = "onmouseup";
+                        escape = !actionParam.isNoEscape();
+                    }
 
-		public static final String onreset_ATTRIBUTE = "onreset";
+                    if (escape) {
+                        if (value == null) {
+                            value = "";
+                        }
+                    } else {
+                        value = new JSReference(value.toString());
 
-		public static final String onselect_ATTRIBUTE = "onselect";
+                        // if(it.hasNext()){onEvent.append(',');};
+                        // renderAjaxLinkParameter( name,
+                        // value, onClick, jsForm, nestingForm);
+                    }
 
-		// public static final String onsubmit_ATTRIBUTE = "onsubmit";
-		public static final String onunload_ATTRIBUTE = "onunload";
+                    parameters.put(name, value);
+                }
+            }
+        }
 
-		public static final String rows_ATTRIBUTE = "rows";
+        return parameters;
+    }
 
-		public static final String size_ATTRIBUTE = "size";
+    private void encodeBehaviors(FacesContext context, ClientBehaviorHolder behaviorHolder,
+                                 String defaultHtmlEventName, String[] attributesExclusions)
+        throws IOException {
 
-		public static final String tabindex_ATTRIBUTE = "tabindex";
+//      if (attributesExclusions != null && attributesExclusions.length != 0) {
+//          assert false : "Not supported yet";
+//      }
+        // TODO: disabled component check
+        String defaultEventName = behaviorHolder.getDefaultEventName();
+        Collection<String> eventNames = behaviorHolder.getEventNames();
 
-		public static final String title_ATTRIBUTE = "title";
+        if (eventNames != null) {
+            UIComponent component = (UIComponent) behaviorHolder;
+            ResponseWriter writer = context.getResponseWriter();
+            Collection<Parameter> parametersList = HandlersChain.createParametersList(createParametersMap(context,
+                                                       component));
 
-		public static final String style_ATTRIBUTE = "style";
+            for (String behaviorEventName : eventNames) {
+                if (behaviorEventName.equals(defaultEventName)) {
+                    continue;
+                }
 
-		public static final String align_ATTRIBUTE = "align";
+                String htmlEventName = "on" + behaviorEventName;
 
-		public static final String width_ATTRIBUTE = "width";
+                if ((attributesExclusions == null) || (Arrays.binarySearch(attributesExclusions, htmlEventName) < 0)) {
+                    HandlersChain handlersChain = new HandlersChain(component, parametersList);
 
-		public static final String dir_ATTRIBUTE = "dir";
+                    handlersChain.addInlineHandlerFromAttribute(context, htmlEventName);
+                    handlersChain.addBehaviors(context, behaviorEventName);
 
-		public static final String rules_ATTRIBUTE = "rules";
+                    String handlerScript = handlersChain.toScript();
 
-		public static final String frame_ATTRIBUTE = "frame";
+                    if (!isEmpty(handlerScript)) {
+                        writer.writeAttribute(htmlEventName, handlerScript, htmlEventName);
+                    }
+                }
+            }
+        }
+    }
 
-		public static final String border_ATTRIBUTE = "border";
+    /**
+     * Encode common pass-thru html attributes.
+     *
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    public void encodePassThru(FacesContext context, UIComponent component, String defaultHtmlEvent)
+        throws IOException {
 
-		public static final String cellspacing_ATTRIBUTE = "cellspacing";
+        encodeAttributesFromArray(context, component, HTML.PASS_THRU);
 
-		public static final String cellpadding_ATTRIBUTE = "cellpadding";
+        if (component instanceof ClientBehaviorHolder) {
+            ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
 
-		public static final String summary_ATTRIBUTE = "summary";
+            encodeBehaviors(context, clientBehaviorHolder, defaultHtmlEvent, null);
+        } else {
+            encodeAttributesFromArray(context, component, HTML.PASS_THRU_EVENTS);
+        }
+    }
 
-		public static final String bgcolor_ATTRIBUTE = "bgcolor";
+    /**
+     * Encode pass-through attributes except specified ones
+     *
+     * @param context
+     * @param component
+     * @param exclusions
+     * @throws IOException
+     */
+    public void encodePassThruWithExclusions(FacesContext context, UIComponent component, String exclusions,
+            String defaultHtmlEvent) throws IOException {
+        
+        if (null != exclusions) {
+            String[] exclusionsArray = exclusions.split(",");
 
-		public static final String usemap_ATTRIBUTE = "usemap";
+            encodePassThruWithExclusionsArray(context, component, exclusionsArray, defaultHtmlEvent);
+        }
+    }
 
-		public static final String enctype_ATTRIBUTE = "enctype";
+    public void encodePassThruWithExclusionsArray(FacesContext context, UIComponent component, String[] exclusions,
+            String defaultHtmlEvent) throws IOException {
+        
+        ResponseWriter writer = context.getResponseWriter();
+        Map<String, Object> attributes = component.getAttributes();
 
-		public static final String accept_charset_ATTRIBUTE = "accept-charset";
+        Arrays.sort(exclusions);
 
-		public static final String accept_ATTRIBUTE = "accept";
+        for (int i = 0; i < HTML.PASS_THRU.length; i++) {
+            String attribute = HTML.PASS_THRU[i];
 
-		public static final String target_ATTRIBUTE = "target";
+            if (Arrays.binarySearch(exclusions, attribute) < 0) {
+                encodePassThruAttribute(context, attributes, writer, attribute);
+            }
+        }
 
-		public static final String onsubmit_ATTRIBUTE = "onsubmit";
+        if (component instanceof ClientBehaviorHolder) {
+            ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
 
-		public static final String readonly_ATTRIBUTE = "readonly";
+            encodeBehaviors(context, clientBehaviorHolder, defaultHtmlEvent, exclusions);
+        } else {
+            for (int i = 0; i < HTML.PASS_THRU_EVENTS.length; i++) {
+                String attribute = HTML.PASS_THRU_EVENTS[i];
 
-		public static final String nowrap_ATTRIBUTE = "nowrap";
+                if (Arrays.binarySearch(exclusions, attribute) < 0) {
+                    encodePassThruAttribute(context, attributes, writer, attribute);
+                }
+            }
+        }
+    }
 
-		public static final String src_ATTRIBUTE = "src";
+    /**
+     * Encode one pass-thru attribute, with plain/boolean/url value, got from
+     * properly component attribute.
+     *
+     * @param context
+     * @param writer
+     * @param attribute
+     * @throws IOException
+     */
+    public void encodePassThruAttribute(FacesContext context, Map<String, Object> attributes, ResponseWriter writer,
+            String attribute) throws IOException {
 
-		public static final String media_ATTRIBUTE = "media";
+        Object value = attributeValue(attribute, attributes.get(getComponentAttributeName(attribute)));
 
-		// public static final String onreset_ATTRIBUTE = "onreset";
-		// attributes sets.
-		public static final String[] PASS_THRU = {
-			// DIR_ATTRIBUTE,
-			// LANG_ATTRIBUTE,
-			// STYLE_ATTRIBUTE,
-			// TITLE_ATTRIBUTE
-			"accesskey", "alt", "cols", "height", "lang", "longdesc",
-			"maxlength", "rows", "size", "tabindex", "title", "width", 
-			"dir", "rules", "frame", "border", "cellspacing", "cellpadding", 
-			"summary", "bgcolor", "usemap", "enctype", "accept-charset", 
-			"accept", "target", "charset", "coords", "hreflang", "rel", 
-			"rev", "shape", "disabled", "readonly", "ismap", "align"
-		};
+        if ((null != value) && shouldRenderAttribute(attribute, value)) {
+            if (Arrays.binarySearch(HTML.PASS_THRU_URI, attribute) >= 0) {
+                String url = context.getApplication().getViewHandler().getResourceURL(context, value.toString());
 
-		public static final String[] PASS_THRU_EVENTS = {
-			"onblur", "onchange", "onclick", "ondblclick",
-			"onfocus", "onkeydown", "onkeypress", "onkeyup", "onload",
-			"onmousedown", "onmousemove", "onmouseout", "onmouseover",
-			"onmouseup", "onreset", "onselect", "onsubmit", "onunload"
-		};
-		
-		/**
-		 * HTML attributes allowed boolean-values only
-		 */
-		public static final String[] PASS_THRU_BOOLEAN = { "disabled",
-			"declare", "readonly", "compact", "ismap", "selected",
-			"checked", "nowrap", "noresize", "nohref", "noshade",
-			"multiple" 
-		};
+                url = context.getExternalContext().encodeResourceURL(url);
+                writer.writeURIAttribute(attribute, url, attribute);
+            } else {
+                writer.writeAttribute(attribute, value, attribute);
+            }
+        }
+    }
 
-		/**
-		 * all HTML attributes with URI value.
-		 */
-		public static final String[] PASS_THRU_URI = { "usemap", "background",
-				"codebase", "cite", "data", "classid", "href", "longdesc",
-				"profile", "src" };
+    public void encodeAttributesFromArray(FacesContext context, UIComponent component, String[] attrs)
+        throws IOException {
+        
+        ResponseWriter writer = context.getResponseWriter();
+        Map<String, Object> attributes = component.getAttributes();
 
-		public static final String[] PASS_THRU_STYLES = { "style", "class", };
+        for (int i = 0; i < attrs.length; i++) {
+            String attribute = attrs[i];
 
-		public static final String SPAN_ELEM = "span";
-		public static final String DIV_ELEM = "div";
-		public static final String SCRIPT_ELEM = "script";
-		public static final String LINK_ELEMENT = "link";
-		public static final String STYLE_CLASS_ATTR = "styleClass";
-		public static final String DISABLED_ATTR = "disabled";
-		public static final String TYPE_ATTR = "type";
-		public static final String CHARSET_ATTR = "charset";
-		public static final String COORDS_ATTR = "coords";
-		public static final String HREFLANG_ATTR = "hreflang";
-		public static final String HREF_ATTR = "href";
-		public static final String REL_ATTR = "rel";
-		public static final String REV_ATTR = "rev";
-		public static final String SHAPE_ATTR = "shape";
-		public static final String title_ELEM = "title";
-		public static final String FORM_ELEMENT = "form";
-		public static final String NAME_ATTRIBUTE = "name";
-		public static final String METHOD_ATTRIBUTE = "method";
-		public static final String ACTION_ATTRIBUTE = "action";
-		public static final String INPUT_ELEM = "input";
-		public static final Object INPUT_TYPE_HIDDEN = "hidden";
-		public static final String value_ATTRIBUTE = "value";
-		public static final String td_ELEM = "td";
-		public static final String th_ELEM = "th";
-		public static final String valign_ATTRIBUTE = "valign";
-		public static final String a_ELEMENT = "a";
-		public static final String HTML_ELEMENT = "html";
-		public static final String HEAD_ELEMENT = "head";
-		public static final String BODY_ELEMENT = "body";
-		public static final String TABLE_ELEMENT = "table";
-		public static final String TR_ELEMENT = "tr";
-		public static final String CAPTION_ELEMENT = "caption";
-		public static final String TBOBY_ELEMENT = "tbody";
-		public static final String THEAD_ELEMENT = "thead";
-		public static final String TFOOT_ELEMENT = "tfoot";
-		public static final String IMG_ELEMENT = "img";
-		
-		public static final String DT_ELEMENT = "dt";
-		public static final String DL_ELEMENT = "dl";
-		
-		public static final String TEXT_JAVASCRIPT_TYPE = "text/javascript";
-	}
+            encodePassThruAttribute(context, attributes, writer, attribute);
+        }
+    }
 
-	/**
-	 * Encode id attribute with clientId component property
-	 * 
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	public void encodeId(FacesContext context, UIComponent component)
-			throws IOException {
-		encodeId(context, component, HTML.id_ATTRIBUTE);
-	}
+    /**
+     * Encode attributes given by comma-separated string list.
+     *
+     * @param context
+     *            current JSF context
+     * @param component
+     *            for with render attributes values
+     * @param attrs
+     *            comma separated list of attributes
+     * @throws IOException
+     */
+    public void encodeAttributes(FacesContext context, UIComponent component, String attrs) throws IOException {
+        if (null != attrs) {
+            String[] attrsArray = attrs.split(",");
 
-	/**
-	 * Encode clientId to custom attribute ( for example, to control name )
-	 * 
-	 * @param context
-	 * @param component
-	 * @param attribute
-	 * @throws IOException
-	 */
-	public void encodeId(FacesContext context, UIComponent component,
-			String attribute) throws IOException {
-		String clientId = null;
-		try {
-			clientId = component.getClientId(context);
-		} catch (Exception e) {
-			// just ignore if clientId wasn't inited yet
-		}
-		if (null != clientId) {
-			context.getResponseWriter().writeAttribute(attribute, clientId,
-					(String) getComponentAttributeName(attribute));
-		}
-	}
+            encodeAttributesFromArray(context, component, attrsArray);
+        }
+    }
 
-	/**
-	 * Encode id attribute with clientId component property. Encoded only if id
-	 * not auto generated.
-	 * 
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	public void encodeCustomId(FacesContext context, UIComponent component)
-			throws IOException {
-		if (component.getId() != null
-				&& !component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
-			context.getResponseWriter().writeAttribute(HTML.id_ATTRIBUTE,
-					component.getClientId(context), HTML.id_ATTRIBUTE);
-		}
-	}
+    /**
+     * @param context
+     * @param component
+     * @param property
+     * @param attributeName
+     *
+     * @throws IOException
+     */
+    public void encodeAttribute(FacesContext context, UIComponent component, Object property, String attributeName)
+        throws IOException {
+        
+        ResponseWriter writer = context.getResponseWriter();
+        Object value = component.getAttributes().get(property);
 
-	public Map<String, Object> createParametersMap(FacesContext context, UIComponent component) {
-		Map<String, Object> parameters = new LinkedHashMap<String, Object>();
-		
-		if (component.getChildCount() > 0) {
-			for (UIComponent child : component.getChildren()) {
-				if (child instanceof UIParameter) {
-					UIParameter parameter = (UIParameter) child;
-					
-					String name = parameter.getName();
-					Object value = parameter.getValue();
+        if (shouldRenderAttribute(attributeName, value)) {
+            writer.writeAttribute(attributeName, value, property.toString());
+        }
+    }
 
-					if (null == name) {
-						throw new IllegalArgumentException(Messages.getMessage(
-								Messages.UNNAMED_PARAMETER_ERROR, component
-										.getClientId(context)));
-					}
+    public void encodeAttribute(FacesContext context, UIComponent component, String attribute) throws IOException {
+        encodeAttribute(context, component, getComponentAttributeName(attribute), attribute);
+    }
 
-					boolean escape = true;
-					if (child instanceof JavaScriptParameter) {
-						JavaScriptParameter actionParam = (JavaScriptParameter) child;
-						escape = !actionParam.isNoEscape();
-					}
-					if (escape) {
-						if(value == null) {
-							value = "";
-						}
-					} else {
-						value = new JSReference(value.toString());
-						// if(it.hasNext()){onEvent.append(',');};
-						// renderAjaxLinkParameter( name,
-						// value, onClick, jsForm, nestingForm);
-					}
+    /**
+     * Write html-attribute
+     *
+     * @param writer
+     * @param attribute
+     * @param value
+     * @throws IOException
+     */
+    public void writeAttribute(ResponseWriter writer, String attribute, Object value) throws IOException {
+        if (shouldRenderAttribute(attribute, value)) {
+            writer.writeAttribute(attribute, value.toString(), attribute);
+        }
+    }
 
-					parameters.put(name, value);
-				}
-			}
-		}
-		
-		return parameters;
-	}
-	
-	private void encodeBehaviors(FacesContext context, ClientBehaviorHolder behaviorHolder, 
-			String defaultHtmlEventName, String[] attributesExclusions) throws IOException {
-		
-//		if (attributesExclusions != null && attributesExclusions.length != 0) {
-//			assert false : "Not supported yet";
-//		}
-		
-		//TODO: disabled component check
-		String defaultEventName = behaviorHolder.getDefaultEventName();
-		Collection<String> eventNames = behaviorHolder.getEventNames();
-		if (eventNames != null) {
-			UIComponent component = (UIComponent) behaviorHolder;
-			ResponseWriter writer = context.getResponseWriter();
-			Collection<Parameter> parametersList = 
-				HandlersChain.createParametersList(createParametersMap(context, component));
-			
-			for (String behaviorEventName : eventNames) {
-				if (behaviorEventName.equals(defaultEventName)) {
-					continue;
-				}
-				
-				String htmlEventName = "on" + behaviorEventName;
-				if(attributesExclusions == null || Arrays.binarySearch(attributesExclusions, htmlEventName) < 0) {
-					HandlersChain handlersChain = new HandlersChain(component, parametersList);
-					handlersChain.addInlineHandlerFromAttribute(context, htmlEventName);
-					handlersChain.addBehaviors(context, behaviorEventName);
-					String handlerScript = handlersChain.toScript();
-					
-					if (!isEmpty(handlerScript)) {
-						writer.writeAttribute(htmlEventName, handlerScript, htmlEventName);
-					}
-				}
-			}
-		}
- 	}
-	
-	/**
-	 * Encode common pass-thru html attributes.
-	 * 
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	public void encodePassThru(FacesContext context, UIComponent component, String defaultHtmlEvent)
-			throws IOException {
-		encodeAttributesFromArray(context, component, HTML.PASS_THRU);
-		if (component instanceof ClientBehaviorHolder) {
-			ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
-			encodeBehaviors(context, clientBehaviorHolder, defaultHtmlEvent, null);
-		} else {
-			encodeAttributesFromArray(context, component, HTML.PASS_THRU_EVENTS);
-		}
-	}
+    /**
+     * @return true if and only if the argument <code>attributeVal</code> is
+     *         an instance of a wrapper for a primitive type and its value is
+     *         equal to the default value for that type as given in the spec.
+     */
+    public boolean shouldRenderAttribute(Object attributeVal) {
+        if (null == attributeVal) {
+            return false;
+        } else if ((attributeVal instanceof Boolean)
+                   && ((Boolean) attributeVal).booleanValue() == Boolean.FALSE.booleanValue()) {
+            return false;
+        } else if (attributeVal.toString().length() == 0) {
+            return false;
+        } else {
+            return isValidProperty(attributeVal);
+        }
+    }
 
-	/**
-	 * Encode pass-through attributes except specified ones
-	 * 
-	 * @param context
-	 * @param component
-	 * @param exclusions
-	 * @throws IOException
-	 */
-	public void encodePassThruWithExclusions(FacesContext context,
-			UIComponent component, String exclusions, String defaultHtmlEvent) throws IOException {
-		if (null != exclusions) {
-			String[] exclusionsArray = exclusions.split(",");
-			encodePassThruWithExclusionsArray(context, component,
-					exclusionsArray, defaultHtmlEvent);
-		}
-	}
+    public boolean shouldRenderAttribute(String attributeName, Object attributeVal) {
+        if (!requiredAttributes.contains(attributeName)) {
+            return shouldRenderAttribute(attributeVal);
+        } else {
+            if (null == attributeVal) {
+                return false;
+            }
+        }
 
-	public void encodePassThruWithExclusionsArray(FacesContext context,
-			UIComponent component, String[] exclusions, String defaultHtmlEvent) throws IOException {
-		ResponseWriter writer = context.getResponseWriter();
-		Map<String, Object> attributes = component.getAttributes();
-		Arrays.sort(exclusions);
-		for (int i = 0; i < HTML.PASS_THRU.length; i++) {
-			String attribute = HTML.PASS_THRU[i];
-			if (Arrays.binarySearch(exclusions, attribute) < 0) {
-				encodePassThruAttribute(context, attributes, writer, attribute);
-			}
-		}
-		
-		if (component instanceof ClientBehaviorHolder) {
-			ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
-			encodeBehaviors(context, clientBehaviorHolder, defaultHtmlEvent, exclusions);
-		} else {
-			for (int i = 0; i < HTML.PASS_THRU_EVENTS.length; i++) {
-				String attribute = HTML.PASS_THRU_EVENTS[i];
-				if (Arrays.binarySearch(exclusions, attribute) < 0) {
-					encodePassThruAttribute(context, attributes, writer, attribute);
-				}
-			}
-		}
-	}
+        return true;
+    }
 
-	/**
-	 * Encode one pass-thru attribute, with plain/boolean/url value, got from
-	 * properly component attribute.
-	 * 
-	 * @param context
-	 * @param component
-	 * @param writer
-	 * @param attribute
-	 * @throws IOException
-	 */
-	public void encodePassThruAttribute(FacesContext context, Map<String, Object> attributes,
-			ResponseWriter writer, String attribute) throws IOException {
-		Object value = attributeValue(attribute, attributes
-				.get(getComponentAttributeName(attribute)));
-		if (null != value && shouldRenderAttribute(attribute, value)) {
-			if (Arrays.binarySearch(HTML.PASS_THRU_URI, attribute) >= 0) {
-				String url = context.getApplication().getViewHandler()
-						.getResourceURL(context, value.toString());
-				url = context.getExternalContext().encodeResourceURL(url);
-				writer.writeURIAttribute(attribute, url, attribute);
-			} else {
-				writer.writeAttribute(attribute, value, attribute);
-			}
-		}
-	}
+    /**
+     * Test for valid value of property. by default, for non-setted properties
+     * with Java primitive types of JSF component return appropriate MIN_VALUE .
+     *
+     * @param property -
+     *            value of property returned from
+     *            {@link UIComponent#getAttributes()}
+     * @return true for setted property, false otherthise.
+     */
+    public boolean isValidProperty(Object property) {
+        if (null == property) {
+            return false;
+        } else if ((property instanceof Integer) && ((Integer) property).intValue() == Integer.MIN_VALUE) {
+            return false;
+        } else if ((property instanceof Double) && ((Double) property).doubleValue() == Double.MIN_VALUE) {
+            return false;
+        } else if ((property instanceof Character) && ((Character) property).charValue() == Character.MIN_VALUE) {
+            return false;
+        } else if ((property instanceof Float) && ((Float) property).floatValue() == Float.MIN_VALUE) {
+            return false;
+        } else if ((property instanceof Short) && ((Short) property).shortValue() == Short.MIN_VALUE) {
+            return false;
+        } else if ((property instanceof Byte) && ((Byte) property).byteValue() == Byte.MIN_VALUE) {
+            return false;
+        } else if ((property instanceof Long) && ((Long) property).longValue() == Long.MIN_VALUE) {
+            return false;
+        }
 
-	public void encodeAttributesFromArray(FacesContext context,
-			UIComponent component, String[] attrs) throws IOException {
-		ResponseWriter writer = context.getResponseWriter();
-		Map<String, Object> attributes = component.getAttributes();
-		for (int i = 0; i < attrs.length; i++) {
-			String attribute = attrs[i];
-			encodePassThruAttribute(context, attributes, writer, attribute);
-		}
-	}
+        return true;
+    }
 
-	/**
-	 * Encode attributes given by comma-separated string list.
-	 * 
-	 * @param context
-	 *            current JSF context
-	 * @param component
-	 *            for with render attributes values
-	 * @param attrs
-	 *            comma separated list of attributes
-	 * @throws IOException
-	 */
-	public void encodeAttributes(FacesContext context, UIComponent component,
-			String attrs) throws IOException {
-		if (null != attrs) {
-			String[] attrsArray = attrs.split(",");
-			encodeAttributesFromArray(context, component, attrsArray);
-		}
-	}
+    /**
+     * Checks if the argument passed in is empty or not.
+     * Object is empty if it is: <br />
+     *  - <code>null<code><br />
+     *  - zero-length string<br />
+     *  - empty collection<br />
+     *  - empty map<br />
+     *  - zero-length array<br />
+     *
+     * @param o object to check for emptiness
+     * @since 3.3.2
+     * @return <code>true</code> if the argument is empty, <code>false</code> otherwise
+     */
+    public boolean isEmpty(Object o) {
+        if (null == o) {
+            return true;
+        }
 
-	/**
-	 * @param context
-	 * @param component
-	 * @param string
-	 * @param string2
-	 * @throws IOException
-	 */
-	public void encodeAttribute(FacesContext context, UIComponent component,
-			Object property, String attributeName) throws IOException {
-		ResponseWriter writer = context.getResponseWriter();
-		Object value = component.getAttributes().get(property);
-		if (shouldRenderAttribute(attributeName, value)) {
-			writer.writeAttribute(attributeName, value, property.toString());
-		}
+        if (o instanceof String) {
+            return 0 == ((String) o).length();
+        }
 
-	}
+        if (o instanceof Collection<?>) {
+            return ((Collection<?>) o).isEmpty();
+        }
 
-	public void encodeAttribute(FacesContext context, UIComponent component,
-			String attribute) throws IOException {
-		encodeAttribute(context, component,
-				getComponentAttributeName(attribute), attribute);
-	}
+        if (o instanceof Map<?, ?>) {
+            return ((Map<?, ?>) o).isEmpty();
+        }
 
-	/**
-	 * Write html-attribute
-	 * 
-	 * @param writer
-	 * @param attribute
-	 * @param value
-	 * @throws IOException
-	 */
-	public void writeAttribute(ResponseWriter writer, String attribute,
-			Object value) throws IOException {
-		if (shouldRenderAttribute(attribute, value)) {
-			writer.writeAttribute(attribute, value.toString(), attribute);
-		}
-	}
+        if (o.getClass().isArray()) {
+            return Array.getLength(o) == 0;
+        }
 
-	/**
-	 * @return true if and only if the argument <code>attributeVal</code> is
-	 *         an instance of a wrapper for a primitive type and its value is
-	 *         equal to the default value for that type as given in the spec.
-	 */
+        return false;
+    }
 
-	public boolean shouldRenderAttribute(Object attributeVal) {
-		if (null == attributeVal) {
-			return false;
-		} else if (attributeVal instanceof Boolean
-				&& ((Boolean) attributeVal).booleanValue() == Boolean.FALSE
-						.booleanValue()) {
-			return false;
-		} else if (attributeVal.toString().length() == 0) {
-			return false;
-		} else
-			return isValidProperty(attributeVal);
-	}
-	
-	public boolean shouldRenderAttribute(String attributeName, Object attributeVal) {
-		if (!requiredAttributes.contains(attributeName)) {
-			return shouldRenderAttribute(attributeVal);
-		} else {
-			if (null == attributeVal) {
-				return false;
-			}
-		}
-		return true;
-	}
+    /**
+     * Puts value into map under specified key if the value is not empty and not default.
+     * Performs optional value wrapping.
+     *
+     * @param hash
+     * @param name
+     * @param value
+     * @param defaultValue
+     * @param wrapper
+     *
+     * @since 3.3.2
+     */
+    public void addToScriptHash(Map<String, Object> hash, String name, Object value, String defaultValue,
+                                ScriptHashVariableWrapper wrapper) {
+        ScriptHashVariableWrapper wrapperOrDefault = (wrapper != null) ? wrapper : ScriptHashVariableWrapper.DEFAULT;
 
-	/**
-	 * Test for valid value of property. by default, for non-setted properties
-	 * with Java primitive types of JSF component return appropriate MIN_VALUE .
-	 * 
-	 * @param property -
-	 *            value of property returned from
-	 *            {@link UIComponent#getAttributes()}
-	 * @return true for setted property, false otherthise.
-	 */
-	public boolean isValidProperty(Object property) {
-		if (null == property) {
-			return false;
-		} else if (property instanceof Integer
-				&& ((Integer) property).intValue() == Integer.MIN_VALUE) {
-			return false;
-		} else if (property instanceof Double
-				&& ((Double) property).doubleValue() == Double.MIN_VALUE) {
-			return false;
-		} else if (property instanceof Character
-				&& ((Character) property).charValue() == Character.MIN_VALUE) {
-			return false;
-		} else if (property instanceof Float
-				&& ((Float) property).floatValue() == Float.MIN_VALUE) {
-			return false;
-		} else if (property instanceof Short
-				&& ((Short) property).shortValue() == Short.MIN_VALUE) {
-			return false;
-		} else if (property instanceof Byte
-				&& ((Byte) property).byteValue() == Byte.MIN_VALUE) {
-			return false;
-		} else if (property instanceof Long
-				&& ((Long) property).longValue() == Long.MIN_VALUE) {
-			return false;
-		}
-		return true;
-	}
+        if (isValidProperty(value) && !isEmpty(value)) {
+            if (!isEmpty(defaultValue)) {
+                if (!defaultValue.equals(value.toString())) {
+                    hash.put(name, wrapperOrDefault.wrap(value));
+                }
+            } else {
+                if (!(value instanceof Boolean) || ((Boolean) value).booleanValue()) {
+                    hash.put(name, wrapperOrDefault.wrap(value));
+                }
+            }
+        }
+    }
 
-	/**
-	 * Checks if the argument passed in is empty or not.
-	 * Object is empty if it is: <br />
-	 * 	- <code>null<code><br />
-	 * 	- zero-length string<br />
-	 * 	- empty collection<br />
-	 * 	- empty map<br />
-	 * 	- zero-length array<br />
-	 * 
-	 * @param o object to check for emptiness
-	 * @since 3.3.2
-	 * @return <code>true</code> if the argument is empty, <code>false</code> otherwise
-	 */
-	public boolean isEmpty(Object o) {
-		if (null == o) {
-			return true;
-		}
-		if (o instanceof String ) {
-			return (0 == ((String)o).length());
-		}
-		if (o instanceof Collection<?>) {
-			return ((Collection<?>)o).isEmpty();
-		}
-		if (o instanceof Map<?, ?>) {
-			return ((Map<?, ?>)o).isEmpty();
-		}
-		if (o.getClass().isArray()) {
-			return Array.getLength(o) == 0;
-		}
-		return false;
-	}
-	
-	/**
-	 * Wrapper class around object value used to transform values into particular JS objects
-	 * 
-	 * @author Nick Belaevski
-	 * @since 3.3.2
-	 */
-	public static enum ScriptHashVariableWrapper {
+    /**
+     * Puts value into map under specified key if the value is not empty and not default.
+     * Performs optional value wrapping.
+     *
+     * @param hash
+     * @param name
+     * @param value
+     * @param defaultValue
+     *
+     * @since 3.3.2
+     */
+    public void addToScriptHash(Map<String, Object> hash, String name, Object value, String defaultValue) {
+        addToScriptHash(hash, name, value, defaultValue, null);
+    }
 
-		/**
-		 * No-op default wrapper
-		 */
-		DEFAULT {
+    /**
+     * Puts value into map under specified key if the value is not empty and not default.
+     * Performs optional value wrapping.
+     *
+     * @param hash
+     * @param name
+     * @param value
+     *
+     * @since 3.3.2
+     */
+    public void addToScriptHash(Map<String, Object> hash, String name, Object value) {
+        addToScriptHash(hash, name, value, null, null);
+    }
 
-			@Override
-			Object wrap(Object o) {
-				return o;
-			}
-			
-		}, 
-		
-		/**
-		 * Event handler functions wrapper. Wraps <pre>functionCode</pre> object into:
-		 * <pre>function(event) {
-		 *   functionCode
-		 * }</pre>
-		 */
-		EVENT_HANDLER {
+    /**
+     * Convert HTML attribute name to component property name.
+     *
+     * @param key
+     * @return
+     */
+    protected Object getComponentAttributeName(Object key) {
+        Object converted = substitutions.get(key);
 
-			@Override
-			Object wrap(Object o) {
-				return new JSFunctionDefinition("event").addToBody(o);
-			}
-			
-		};
-		
-		/**
-		 * Method that does the wrapping
-		 * 
-		 * @param o object to wrap
-		 * @return wrapped object
-		 */
-		abstract Object wrap(Object o);
-	}
-	
-	/**
-	 * Puts value into map under specified key if the value is not empty and not default. 
-	 * Performs optional value wrapping.
-	 * 
-	 * @param hash
-	 * @param name
-	 * @param value
-	 * @param defaultValue
-	 * @param wrapper
-	 * 
-	 * @since 3.3.2
-	 */
-	public void addToScriptHash(Map<String, Object> hash, 
-			String name, 
-			Object value, 
-			String defaultValue,
-			ScriptHashVariableWrapper wrapper) {
-		
-		ScriptHashVariableWrapper wrapperOrDefault = wrapper != null ? wrapper : ScriptHashVariableWrapper.DEFAULT;
-		
-		if (isValidProperty(value) && !isEmpty(value)) {
-			if (!isEmpty(defaultValue)) {
-				if (!defaultValue.equals(value.toString())) {
-					hash.put(name, wrapperOrDefault.wrap(value));
-				}
-			} else {
-				if (!(value instanceof Boolean) || ((Boolean) value).booleanValue()) {
-					hash.put(name, wrapperOrDefault.wrap(value));
-				}
-			}
-		}
-	}
-	
-	/**
-	 * Puts value into map under specified key if the value is not empty and not default. 
-	 * Performs optional value wrapping.
-	 * 
-	 * @param hash
-	 * @param name
-	 * @param value
-	 * @param defaultValue
-	 * 
-	 * @since 3.3.2
-	 */
-	public void addToScriptHash(Map<String, Object> hash, 
-			String name, 
-			Object value, 
-			String defaultValue) {
-		addToScriptHash(hash, name, value, defaultValue, null);
-	}
+        if (null == converted) {
+            return key;
+        } else {
+            return converted;
+        }
+    }
 
-	/**
-	 * Puts value into map under specified key if the value is not empty and not default. 
-	 * Performs optional value wrapping.
-	 * 
-	 * @param hash
-	 * @param name
-	 * @param value
-	 * 
-	 * @since 3.3.2
-	 */
-	public void addToScriptHash(Map<String, Object> hash, 
-			String name, 
-			Object value) {
-		addToScriptHash(hash, name, value, null, null);
-	}
+    /**
+     * Convert attribute value to proper object. For known html boolean
+     * attributes return name for true value, otherthise - null. For non-boolean
+     * attributes return same value.
+     *
+     * @param name
+     *            attribute name.
+     * @param value
+     * @return
+     */
+    protected Object attributeValue(String name, Object value) {
+        if (null == value || Arrays.binarySearch(HTML.PASS_THRU_BOOLEAN, name) < 0) {
+            return value;
+        }
 
-	/**
-	 * Convert HTML attribute name to component property name.
-	 * 
-	 * @param key
-	 * @return
-	 */
-	protected Object getComponentAttributeName(Object key) {
-		Object converted = substitutions.get(key);
-		if (null == converted) {
-			return key;
-		} else {
-			return converted;
-		}
-	}
+        boolean checked;
 
-	/**
-	 * Convert attribute value to proper object. For known html boolean
-	 * attributes return name for true value, otherthise - null. For non-boolean
-	 * attributes return same value.
-	 * 
-	 * @param name
-	 *            attribute name.
-	 * @param value
-	 * @return
-	 */
-	protected Object attributeValue(String name, Object value) {
-		if (null != value
-				&& Arrays.binarySearch(HTML.PASS_THRU_BOOLEAN, name) >= 0) {
-			boolean checked = false;
-			if (value instanceof Boolean) {
-				checked = ((Boolean) value).booleanValue();
-			} else {
-				if (!(value instanceof String)) {
-					value = value.toString();
-				}
-				checked = Boolean.parseBoolean((String) value);
-			}
-			return checked ? name : null;
-		} else {
-			return value;
-		}
-	}
+        if (value instanceof Boolean) {
+            checked = ((Boolean) value).booleanValue();
+        } else {
+            checked = Boolean.parseBoolean(value.toString());
+        }
 
-	/**
-	 * Get boolean value of logical attribute
-	 * 
-	 * @param component
-	 * @param name
-	 *            attribute name
-	 * @return true if attribute is equals Boolean.TRUE or String "true" , false
-	 *         otherwise.
-	 */
-	public boolean isBooleanAttribute(UIComponent component, String name) {
-		Object attrValue = component.getAttributes().get(name);
-		boolean result = false;
-		if (null != attrValue) {
-			if (attrValue instanceof String) {
-				result = "true".equalsIgnoreCase((String) attrValue);
-			} else {
-				result = Boolean.TRUE.equals(attrValue);
-			}
-		}
-		return result;
-	}
+        return checked ? name : null;
+    }
 
-	/**
-	 * Return converted value for {@link javax.faces.component.ValueHolder} as
-	 * String, perform nessesary convertions.
-	 * 
-	 * @param context
-	 * @param component
-	 * @return
-	 */
-	public String getValueAsString(FacesContext context, UIComponent component) {
-		// First - get submitted value for input components
-		if (component instanceof EditableValueHolder) {
-			EditableValueHolder input = (EditableValueHolder) component;
-			String submittedValue = (String) input.getSubmittedValue();
-			if (null != submittedValue) {
-				return submittedValue;
-			}
-		}
-		// If no submitted value presented - convert same for UIInput/UIOutput
-		if (component instanceof ValueHolder) {
-			return formatValue(context, component, ((ValueHolder) component)
-					.getValue());
-		} else {
-			throw new IllegalArgumentException(Messages.getMessage(
-					Messages.CONVERTING_NON_VALUE_HOLDER_COMPONENT_ERROR,
-					component.getId()));
-		}
-	}
+    /**
+     * Get boolean value of logical attribute
+     *
+     * @param component
+     * @param name
+     *            attribute name
+     * @return true if attribute is equals Boolean.TRUE or String "true" , false
+     *         otherwise.
+     */
+    public boolean isBooleanAttribute(UIComponent component, String name) {
+        Object attrValue = component.getAttributes().get(name);
+        boolean result = false;
 
-	/**
-	 * Convert any object value to string. If component instance of
-	 * {@link ValueHolder } got {@link Converter} for formatting. If not,
-	 * attempt to use converter based on value type.
-	 * 
-	 * @param context
-	 * @param component
-	 * @return
-	 */
-	public String formatValue(FacesContext context, UIComponent component,
-			Object value) {
-		if (value instanceof String) {
-			return (String) value;
-		}
-		Converter converter = null;
-		if (component instanceof ValueHolder) {
-			ValueHolder holder = (ValueHolder) component;
-			converter = holder.getConverter();
-		}
-		if (null == converter && null != value) {
-			try {
-				converter = context.getApplication().createConverter(
-						value.getClass());
-			} catch (FacesException e) {
-				// TODO - log converter exception.
-			}
-		}
-		if (null == converter) {
-			if (null != value) {
-				return value.toString();
-			}
-		} else {
-			return converter.getAsString(context, component, value);
-		}
-		return "";
-	}
+        if (null != attrValue) {
+            if (attrValue instanceof String) {
+                result = "true".equalsIgnoreCase((String) attrValue);
+            } else {
+                result = Boolean.TRUE.equals(attrValue);
+            }
+        }
 
-	public String encodePx(String value) {
-		return HtmlDimensions.formatPx(HtmlDimensions.decode(value));
-	}
+        return result;
+    }
 
-	/**
-	 * formats given value to
-	 * 
-	 * @param value
-	 * @param pattern
-	 * @return
-	 */
-	public String encodePctOrPx(String value) {
-		if (value.indexOf('%') > 0) {
-			return value;
-		} else {
-			return encodePx(value);
-		}
-	}
+    /**
+     * Return converted value for {@link javax.faces.component.ValueHolder} as
+     * String, perform nessesary convertions.
+     *
+     * @param context
+     * @param component
+     * @return
+     */
+    public String getValueAsString(FacesContext context, UIComponent component) {
 
-	/**
-	 * Find nested form for given component
-	 * 
-	 * @param component
-	 * @return nested <code>UIForm</code> component, or <code>null</code>
-	 */
-	public UIForm getNestingForm(FacesContext context, UIComponent component) {
-		UIComponent parent = component.getParent();
-		while (parent != null && !(parent instanceof UIForm)) {
-			parent = parent.getParent();
-		}
+        // First - get submitted value for input components
+        if (component instanceof EditableValueHolder) {
+            EditableValueHolder input = (EditableValueHolder) component;
+            String submittedValue = (String) input.getSubmittedValue();
 
-		UIForm nestingForm = null;
-		if (parent != null) {
-			// link is nested inside a form
-			nestingForm = (UIForm) parent;
-		}
-		return nestingForm;
-	}
+            if (null != submittedValue) {
+                return submittedValue;
+            }
+        }
 
-	/**
-	 * @param context
-	 * @param component
-	 * @return
-	 * @throws IOException
-	 */
-	public void encodeBeginFormIfNessesary(FacesContext context,
-			UIComponent component) throws IOException {
-		UIForm form = getNestingForm(context, component);
-		if (null == form) {
-			ResponseWriter writer = context.getResponseWriter();
-			String clientId = component.getClientId(context) + DUMMY_FORM_ID;
-			encodeBeginForm(context, component, writer, clientId);
-			// writer.writeAttribute(HTML.style_ATTRIBUTE, "margin:0;
-			// padding:0;", null);
-		}
-	}
+        // If no submitted value presented - convert same for UIInput/UIOutput
+        if (component instanceof ValueHolder) {
+            return formatValue(context, component, ((ValueHolder) component).getValue());
+        } else {
+            throw new IllegalArgumentException(
+                Messages.getMessage(Messages.CONVERTING_NON_VALUE_HOLDER_COMPONENT_ERROR, component.getId()));
+        }
+    }
 
-	/**
-	 * @param context
-	 * @param component
-	 * @param writer
-	 * @param clientId
-	 * @throws IOException
-	 */
-	public void encodeBeginForm(FacesContext context, UIComponent component,
-			ResponseWriter writer, String clientId) throws IOException {
-		String actionURL = getActionUrl(context);
-		String encodeActionURL = context.getExternalContext().encodeActionURL(
-				actionURL);
+    /**
+     * Convert any object value to string. If component instance of
+     * {@link ValueHolder } got {@link Converter} for formatting. If not,
+     * attempt to use converter based on value type.
+     *
+     * @param context
+     * @param component
+     * @return
+     */
+    public String formatValue(FacesContext context, UIComponent component, Object value) {
+        if (value instanceof String) {
+            return (String) value;
+        }
 
-		writer.startElement(HTML.FORM_ELEMENT, component);
-		writer.writeAttribute(HTML.id_ATTRIBUTE, clientId, null);
-		writer.writeAttribute(HTML.NAME_ATTRIBUTE, clientId, null);
-		writer.writeAttribute(HTML.METHOD_ATTRIBUTE, "post", null);
-		writer.writeAttribute(HTML.style_ATTRIBUTE, "margin:0; padding:0; display: inline;",
-				null);
-		writer.writeURIAttribute(HTML.ACTION_ATTRIBUTE, encodeActionURL,
-				"action");
-	}
+        Converter converter = null;
 
-	/**
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	public void encodeEndFormIfNessesary(FacesContext context,
-			UIComponent component) throws IOException {
-		UIForm form = getNestingForm(context, component);
-		if (null == form) {
-			ResponseWriter writer = context.getResponseWriter();
-			// TODO - hidden form parameters ?
-			encodeEndForm(context, writer);
-		}
-	}
+        if (component instanceof ValueHolder) {
+            ValueHolder holder = (ValueHolder) component;
 
-	/**
-	 * @param context
-	 * @param writer
-	 * @throws IOException
-	 */
-	public void encodeEndForm(FacesContext context, ResponseWriter writer)
-			throws IOException {
-		AjaxRendererUtils.writeState(context);
-		writer.endElement(HTML.FORM_ELEMENT);
-	}
+            converter = holder.getConverter();
+        }
 
-	/**
-	 * @param facesContext
-	 * @return String A String representing the action URL
-	 */
-	public String getActionUrl(FacesContext facesContext) {
-		ViewHandler viewHandler = facesContext.getApplication()
-				.getViewHandler();
-		String viewId = facesContext.getViewRoot().getViewId();
-		return viewHandler.getActionURL(facesContext, viewId);
-	}
+        if ((null == converter) && (null != value)) {
+            try {
+                converter = context.getApplication().createConverter(value.getClass());
+            } catch (FacesException e) {
 
-	/**
-	 * Simplified version of {@link encodeId}
-	 * 
-	 * @param context
-	 * @param component
-	 * @return client id of current component
-	 */
-	public String clientId(FacesContext context, UIComponent component) {
-		String clientId = "";
-		try {
-			clientId = component.getClientId(context);
-		} catch (Exception e) {
-			// just ignore
-		}
-		return clientId;
-	}
+                // TODO - log converter exception.
+            }
+        }
 
-	/**
-	 * Wtrie JavaScript with start/end elements and type.
-	 * 
-	 * @param context
-	 * @param tab
-	 * @param string
-	 */
+        if (null == converter) {
+            if (null != value) {
+                return value.toString();
+            }
+        } else {
+            return converter.getAsString(context, component, value);
+        }
 
-	public void writeScript(FacesContext context, UIComponent component,
-			Object script) throws IOException {
-		ResponseWriter writer = context.getResponseWriter();
-		writer.startElement(HTML.SCRIPT_ELEM, component);
-		writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", "type");
-		writer.writeText(script, null);
-		writer.endElement(HTML.SCRIPT_ELEM);
-	}
+        return "";
+    }
 
-	/**
-	 * @param context
-	 * @param component
-	 * @param shortIds
-	 * @since 4.0
-	 * @return
-	 */
-	public Collection<String> findComponentsFor(FacesContext context, UIComponent component, Collection<String> shortIds) {
-		//TODO - implement
-		//TODO add support for @*
-		Set<String> result = new LinkedHashSet<String>();
-		for (String id : shortIds) {
-			if (AjaxRendererUtils.THIS.equals(id)) {
-				result.add(component.getClientId(context));
-			} else if (AjaxRendererUtils.FORM.equals(id)) {
-				result.add(getNestingForm(context, component).getClientId(context));
-			} else {
-				UIComponent foundComponent = findComponentFor(component, id);
-				result.add(foundComponent != null ? foundComponent.getClientId(context) : id);
-			}
-		}
-		
-		return result;
-	}
-	
+    public String encodePx(String value) {
+        return HtmlDimensions.formatPx(HtmlDimensions.decode(value));
+    }
 
-	public UIComponent findComponentFor(FacesContext context,
-		UIComponent component, String id) {
-	    	return findComponentFor(component,id);
-	}
+    /**
+     * formats given value to
+     *
+     * @param value
+     *
+     * @return
+     */
+    public String encodePctOrPx(String value) {
+        if (value.indexOf('%') > 0) {
+            return value;
+        } else {
+            return encodePx(value);
+        }
+    }
 
-	/**
-	 * @param component
-	 * @param id
-	 * @return
-	 */
-	public UIComponent findComponentFor(UIComponent component,
-			String id) {
-	    
-	    	if (id == null) {
-	    	    throw new NullPointerException("id is null!");
-	    	}
-	    	
-	    	if (id.length() == 0) {
-	    	    return null;
-	    	}
-	    
-		UIComponent target = null;
-		UIComponent parent = component;
-		UIComponent root = component;
-		while (null == target && null != parent) {
-			target = parent.findComponent(id);
-			root = parent;
-			parent = parent.getParent();
-		}
-		if (null == target) {
-			target = findUIComponentBelow(root, id);
-		}
-		return target;
-	}
-	
-	/**
-	 * If target component contains generated id and for doesn't, correct for id 
-	 * @param forAttr
-	 * @param target
-	 * 
-	 */
-	public String correctForIdReference(String forAttr, UIComponent component) {
-		
-		int contains = forAttr.indexOf(UIViewRoot.UNIQUE_ID_PREFIX);
-		if (contains <= 0) {
-			String id = component.getId();
-			int pos = id.indexOf(UIViewRoot.UNIQUE_ID_PREFIX); 
-			if ( pos > 0) {
-				forAttr = forAttr.concat(id.substring(pos));
-			}
-		}
-		return forAttr;
-	}
+    /**
+     * Find nested form for given component
+     *
+     * @param component
+     * @return nested <code>UIForm</code> component, or <code>null</code>
+     */
+    public UIForm getNestingForm(FacesContext context, UIComponent component) {
+        UIComponent parent = component.getParent();
 
-	private UIComponent findUIComponentBelow(UIComponent root, String id) {
-		UIComponent target = null;
-		for (Iterator<UIComponent> iter = root.getFacetsAndChildren(); iter.hasNext();) {
-			UIComponent child = (UIComponent) iter.next();
-			if (child instanceof NamingContainer) {
-				try {
-					target = child.findComponent(id);
-				} catch (IllegalArgumentException iae) {
-					continue;
-				}
-			}
-			if (target == null) {
-				if (child.getChildCount() > 0 || child.getFacetCount() > 0) {
-					target = findUIComponentBelow(child, id);
-				}
-			}
+        while ((parent != null) && !(parent instanceof UIForm)) {
+            parent = parent.getParent();
+        }
 
-			if (target != null) {
-				break;
-			}
+        UIForm nestingForm = null;
 
-		}
-		return target;
-	}
-	
-	public static void writeEventHandlerFunction(FacesContext context,
-			UIComponent component, String eventName) throws IOException {
+        if (parent != null) {
 
-		ResponseWriter writer = context.getResponseWriter();
-		Object script = component.getAttributes().get(eventName);
-		if (script != null && !script.equals("")) {
-			JSFunctionDefinition onEventDefinition = new JSFunctionDefinition();
-			onEventDefinition.addParameter("event");
-			onEventDefinition.addToBody(script);
-			writer.writeText(eventName + ": "
-					+ onEventDefinition.toScript(), null);
-		}else{
-			writer.writeText(eventName + ": ''", null);
-		}
-	}
-	
-	public JSFunctionDefinition getAsEventHandler(FacesContext context, UIComponent component, String attributeName, String append) {
-		String event = (String) component.getAttributes().get(attributeName);
-				
-		if (event != null) {
-			event = event.trim();
-		
-			if (event.length() != 0) {
-				JSFunctionDefinition function = new JSFunctionDefinition();
-				function.addParameter("event");
-				if(null!=append && append.length()>0){
-					function.addToBody(event+append);
-				}else{
-					function.addToBody(event);
-				}
-			return  function;
-			}
-		}
+            // link is nested inside a form
+            nestingForm = (UIForm) parent;
+        }
 
-		return null;
-	}
-	
-	public String escapeJavaScript(Object o) {
-		if (o != null) {
-			StringBuilder result = new StringBuilder();
-			JSEncoder encoder = new JSEncoder();
+        return nestingForm;
+    }
 
-			char chars[] = o.toString().toCharArray();
+    /**
+     * @param context
+     * @param component
+     * @return
+     * @throws IOException
+     */
+    public void encodeBeginFormIfNessesary(FacesContext context, UIComponent component) throws IOException {
+        UIForm form = getNestingForm(context, component);
+
+        if (null == form) {
+            ResponseWriter writer = context.getResponseWriter();
+            String clientId = component.getClientId(context) + DUMMY_FORM_ID;
+
+            encodeBeginForm(context, component, writer, clientId);
+
+            // writer.writeAttribute(HTML.STYLE_ATTRIBUTE, "margin:0;
+            // padding:0;", null);
+        }
+    }
+
+    /**
+     * @param context
+     * @param component
+     * @param writer
+     * @param clientId
+     * @throws IOException
+     */
+    public void encodeBeginForm(FacesContext context, UIComponent component, ResponseWriter writer, String clientId)
+        throws IOException {
+        
+        String actionURL = getActionUrl(context);
+        String encodeActionURL = context.getExternalContext().encodeActionURL(actionURL);
+
+        writer.startElement(HTML.FORM_ELEMENT, component);
+        writer.writeAttribute(HTML.ID_ATTRIBUTE, clientId, null);
+        writer.writeAttribute(HTML.NAME_ATTRIBUTE, clientId, null);
+        writer.writeAttribute(HTML.METHOD_ATTRIBUTE, "post", null);
+        writer.writeAttribute(HTML.STYLE_ATTRIBUTE, "margin:0; padding:0; display: inline;", null);
+        writer.writeURIAttribute(HTML.ACTION_ATTRIBUTE, encodeActionURL, "action");
+    }
+
+    /**
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    public void encodeEndFormIfNessesary(FacesContext context, UIComponent component) throws IOException {
+        UIForm form = getNestingForm(context, component);
+
+        if (null == form) {
+            ResponseWriter writer = context.getResponseWriter();
+
+            // TODO - hidden form parameters ?
+            encodeEndForm(context, writer);
+        }
+    }
+
+    /**
+     * @param context
+     * @param writer
+     * @throws IOException
+     */
+    public void encodeEndForm(FacesContext context, ResponseWriter writer) throws IOException {
+        AjaxRendererUtils.writeState(context);
+        writer.endElement(HTML.FORM_ELEMENT);
+    }
+
+    /**
+     * @param facesContext
+     * @return String A String representing the action URL
+     */
+    public String getActionUrl(FacesContext facesContext) {
+        ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
+        String viewId = facesContext.getViewRoot().getViewId();
+
+        return viewHandler.getActionURL(facesContext, viewId);
+    }
+
+    /**
+     * Simplified version of {@link encodeId}
+     *
+     * @param context
+     * @param component
+     * @return client id of current component
+     */
+    public String clientId(FacesContext context, UIComponent component) {
+        String clientId = "";
+
+        try {
+            clientId = component.getClientId(context);
+        } catch (Exception e) {
+
+            // just ignore
+        }
+
+        return clientId;
+    }
+
+    /**
+     * Wtrie JavaScript with start/end elements and type.
+     *
+     * @param context
+     * @param component
+     * @param script
+     */
+    public void writeScript(FacesContext context, UIComponent component, Object script) throws IOException {
+        ResponseWriter writer = context.getResponseWriter();
+
+        writer.startElement(HTML.SCRIPT_ELEM, component);
+        writer.writeAttribute(HTML.TYPE_ATTR, "text/javascript", "type");
+        writer.writeText(script, null);
+        writer.endElement(HTML.SCRIPT_ELEM);
+    }
+
+    /**
+     * @param context
+     * @param component
+     * @param shortIds
+     * @since 4.0
+     * @return
+     */
+    public Collection<String> findComponentsFor(FacesContext context, UIComponent component,
+            Collection<String> shortIds) {
+
+        // TODO - implement
+        // TODO add support for @*
+        Set<String> result = new LinkedHashSet<String>();
+
+        for (String id : shortIds) {
+            if (AjaxRendererUtils.THIS.equals(id)) {
+                result.add(component.getClientId(context));
+            } else if (AjaxRendererUtils.FORM.equals(id)) {
+                result.add(getNestingForm(context, component).getClientId(context));
+            } else {
+                UIComponent foundComponent = findComponentFor(component, id);
+
+                result.add((foundComponent != null) ? foundComponent.getClientId(context) : id);
+            }
+        }
+
+        return result;
+    }
+
+    public UIComponent findComponentFor(FacesContext context, UIComponent component, String id) {
+        return findComponentFor(component, id);
+    }
+
+    /**
+     * @param component
+     * @param id
+     * @return
+     */
+    public UIComponent findComponentFor(UIComponent component, String id) {
+        if (id == null) {
+            throw new NullPointerException("id is null!");
+        }
+
+        if (id.length() == 0) {
+            return null;
+        }
+
+        UIComponent target = null;
+        UIComponent parent = component;
+        UIComponent root = component;
+
+        while ((null == target) && (null != parent)) {
+            target = parent.findComponent(id);
+            root = parent;
+            parent = parent.getParent();
+        }
+
+        if (null == target) {
+            target = findUIComponentBelow(root, id);
+        }
+
+        return target;
+    }
+
+    /**
+     * If target component contains generated id and for doesn't, correct for id
+     * @param forAttr
+     * @param component
+     *
+     */
+    public String correctForIdReference(String forAttr, UIComponent component) {
+        int contains = forAttr.indexOf(UIViewRoot.UNIQUE_ID_PREFIX);
+
+        if (contains <= 0) {
+            String id = component.getId();
+            int pos = id.indexOf(UIViewRoot.UNIQUE_ID_PREFIX);
+
+            if (pos > 0) {
+                return forAttr.concat(id.substring(pos));
+            }
+        }
+
+        return forAttr;
+    }
+
+    private UIComponent findUIComponentBelow(UIComponent root, String id) {
+        UIComponent target = null;
+
+        for (Iterator<UIComponent> iter = root.getFacetsAndChildren(); iter.hasNext(); ) {
+            UIComponent child = (UIComponent) iter.next();
+
+            if (child instanceof NamingContainer) {
+                try {
+                    target = child.findComponent(id);
+                } catch (IllegalArgumentException iae) {
+                    continue;
+                }
+            }
+
+            if (target == null) {
+                if ((child.getChildCount() > 0) || (child.getFacetCount() > 0)) {
+                    target = findUIComponentBelow(child, id);
+                }
+            }
+
+            if (target != null) {
+                break;
+            }
+        }
+
+        return target;
+    }
+
+    public static void writeEventHandlerFunction(FacesContext context, UIComponent component, String eventName)
+        throws IOException {
+        
+        ResponseWriter writer = context.getResponseWriter();
+        Object script = component.getAttributes().get(eventName);
+
+        if ((script != null) && !script.equals("")) {
+            JSFunctionDefinition onEventDefinition = new JSFunctionDefinition();
+
+            onEventDefinition.addParameter("event");
+            onEventDefinition.addToBody(script);
+            writer.writeText(eventName + ": " + onEventDefinition.toScript(), null);
+        } else {
+            writer.writeText(eventName + ": ''", null);
+        }
+    }
+
+    public JSFunctionDefinition getAsEventHandler(FacesContext context, UIComponent component, String attributeName,
+            String append) {
+        String event = (String) component.getAttributes().get(attributeName);
+
+        if (event != null) {
+            event = event.trim();
+
+            if (event.length() != 0) {
+                JSFunctionDefinition function = new JSFunctionDefinition();
+
+                function.addParameter("event");
+
+                if ((null != append) && (append.length() > 0)) {
+                    function.addToBody(event + append);
+                } else {
+                    function.addToBody(event);
+                }
+
+                return function;
+            }
+        }
+
+        return null;
+    }
+
+    public String escapeJavaScript(Object o) {
+        if (o != null) {
+            StringBuilder result = new StringBuilder();
+            JSEncoder encoder = new JSEncoder();
+            char[] chars = o.toString().toCharArray();
             int start = 0;
             int end = chars.length;
-			for (int x = start; x < end; x++) {
+
+            for (int x = start; x < end; x++) {
                 char c = chars[x];
-                
+
                 if (encoder.compile(c)) {
                     continue;
                 }
-                
+
                 if (start != x) {
-                	result.append(chars, start, x - start );
+                    result.append(chars, start, x - start);
                 }
-                
+
                 result.append(encoder.encode(c));
                 start = x + 1;
-                
+
                 continue;
             }
-			
+
             if (start != end) {
-            	result.append(chars, start, end - start);
+                result.append(chars, start, end - start);
             }
-			
+
             return result.toString();
-		} else {
-			return null;
-		}
-	}
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * Common HTML elements and attributes names.
+     *
+     * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
+     * @version $Revision: 1.1.2.6 $ $Date: 2007/02/08 19:07:16 $
+     *
+     */
+    public interface HTML {
+        public static final String ACCEPT_ATTRIBUTE = "accept";
+        public static final String ACCEPT_CHARSET_ATTRIBUTE = "accept-charset";
+        public static final String ACCESSKEY_ATTRIBUTE = "accesskey";
+        public static final String ACTION_ATTRIBUTE = "action";
+        public static final String ALIGN_ATTRIBUTE = "align";
+        public static final String ALT_ATTRIBUTE = "alt";
+        public static final String AUTOCOMPLETE_ATTRIBUTE = "autocomplete";
+        public static final String A_ELEMENT = "a";
+        public static final String BGCOLOR_ATTRIBUTE = "bgcolor";
+        public static final String BODY_ELEMENT = "body";
+        public static final String BORDER_ATTRIBUTE = "border";
+
+        // elements
+        public static final String BUTTON = "button";
+        public static final String CAPTION_ELEMENT = "caption";
+        public static final String CELLPADDING_ATTRIBUTE = "cellpadding";
+        public static final String CELLSPACING_ATTRIBUTE = "cellspacing";
+        public static final String CHARSET_ATTR = "charset";
+        public static final String CLASS_ATTRIBUTE = "class";
+        public static final String COLS_ATTRIBUTE = "cols";
+        public static final String COORDS_ATTR = "coords";
+        public static final String DIR_ATTRIBUTE = "dir";
+        public static final String DISABLED_ATTR = "disabled";
+        public static final String DIV_ELEM = "div";
+        public static final String DL_ELEMENT = "dl";
+        public static final String DT_ELEMENT = "dt";
+        public static final String ENCTYPE_ATTRIBUTE = "enctype";
+        public static final String FORM_ELEMENT = "form";
+        public static final String FRAME_ATTRIBUTE = "frame";
+        public static final String HEAD_ELEMENT = "head";
+        public static final String HEIGHT_ATTRIBUTE = "height";
+        public static final String HREFLANG_ATTR = "hreflang";
+        public static final String HREF_ATTR = "href";
+        public static final String HTML_ELEMENT = "html";
+
+        // attributes
+        public static final String ID_ATTRIBUTE = "id";
+        public static final String IMG_ELEMENT = "img";
+        public static final String INPUT_ELEM = "input";
+        public static final Object INPUT_TYPE_HIDDEN = "hidden";
+        public static final String LANG_ATTRIBUTE = "lang";
+        public static final String LINK_ELEMENT = "link";
+        public static final String LONGDESC_ATTRIBUTE = "longdesc";
+        public static final String MAXLENGTH_ATTRIBUTE = "maxlength";
+        public static final String MEDIA_ATTRIBUTE = "media";
+        public static final String METHOD_ATTRIBUTE = "method";
+        public static final String NAME_ATTRIBUTE = "name";
+        public static final String NOWRAP_ATTRIBUTE = "nowrap";
+        public static final String ONBLUR_ATTRIBUTE = "onblur";
+        public static final String ONCHANGE_ATTRIBUTE = "onchange";
+        public static final String ONCLICK_ATTRIBUTE = "onclick";
+        public static final String ONDBLCLICK_ATTRIBUTE = "ondblclick";
+        public static final String ONFOCUS_ATTRIBUTE = "onfocus";
+        public static final String ONKEYDOWN_ATTRIBUTE = "onkeydown";
+        public static final String ONKEYPRESS_ATTRIBUTE = "onkeypress";
+        public static final String ONKEYUP_ATTRIBUTE = "onkeyup";
+        public static final String ONLOAD_ATTRIBUTE = "onload";
+        public static final String ONMOUSEDOWN_ATTRIBUTE = "onmousedown";
+        public static final String ONMOUSEMOVE_ATTRIBUTE = "onmousemove";
+        public static final String ONMOUSEOUT_ATTRIBUTE = "onmouseout";
+        public static final String ONMOUSEOVER_ATTRIBUTE = "onmouseover";
+        public static final String ONMOUSEUP_ATTRIBUTE = "onmouseup";
+        public static final String ONRESET_ATTRIBUTE = "onreset";
+        public static final String ONSELECT_ATTRIBUTE = "onselect";
+        public static final String ONSUBMIT_ATTRIBUTE = "onsubmit";
+        public static final String ONUNLOAD_ATTRIBUTE = "onunload";
+
+        // public static final String ONRESET_ATTRIBUTE = "onreset";
+        // attributes sets.
+        public static final String[] PASS_THRU = {
+
+            // DIR_ATTRIBUTE,
+            // LANG_ATTRIBUTE,
+            // STYLE_ATTRIBUTE,
+            // TITLE_ATTRIBUTE
+            "accesskey", "alt", "cols", "height", "lang", "longdesc", "maxlength", "rows", "size", "tabindex", "title",
+            "width", "dir", "rules", "frame", "border", "cellspacing", "cellpadding", "summary", "bgcolor", "usemap",
+            "enctype", "accept-charset", "accept", "target", "charset", "coords", "hreflang", "rel", "rev", "shape",
+            "disabled", "readonly", "ismap", "align"
+        };
+
+        /**
+         * HTML attributes allowed boolean-values only
+         */
+        public static final String[] PASS_THRU_BOOLEAN = {
+            "disabled", "declare", "readonly", "compact", "ismap", "selected", "checked", "nowrap", "noresize",
+            "nohref", "noshade", "multiple"
+        };
+        public static final String[] PASS_THRU_EVENTS = {
+            "onblur", "onchange", "onclick", "ondblclick", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onload",
+            "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onreset", "onselect", "onsubmit",
+            "onunload"
+        };
+        public static final String[] PASS_THRU_STYLES = {"style", "class", };
+
+        /**
+         * all HTML attributes with URI value.
+         */
+        public static final String[] PASS_THRU_URI = {
+            "usemap", "background", "codebase", "cite", "data", "classid", "href", "longdesc", "profile", "src"
+        };
+        public static final String READONLY_ATTRIBUTE = "readonly";
+        public static final String REL_ATTR = "rel";
+        public static final String REV_ATTR = "rev";
+        public static final String ROWS_ATTRIBUTE = "rows";
+        public static final String RULES_ATTRIBUTE = "rules";
+        public static final String SCRIPT_ELEM = "script";
+        public static final String SHAPE_ATTR = "shape";
+        public static final String SIZE_ATTRIBUTE = "size";
+        public static final String SPAN_ELEM = "span";
+        public static final String SRC_ATTRIBUTE = "src";
+        public static final String STYLE_ATTRIBUTE = "style";
+        public static final String STYLE_CLASS_ATTR = "styleClass";
+        public static final String SUMMARY_ATTRIBUTE = "summary";
+        public static final String TABINDEX_ATTRIBUTE = "tabindex";
+        public static final String TABLE_ELEMENT = "table";
+        public static final String TARGET_ATTRIBUTE = "target";
+        public static final String TBOBY_ELEMENT = "tbody";
+        public static final String TD_ELEM = "td";
+        public static final String TEXT_JAVASCRIPT_TYPE = "text/javascript";
+        public static final String TFOOT_ELEMENT = "tfoot";
+        public static final String THEAD_ELEMENT = "thead";
+        public static final String TH_ELEM = "th";
+        public static final String TITLE_ATTRIBUTE = "title";
+        public static final String TITLE_ELEM = "title";
+        public static final String TR_ELEMENT = "tr";
+        public static final String TYPE_ATTR = "type";
+        public static final String USEMAP_ATTRIBUTE = "usemap";
+        public static final String VALIGN_ATTRIBUTE = "valign";
+        public static final String VALUE_ATTRIBUTE = "value";
+        public static final String WIDTH_ATTRIBUTE = "width";
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Classes and interface participating in component rendering process
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/MultipartRequest.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/MultipartRequest.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/MultipartRequest.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.request;
 
+import org.ajax4jsf.exception.FileUploadException;
+import org.ajax4jsf.webapp.BaseXMLFilter;
+
+import org.richfaces.component.FileUploadConstants;
+import org.richfaces.model.UploadItem;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -30,6 +38,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Enumeration;
@@ -44,947 +53,959 @@
 
 import javax.faces.context.ExternalContext;
 import javax.faces.context.FacesContext;
+
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletRequestWrapper;
 
-import org.ajax4jsf.exception.FileUploadException;
-import org.ajax4jsf.webapp.BaseXMLFilter;
-import org.richfaces.component.FileUploadConstants;
-import org.richfaces.model.UploadItem;
-
 /**
  * Request wrapper for supporting multipart requests, used for file uploading.
- * 
+ *
  * @author Shane Bryzak
  */
 public class MultipartRequest extends HttpServletRequestWrapper {
-	private static final String PARAM_NAME = "name";
-	private static final String PARAM_FILENAME = "filename";
-	private static final String PARAM_CONTENT_TYPE = "Content-Type";
+    private static final int BUFFER_SIZE = 2048;
+    private static final int CHUNK_SIZE = 512;
+    private static final byte CR = 0x0d;
+    private static final byte LF = 0x0a;
+    private static final String PARAM_CONTENT_TYPE = "Content-Type";
+    private static final String PARAM_FILENAME = "filename";
+    private static final String PARAM_NAME = "name";
+    private static final byte[] CR_LF = {CR, LF};
+    private static final Pattern PARAM_VALUE_PATTERN = Pattern.compile("^\\s*([^\\s=]+)\\s*[=:]\\s*(.+)\\s*$");
+    private static final Pattern FILE_NAME_PATTERN = Pattern.compile(".*filename=\"(.*)\"");
+    private int bytesRead = 0;
+    private Integer contentLength = 0;
+    private String encoding = null;
+    boolean initialized = false;
+    private Map<String, Param> parameters = null;
+    private Map<String, Object> percentMap = null;
+    private int pos = 0;
+    private int read = 0;
 
-	private static final int BUFFER_SIZE = 2048;
-	private static final int CHUNK_SIZE = 512;
+    // we shouldn't allow to stop until request reaches PhaseListener because of portlets
+    private boolean canStop = false;
+    private String requestKey = null;
+    private Map<String, String> requestKeysMap = null;
+    private Map<String, Integer> requestSizeMap = null;
+    private List<String> keys = new ArrayList<String>();
+    private boolean shouldStop = false;
+    private int zeroReadAttempts = 20; // 20 attempts to read not-readable data
+    private byte[] boundaryMarker;
+    private byte[] buffer;
+    private boolean canceled;
+    private boolean createTempFiles;
+    private InputStream input;
+    private ReadState readState;
+    private MultipartRequestRegistry requestRegistry;
+    private String uid;
 
-	private boolean createTempFiles;
+    private enum ReadState {BOUNDARY, HEADERS, DATA}
 
-	private String uid;
+    public MultipartRequest(HttpServletRequest request, boolean createTempFiles, int maxRequestSize, String uid) {
+        super(request);
+        this.createTempFiles = createTempFiles;
+        this.uid = uid;
 
-	private String encoding = null;
+        String contentLength = request.getHeader("Content-Length");
 
-	private Integer contentLength = 0;
+        this.contentLength = Integer.parseInt(contentLength);
 
-	private int bytesRead = 0;
-	
-	private int read = 0;
+        if ((contentLength != null) && (maxRequestSize > 0) && (this.contentLength > maxRequestSize)) {
 
-	//we shouldn't allow to stop until request reaches PhaseListener because of portlets
-	private boolean canStop = false;
-	
-	private Map<String, Param> parameters = null;
+            // TODO : we should make decision if can generate exception in this
+            // place
+            // throw new FileUploadException(
+            // "Multipart request is larger than allowed size");
+        }
+    }
 
-	private Map<String, Object> percentMap = null;
-	
-	private Map<String, Integer> requestSizeMap = null;
-	
-	private Map<String, String> requestKeysMap = null;
-	
-	private String requestKey = null;
-	
-	private MultipartRequestRegistry requestRegistry;
-	
-	private List<String> keys = new ArrayList<String>();
+    private String decodeFileName(String name) {
+        String fileName = null;
 
-	private enum ReadState {
-		BOUNDARY, HEADERS, DATA
-	}
+        try {
+            if (getRequest().getParameter("_richfaces_send_http_error") != null) {
+                fileName = new String(name.getBytes(encoding), "UTF-8");
+            } else {
+                StringBuffer buffer = new StringBuffer();
+                String[] codes = name.split(";");
 
-	private static final byte CR = 0x0d;
-	private static final byte LF = 0x0a;
-	private static final byte[] CR_LF = { CR, LF };
+                if (codes != null) {
+                    for (String code : codes) {
+                        if (code.startsWith("&")) {
+                            String sCode = code.replaceAll("[&#]*", "");
+                            Integer iCode = Integer.parseInt(sCode);
 
-	private abstract class Param {
-		private String name;
+                            buffer.append(Character.toChars(iCode));
+                        } else {
+                            buffer.append(code);
+                        }
+                    }
 
-		public Param(String name) {
-			this.name = name;
-		}
+                    fileName = buffer.toString();
+                }
+            }
+        } catch (Exception e) {
+            fileName = name;
+        }
 
-		public String getName() {
-			return name;
-		}
+        return fileName;
+    }
 
-		public abstract void appendData(byte[] data, int start, int length)
-				throws IOException;
+    public void cancel() {
+        this.canceled = true;
 
-	}
+        if (parameters != null) {
+            Iterator<Param> it = parameters.values().iterator();
 
-	private class ValueParam extends Param {
-		private Object value = null;
-		private ByteArrayOutputStream buf = new ByteArrayOutputStream();
+            while (it.hasNext()) {
+                Param p = it.next();
 
-		public ValueParam(String name) {
-			super(name);
-		}
+                if (p instanceof FileParam) {
+                    ((FileParam) p).deleteFile();
+                }
+            }
+        }
+    }
 
-		@Override
-		public void appendData(byte[] data, int start, int length)
-				throws IOException {
-			// read += length;
-			buf.write(data, start, length);
-		}
+    private void fillBuffer() throws IOException {
+        if (pos < read) {
 
-		public void complete() throws UnsupportedEncodingException {
-			String val = encoding == null ? new String(buf.toByteArray())
-					: new String(buf.toByteArray(), encoding);
-			if (value == null) {
-				value = val;
-			} else {
-				if (!(value instanceof List)) {
-					List<String> v = new ArrayList<String>();
-					v.add((String) value);
-					value = v;
-				}
+            // move the bytes that weren't read to the start of
+            // the
+            // buffer
+            int bytesNotRead = read - pos;
 
-				((List) value).add(val);
-			}
-			buf.reset();
-		}
+            if (bytesNotRead != buffer.length) {
+                System.arraycopy(buffer, pos, buffer, 0, bytesNotRead);
+                read = input.read(buffer, bytesNotRead, buffer.length - bytesNotRead);
 
-		public Object getValue() {
-			return value;
-		}
-	}
+                if ((read != 0) || (--zeroReadAttempts != 0)) {
+                    if (read > 0) {
+                        bytesRead += read;
+                    }
 
-	private class FileParam extends Param {
-		private String filename;
-		private String contentType;
-		private int fileSize;
+                    read += bytesNotRead;
+                } else {
 
-		private ByteArrayOutputStream bOut = null;
-		private FileOutputStream fOut = null;
-		private File tempFile = null;
+                    // read is already zero
+                    // read = 0;
+                }
+            } else {
+                read = bytesNotRead;
+            }
+        } else {
+            read = input.read(buffer);
 
-		public FileParam(String name) {
-			super(name);
-			keys.add(name);
-		}
+            if (read > 0) {
+                bytesRead += read;
+            }
+        }
 
-		public Object getFile() {
-			if (null != tempFile) {
-				if (fOut != null) {
-					try {
-						fOut.close();
-					} catch (IOException ex) {
-					}
-					fOut = null;
-				}
-				return tempFile;
-			} else if (null != bOut) {
-				return bOut.toByteArray();
-			}
-			return null;
-		}
+        fillProgressInfo();
+        pos = 0;
+    }
 
-		public String getFilename() {
-			return filename;
-		}
+    private void readNext() throws IOException {
+        Param p = readHeader();
 
-		public void setFilename(String filename) {
-			this.filename = filename;
-		}
+        readData(p);
+    }
 
-		public String getContentType() {
-			return contentType;
-		}
+    private void readData(Param p) throws IOException {
+        int localRead = this.read;
 
-		public void setContentType(String contentType) {
-			this.contentType = contentType;
-		}
+        while (localRead > 0) {
+            for (int i = this.pos; i < localRead; i++) {
 
-		public int getFileSize() {
-			return fileSize;
-		}
+                // If we've encountered another boundary...
+                if (checkSequence(buffer, i - boundaryMarker.length - CR_LF.length, CR_LF)
+                        && checkSequence(buffer, i, boundaryMarker)) {
 
-		public File createTempFile() {
-			try {
+                    // Write any data before the boundary (that
+                    // hasn't
+                    // already been written) to the param
+                    if (pos < i - boundaryMarker.length - CR_LF.length - 1) {
+                        p.appendData(buffer, pos, i - pos - boundaryMarker.length - CR_LF.length - 1);
+                    }
 
-				tempFile = File.createTempFile(UUID.randomUUID().toString(), ".upload");
-				// tempFile.deleteOnExit();
-				fOut = new FileOutputStream(tempFile);
-			} catch (IOException ex) {
-				throw new FileUploadException("Could not create temporary file");
-			}
-			return tempFile;
-		}
+                    if (p instanceof ValueParam) {
+                        ((ValueParam) p).complete();
+                    }
 
-		public void deleteFile() {
-			try {
-				if (fOut != null) {
-					fOut.close();
-					if (tempFile != null) {
-						tempFile.delete();
-					}
-				}
-			} catch (Exception e) {
-				throw new FileUploadException("Could not delete temporary file");
-			}
-		}
+                    if (checkSequence(buffer, i + CR_LF.length, CR_LF)) {
+                        i += CR_LF.length;
+                        pos = i + 1;
+                    } else {
+                        pos = i;
+                    }
 
-		@Override
-		public void appendData(byte[] data, int start, int length)
-				throws IOException {
-			// read += length;
-			if (fOut != null) {
-				fOut.write(data, start, length);
-				fOut.flush();
-			} else {
-				if (bOut == null)
-					bOut = new ByteArrayOutputStream();
-				bOut.write(data, start, length);
-			}
+                    readState = ReadState.HEADERS;
 
-			fileSize += length;
-		}
+                    break;
+                } else if (i > (pos + boundaryMarker.length + CHUNK_SIZE + CR_LF.length)) {
 
-		public byte[] getData() {
-			if (fOut != null) {
-				try {
-					fOut.close();
-				} catch (IOException ex) {
-				}
-				fOut = null;
-			}
+                    // Otherwise write whatever data we have to the param
+                    p.appendData(buffer, pos, CHUNK_SIZE);
+                    pos += CHUNK_SIZE;
+                }
+            }
 
-			if (bOut != null) {
-				return bOut.toByteArray();
-			} else if (tempFile != null) {
-				if (tempFile.exists()) {
-					try {
-						FileInputStream fIn = new FileInputStream(tempFile);
-						ByteArrayOutputStream bOut = new ByteArrayOutputStream();
-						byte[] buf = new byte[512];
-						int read = fIn.read(buf);
-						while (read != -1) {
-							bOut.write(buf, 0, read);
-							read = fIn.read(buf);
-						}
-						bOut.flush();
+            if (ReadState.DATA.equals(readState)) {
+                fillBuffer();
+                localRead = this.read;
+            } else {
+                break;
+            }
+        }
+    }
 
-						fIn.close();
-						tempFile.delete();
-						return bOut.toByteArray();
-					} catch (IOException ex) { /* too bad? */
-					}
-				}
-			}
+    private Param readHeader() throws IOException {
+        Param p = null;
+        Map<String, String> headers = new HashMap<String, String>();
+        int localRead = this.read;
+        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
 
-			return null;
-		}
+        while (localRead > 0) {
+            for (int i = this.pos; i < localRead; i++) {
+                if (checkSequence(buffer, i, CR_LF)) {
+                    baos.write(buffer, pos, i - pos - 1);
 
-		public InputStream getInputStream() {
-			if (fOut != null) {
-				try {
-					fOut.close();
-				} catch (IOException ex) {
-				}
-				fOut = null;
-			}
+                    String param = (encoding == null)
+                                   ? new String(baos.toByteArray()) : new String(baos.toByteArray(), encoding);
 
-			if (bOut != null) {
-				return new ByteArrayInputStream(bOut.toByteArray());
-			} else if (tempFile != null) {
-				try {
-					return new FileInputStream(tempFile) {
-						@Override
-						public void close() throws IOException {
-							super.close();
-							tempFile.delete();
-						}
-					};
-				} catch (FileNotFoundException ex) {
-				}
-			}
+                    parseParams(param, "; ", headers);
 
-			return null;
-		}
-	}
+                    if (checkSequence(buffer, i + CR_LF.length, CR_LF)) {
+                        readState = ReadState.DATA;
+                        i += CR_LF.length;
+                        pos = i + 1;
 
-	private boolean shouldStop = false;
-	private boolean canceled;
+                        String paramName = headers.get(PARAM_NAME);
 
-	public MultipartRequest(HttpServletRequest request,
-			boolean createTempFiles, int maxRequestSize, String uid) {
-		super(request);
-		this.createTempFiles = createTempFiles;
-		this.uid = uid;
+                        if (paramName != null) {
+                            if (headers.containsKey(PARAM_FILENAME)) {
+                                FileParam fp = new FileParam(paramName);
 
-		String contentLength = request.getHeader("Content-Length");
-		this.contentLength = Integer.parseInt(contentLength);
-		if (contentLength != null && maxRequestSize > 0
-				&& this.contentLength > maxRequestSize) {
-			// TODO : we should make decision if can generate exception in this
-			// place
-			// throw new FileUploadException(
-			// "Multipart request is larger than allowed size");
-		}
-	}
+                                if (createTempFiles) {
+                                    fp.createTempFile();
+                                }
 
-	private String decodeFileName(String name) {
-		String fileName = null;
+                                fp.setContentType(headers.get(PARAM_CONTENT_TYPE));
+                                fp.setFilename(decodeFileName(headers.get(PARAM_FILENAME)));
+                                p = fp;
+                            } else {
+                                if (parameters.containsKey(paramName)) {
+                                    p = parameters.get(paramName);
+                                } else {
+                                    p = new ValueParam(paramName);
+                                }
+                            }
 
-		try {
-			if (getRequest().getParameter("_richfaces_send_http_error") != null) {
-				fileName = new String(name.getBytes(encoding), "UTF-8");
-			} else {
-				StringBuffer buffer = new StringBuffer();
-				String[] codes = name.split(";");
-				if (codes != null) {
-					for (String code : codes) {
-						if (code.startsWith("&")) {
-							String sCode = code.replaceAll("[&#]*", "");
-							Integer iCode = Integer.parseInt(sCode);
-							buffer.append(Character.toChars(iCode));
-						} else {
-							buffer.append(code);
-						}
-					}
-					fileName = buffer.toString();
-				}
-			}
-		} catch (Exception e) {
-			fileName = name;
-		}
+                            if (!parameters.containsKey(paramName)) {
+                                parameters.put(paramName, p);
+                            }
+                        }
 
-		return fileName;
-	}
+                        headers.clear();
+                        baos.reset();
 
-	public void cancel() {
-		this.canceled = true;
-		
-		if (parameters != null) {
-			Iterator<Param> it = parameters.values().iterator();
-			while (it.hasNext()) {
-				Param p = it.next();
-				if (p instanceof FileParam) {
-					((FileParam) p).deleteFile();
-				}
-			}
-		}
-	}
+                        break;
+                    } else {
+                        pos = i + 1;
+                        baos.reset();
+                    }
+                }
+            }
 
-	private byte[] boundaryMarker;
-	
-	private byte[] buffer;
-	
-	private ReadState readState;
-	
-	private InputStream input;
-	
-	private int pos = 0;
+            if (ReadState.HEADERS.equals(readState)) {
+                baos.write(buffer, pos, read - pos);
+                pos = read;
+                fillBuffer();
+                localRead = this.read;
+            } else {
+                break;
+            }
+        }
 
-	private int zeroReadAttempts = 20; // 20 attempts to read not-readable data
-	
-	private void fillBuffer() throws IOException {
-		if (pos < read) {
-			// move the bytes that weren't read to the start of
-			// the
-			// buffer
-			int bytesNotRead = read - pos;
-			
-			if (bytesNotRead != buffer.length) {
-				System.arraycopy(buffer, pos, buffer, 0,
-						bytesNotRead);
-				read = input.read(buffer, bytesNotRead,
-						buffer.length - bytesNotRead);
-				
-				if (read != 0 || --zeroReadAttempts != 0) {
-					if (read > 0) {
-						bytesRead += read;
-					}
+        return p;
+    }
 
-					read += bytesNotRead;
-				} else {
-					//read is already zero
-					//read = 0;
-				}
-			} else {
-				read = bytesNotRead;
-			}
-		} else {
-			read = input.read(buffer);
+    private void initialize() throws IOException {
+        if (!initialized) {
+            initialized = true;
+            this.boundaryMarker = getBoundaryMarker(super.getContentType());
 
-			if (read > 0) {
-				bytesRead += read;
-			}
-		}
-		
-		fillProgressInfo();
-		pos = 0;
-	}
-	
-	private void readNext() throws IOException {
-		Param p = readHeader();
-		readData(p);
-	}
+            if (this.boundaryMarker == null) {
+                throw new FileUploadException("The request was rejected because " + "no multipart boundary was found");
+            }
 
-	private void readData(Param p) throws IOException {
-		int localRead = this.read;
-		
-		while (localRead > 0) {
-			for (int i = this.pos; i < localRead; i++) {
-				// If we've encountered another boundary...
-				if (checkSequence(buffer, i - boundaryMarker.length
-						- CR_LF.length, CR_LF)
-						&& checkSequence(buffer, i, boundaryMarker)) {
-					// Write any data before the boundary (that
-					// hasn't
-					// already been written) to the param
-					if (pos < i - boundaryMarker.length
-							- CR_LF.length - 1) {
-						p.appendData(buffer, pos, i - pos
-								- boundaryMarker.length
-								- CR_LF.length - 1);
-					}
+            this.encoding = getCharacterEncoding();
+            this.parameters = new HashMap<String, Param>();
+            this.buffer = new byte[BUFFER_SIZE];
+            this.readState = ReadState.BOUNDARY;
+            this.input = getInputStream();
+            setupProgressData();
+            fillBuffer();
 
-					if (p instanceof ValueParam)
-						((ValueParam) p).complete();
+            int localRead = this.read;
 
-					if (checkSequence(buffer, i + CR_LF.length,
-							CR_LF)) {
-						i += CR_LF.length;
-						pos = i + 1;
-					} else {
-						pos = i;
-					}
+            while (localRead > 0) {
+                for (int i = 0; i < localRead; i++) {
+                    if (checkSequence(buffer, i, boundaryMarker) && checkSequence(buffer, i + 2, CR_LF)) {
+                        readState = ReadState.HEADERS;
+                        i += 2;
+                        pos = i + 1;
 
-					readState = ReadState.HEADERS;
-					break;
-				}
-				// Otherwise write whatever data we have to the
-				// param
-				else if (i > (pos + boundaryMarker.length
-						+ CHUNK_SIZE + CR_LF.length)) {
-					p.appendData(buffer, pos, CHUNK_SIZE);
-					pos += CHUNK_SIZE;
+                        break;
+                    }
+                }
 
-				}
-			}
-			
-			if (ReadState.DATA.equals(readState)) {
-				fillBuffer();
-				localRead = this.read;
-			} else {
-				break;
-			}
-		}
-	}
+                if (ReadState.BOUNDARY.equals(readState)) {
+                    pos = read - (boundaryMarker.length + CR_LF.length) + 1;
+                    fillBuffer();
+                    localRead = this.read;
+                } else {
+                    break;
+                }
+            }
+        }
+    }
 
-	private Param readHeader() throws IOException {
-		Param p = null;
+    public void parseRequest() {
+        canStop = true;
+        setupProgressData();
 
-		Map<String, String> headers = new HashMap<String, String>();
+        try {
+            initialize();
 
-		int localRead = this.read;
-		
-		ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
-		
-		while (localRead > 0) {
-			for (int i = this.pos; i < localRead; i++) {
-				if (checkSequence(buffer, i, CR_LF)) {
-					baos.write(buffer, pos, i - pos - 1);
+            while (read > 0) {
+                readNext();
+            }
+        } catch (IOException e) {
+            this.cancel();
 
-					String param = (encoding == null) ? 
-							new String(baos.toByteArray()) : 
-							new String(baos.toByteArray(), encoding);
+            if (!this.shouldStop) {
+                throw new FileUploadException("IO Error parsing multipart request", e);
+            }
+        }
+    }
 
-					parseParams(param, "; ", headers);
+    public static MultipartRequest lookupRequest(FacesContext context, String uploadId) {
+        Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
+        Map<String, String> requestKeys = (Map<String,
+                                              String>) sessionMap.get(FileUploadConstants.REQUEST_KEYS_BEAN_NAME);
 
-					if (checkSequence(buffer, i + CR_LF.length,
-							CR_LF)) {
-						readState = ReadState.DATA;
-						i += CR_LF.length;
-						pos = i + 1;
+        if (requestKeys != null) {
+            String requestKey = requestKeys.get(uploadId);
 
-						String paramName = headers.get(PARAM_NAME);
-						if (paramName != null) {
-							if (headers.containsKey(PARAM_FILENAME)) {
-								FileParam fp = new FileParam(
-										paramName);
-								if (createTempFiles)
-									fp.createTempFile();
-								fp.setContentType(headers
-										.get(PARAM_CONTENT_TYPE));
-								fp
-										.setFilename(decodeFileName(headers
-												.get(PARAM_FILENAME)));
-								p = fp;
-							} else {
-								if (parameters
-										.containsKey(paramName)) {
-									p = parameters.get(paramName);
-								} else {
-									p = new ValueParam(paramName);
-								}
-							}
+            if (requestKey != null) {
+                MultipartRequestRegistry requestRegistry = MultipartRequestRegistry.getInstance(context);
 
-							if (!parameters.containsKey(paramName)) {
-								parameters.put(paramName, p);
-							}
-						}
+                if (requestRegistry != null) {
+                    MultipartRequest request = requestRegistry.getRequest(requestKey);
 
-						headers.clear();
-						baos.reset();
-						
-						break;
-					} else {
-						pos = i + 1;
-						baos.reset();
-					}
-				}
-			}
-			
-			if (ReadState.HEADERS.equals(readState)) {
-				baos.write(buffer, pos, read - pos);
-				pos = read;
-				fillBuffer();
-				localRead = this.read;
-			} else {
-				break;
-			}
-		}
-		return p;
-	}
+                    if (request != null) {
+                        return request;
+                    }
+                }
+            }
+        }
 
-	boolean initialized = false;
-	
-	private void initialize() throws IOException {
-		if (!initialized) {
-			initialized = true;
+        return null;
+    }
 
-			this.boundaryMarker = getBoundaryMarker(super.getContentType());
-			if (this.boundaryMarker == null) {
-				throw new FileUploadException("The request was rejected because "
-						+ "no multipart boundary was found");
-			}
+    @SuppressWarnings("unchecked")
+    private void setupProgressData() {
+        if ((percentMap == null) || (requestSizeMap == null) || (requestKeysMap == null)) {
+            FacesContext facesContext = FacesContext.getCurrentInstance();
 
-			this.encoding = getCharacterEncoding();
+            if (facesContext != null) {
+                ExternalContext externalContext = facesContext.getExternalContext();
 
-			this.parameters = new HashMap<String, Param>();
+                if (externalContext != null) {
+                    Map<String, Object> sessionMap = externalContext.getSessionMap();
 
-			this.buffer = new byte[BUFFER_SIZE];
+                    if (sessionMap != null) {
+                        String uploadId = getUploadId();
 
-			this.readState = ReadState.BOUNDARY;
+                        synchronized (sessionMap) {
+                            if (percentMap == null) {
+                                percentMap = (Map<String,
+                                                  Object>) sessionMap.get(FileUploadConstants.PERCENT_BEAN_NAME);
 
-			this.input = getInputStream();
-			
-			setupProgressData();
-			
-			fillBuffer();
-			int localRead = this.read;
-			
-			while (localRead > 0) {
-				for (int i = 0; i < localRead; i++) {
-					if (checkSequence(buffer, i, boundaryMarker)
-							&& checkSequence(buffer, i + 2, CR_LF)) {
-						readState = ReadState.HEADERS;
-						i += 2;
-						pos = i + 1;
-						
-						break;
-					}
-				}
-				
-				if (ReadState.BOUNDARY.equals(readState)) {
-					pos = read - (boundaryMarker.length + CR_LF.length) + 1;
-					fillBuffer();
-					localRead = this.read;
-				} else {
-					break;
-				}
-			}
-			
-		}
-	}
-	
-	public void parseRequest() {
-		canStop = true;
-		
-		setupProgressData();
-		
-		try {
-			initialize();
-			
-			while (read > 0) {
-				readNext();
-			}
-			
-		} catch (IOException e) {
-			this.cancel();
-			
-			if (!this.shouldStop) {
-				throw new FileUploadException("IO Error parsing multipart request", e);
-			}
-		}
-	}
-	
-	public static MultipartRequest lookupRequest(FacesContext context, String uploadId) {
-		Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
-		Map<String, String> requestKeys = (Map<String, String>) sessionMap.get(FileUploadConstants.REQUEST_KEYS_BEAN_NAME);
-		if (requestKeys != null) {
-			String requestKey = requestKeys.get(uploadId);
-			if (requestKey != null) {
-				MultipartRequestRegistry requestRegistry = MultipartRequestRegistry.getInstance(context);
-				if (requestRegistry != null) {
-					MultipartRequest request = requestRegistry.getRequest(requestKey);
-					if (request != null) {
-						return request;
-					}
-				}
-			}
-		}
-		
-		return null;
-	}
-	
-	@SuppressWarnings("unchecked")
-	private void setupProgressData() {
-		if (percentMap == null || requestSizeMap == null || requestKeysMap == null) {
-			FacesContext facesContext = FacesContext.getCurrentInstance();
-			if (facesContext != null) {
-				ExternalContext externalContext = facesContext.getExternalContext();
-				if (externalContext != null) {
-					Map<String, Object> sessionMap = externalContext.getSessionMap();
-					if (sessionMap != null) {
-						String uploadId = getUploadId();
+                                if (percentMap == null) {
+                                    percentMap = new ConcurrentHashMap<String, Object>();
+                                    sessionMap.put(FileUploadConstants.PERCENT_BEAN_NAME, percentMap);
+                                }
+                            }
 
-						synchronized (sessionMap) {
-							if (percentMap == null) {
-								percentMap = (Map<String, Object>) sessionMap.get(FileUploadConstants.PERCENT_BEAN_NAME);
-								if (percentMap == null) {
-									percentMap = new ConcurrentHashMap<String, Object>();
-									sessionMap.put(FileUploadConstants.PERCENT_BEAN_NAME, percentMap);
-								}
-							}
+                            if (requestSizeMap == null) {
+                                requestSizeMap =
+                                    (Map<String, Integer>) sessionMap.get(FileUploadConstants.REQUEST_SIZE_BEAN_NAME);
 
-							if (requestSizeMap == null) {
-								requestSizeMap = (Map<String, Integer>) sessionMap.get(FileUploadConstants.REQUEST_SIZE_BEAN_NAME);
-								if (requestSizeMap == null) {
-									requestSizeMap = new ConcurrentHashMap<String, Integer>();
-									sessionMap.put(FileUploadConstants.REQUEST_SIZE_BEAN_NAME, requestSizeMap);
-								}
-							}
-							
-							if (requestKeysMap == null) {
-								requestKeysMap = (Map<String, String>) sessionMap.get(FileUploadConstants.REQUEST_KEYS_BEAN_NAME);
-								if (requestKeysMap == null) {
-									requestKeysMap = new ConcurrentHashMap<String, String>();
-									sessionMap.put(FileUploadConstants.REQUEST_KEYS_BEAN_NAME, requestKeysMap);
-								}
-								
-							}
-						}
-						
-						percentMap.put(uploadId, Double.valueOf(0));
+                                if (requestSizeMap == null) {
+                                    requestSizeMap = new ConcurrentHashMap<String, Integer>();
+                                    sessionMap.put(FileUploadConstants.REQUEST_SIZE_BEAN_NAME, requestSizeMap);
+                                }
+                            }
 
-						requestSizeMap.put(uploadId, getSize());
+                            if (requestKeysMap == null) {
+                                requestKeysMap =
+                                    (Map<String, String>) sessionMap.get(FileUploadConstants.REQUEST_KEYS_BEAN_NAME);
 
-						requestRegistry = MultipartRequestRegistry.getInstance(facesContext);
-						requestKey = requestRegistry.registerRequest(this);
-						requestKeysMap.put(uploadId, requestKey);
+                                if (requestKeysMap == null) {
+                                    requestKeysMap = new ConcurrentHashMap<String, String>();
+                                    sessionMap.put(FileUploadConstants.REQUEST_KEYS_BEAN_NAME, requestKeysMap);
+                                }
+                            }
+                        }
 
-					}
-				}
-			}
-		}
-	}
+                        percentMap.put(uploadId, Double.valueOf(0));
+                        requestSizeMap.put(uploadId, getSize());
+                        requestRegistry = MultipartRequestRegistry.getInstance(facesContext);
+                        requestKey = requestRegistry.registerRequest(this);
+                        requestKeysMap.put(uploadId, requestKey);
+                    }
+                }
+            }
+        }
+    }
 
-	private void fillProgressInfo() {
-		setupProgressData();
-		
-		if (percentMap != null) {
-			Double percent = (Double) (100.0 * this.bytesRead / this.contentLength);
-			percentMap.put(uid, percent);
-			// this.percent = percent;
-		}
-	}
+    private void fillProgressInfo() {
+        setupProgressData();
 
-	private byte[] getBoundaryMarker(String contentType) {
-		Map<String, String> params = parseParams(contentType, ";");
-		String boundaryStr = (String) params.get("boundary");
+        if (percentMap != null) {
+            Double percent = (Double) (100.0 * this.bytesRead / this.contentLength);
 
-		if (boundaryStr == null)
-			return null;
+            percentMap.put(uid, percent);
 
-		try {
-			return boundaryStr.getBytes("ISO-8859-1");
-		} catch (UnsupportedEncodingException e) {
-			return boundaryStr.getBytes();
-		}
-	}
+            // this.percent = percent;
+        }
+    }
 
-	/**
-	 * Checks if a specified sequence of bytes ends at a specific position
-	 * within a byte array.
-	 * 
-	 * @param data
-	 * @param pos
-	 * @param seq
-	 * @return boolean indicating if the sequence was found at the specified
-	 *         position
-	 */
-	private boolean checkSequence(byte[] data, int pos, byte[] seq) {
-		if (pos - seq.length < -1 || pos >= data.length)
-			return false;
+    private byte[] getBoundaryMarker(String contentType) {
+        Map<String, String> params = parseParams(contentType, ";");
+        String boundaryStr = (String) params.get("boundary");
 
-		for (int i = 0; i < seq.length; i++) {
-			if (data[(pos - seq.length) + i + 1] != seq[i])
-				return false;
-		}
+        if (boundaryStr == null) {
+            return null;
+        }
 
-		return true;
-	}
+        try {
+            return boundaryStr.getBytes("ISO-8859-1");
+        } catch (UnsupportedEncodingException e) {
+            return boundaryStr.getBytes();
+        }
+    }
 
-	private static final Pattern PARAM_VALUE_PATTERN = Pattern
-			.compile("^\\s*([^\\s=]+)\\s*[=:]\\s*(.+)\\s*$");
+    /**
+     * Checks if a specified sequence of bytes ends at a specific position
+     * within a byte array.
+     *
+     * @param data
+     * @param pos
+     * @param seq
+     * @return boolean indicating if the sequence was found at the specified
+     *         position
+     */
+    private boolean checkSequence(byte[] data, int pos, byte[] seq) {
+        if ((pos - seq.length < -1) || (pos >= data.length)) {
+            return false;
+        }
 
-	private static final Pattern FILE_NAME_PATTERN = Pattern
-			.compile(".*filename=\"(.*)\"");
+        for (int i = 0; i < seq.length; i++) {
+            if (data[(pos - seq.length) + i + 1] != seq[i]) {
+                return false;
+            }
+        }
 
-	private Map<String, String> parseParams(String paramStr, String separator) {
-		Map<String, String> paramMap = new HashMap<String, String>();
-		parseParams(paramStr, separator, paramMap);
-		return paramMap;
-	}
+        return true;
+    }
 
-	private void parseParams(String paramStr, String separator,
-			Map<String, String> paramMap) {
-		String[] parts = paramStr.split(separator);
+    private Map<String, String> parseParams(String paramStr, String separator) {
+        Map<String, String> paramMap = new HashMap<String, String>();
 
-		for (String part : parts) {
-			Matcher m = PARAM_VALUE_PATTERN.matcher(part);
-			if (m.matches()) {
-				String key = m.group(1);
-				String value = m.group(2);
+        parseParams(paramStr, separator, paramMap);
 
-				// Strip double quotes
-				if (value.startsWith("\"") && value.endsWith("\""))
-					value = value.substring(1, value.length() - 1);
-				if (!"filename".equals(key)) {
-					paramMap.put(key, value);
-				} else {
-					paramMap.put(key, parseFileName(paramStr));
-				}
-			}
-		}
-	}
+        return paramMap;
+    }
 
-	private String parseFileName(String parseStr) {
-		Matcher m = FILE_NAME_PATTERN.matcher(parseStr);
-		if (m.matches()) {
-			String name = m.group(1);
-			if (name.startsWith("&")) {
-				return decodeFileName(name);
-			} else {
-				return name;
-			}
-		}
-		return null;
-	}
+    private void parseParams(String paramStr, String separator, Map<String, String> paramMap) {
+        String[] parts = paramStr.split(separator);
 
-	private Param getParam(String name) {
-		Param param = null;
-		if (parameters != null) {
-			param = parameters.get(name);
-		}
-		
-		if (param == null) {
-			if (!canceled) {
-				try {
-					initialize();
+        for (String part : parts) {
+            Matcher m = PARAM_VALUE_PATTERN.matcher(part);
 
-					while (param == null && read > 0) {
-						readNext();
-						param = parameters.get(name);
-					}
-				} catch (IOException e) {
-					this.cancel();
-					throw new FileUploadException("IO Error parsing multipart request", e);
-				}
-			}
-		}
-		
-		return param;
-	}
+            if (m.matches()) {
+                String key = m.group(1);
+                String value = m.group(2);
 
-	public Integer getSize() {
-		return contentLength;
-	}
+                // Strip double quotes
+                if (value.startsWith("\"") && value.endsWith("\"")) {
+                    value = value.substring(1, value.length() - 1);
+                }
 
-	@Override
-	public Enumeration getParameterNames() {
-		if (parameters == null)
-			parseRequest();
+                if (!"filename".equals(key)) {
+                    paramMap.put(key, value);
+                } else {
+                    paramMap.put(key, parseFileName(paramStr));
+                }
+            }
+        }
+    }
 
-		return Collections.enumeration(parameters.keySet());
-	}
+    private String parseFileName(String parseStr) {
+        Matcher m = FILE_NAME_PATTERN.matcher(parseStr);
 
-	public byte[] getFileBytes(String name) {
-		Param p = getParam(name);
-		return (p != null && p instanceof FileParam) ? ((FileParam) p)
-				.getData() : null;
-	}
+        if (m.matches()) {
+            String name = m.group(1);
 
-	public InputStream getFileInputStream(String name) {
-		Param p = getParam(name);
-		return (p != null && p instanceof FileParam) ? ((FileParam) p)
-				.getInputStream() : null;
-	}
+            if (name.startsWith("&")) {
+                return decodeFileName(name);
+            } else {
+                return name;
+            }
+        }
 
-	public String getFileContentType(String name) {
-		Param p = getParam(name);
-		return (p != null && p instanceof FileParam) ? ((FileParam) p)
-				.getContentType() : null;
-	}
+        return null;
+    }
 
-	public Object getFile(String name) {
-		Param p = getParam(name);
-		return (p != null && p instanceof FileParam) ? ((FileParam) p)
-				.getFile() : null;
-	}
+    private Param getParam(String name) {
+        Param param = null;
 
-	public String getFileName(String name) {
-		Param p = getParam(name);
-		return (p != null && p instanceof FileParam) ? ((FileParam) p)
-				.getFilename() : null;
-	}
+        if (parameters != null) {
+            param = parameters.get(name);
+        }
 
-	public int getFileSize(String name) {
-		Param p = getParam(name);
-		return (p != null && p instanceof FileParam) ? ((FileParam) p)
-				.getFileSize() : -1;
-	}
+        if (param == null) {
+            if (!canceled) {
+                try {
+                    initialize();
 
-	@Override
-	public String getParameter(String name) {
-		Param p = getParam(name);
-		if (p != null && p instanceof ValueParam) {
-			ValueParam vp = (ValueParam) p;
-			if (vp.getValue() instanceof String)
-				return (String) vp.getValue();
-		} else if (p != null && p instanceof FileParam) {
-			return "---BINARY DATA---";
-		} else {
-			return super.getParameter(name);
-		}
+                    while ((param == null) && (read > 0)) {
+                        readNext();
+                        param = parameters.get(name);
+                    }
+                } catch (IOException e) {
+                    this.cancel();
 
-		return null;
-	}
+                    throw new FileUploadException("IO Error parsing multipart request", e);
+                }
+            }
+        }
 
-	@Override
-	public String[] getParameterValues(String name) {
-		parseRequest();
-		
-		Param p = getParam(name);
-		if (p != null && p instanceof ValueParam) {
-			ValueParam vp = (ValueParam) p;
-			if (vp.getValue() instanceof List) {
-				List vals = (List) vp.getValue();
-				String[] values = new String[vals.size()];
-				vals.toArray(values);
-				return values;
-			} else {
-				return new String[] { (String) vp.getValue() };
-			}
-		} else {
-			return super.getParameterValues(name);
-		}
-	}
+        return param;
+    }
 
-	@Override
-	public Map getParameterMap() {
-		if (parameters == null)
-			parseRequest();
+    public Integer getSize() {
+        return contentLength;
+    }
 
-		Map<String, Object> params = new HashMap<String, Object>(super
-				.getParameterMap());
+    @Override
+    public Enumeration getParameterNames() {
+        if (parameters == null) {
+            parseRequest();
+        }
 
-		for (String name : parameters.keySet()) {
-			Param p = parameters.get(name);
-			if (p instanceof ValueParam) {
-				ValueParam vp = (ValueParam) p;
-				if (vp.getValue() instanceof String) {
-					params.put(name, vp.getValue());
-				} else if (vp.getValue() instanceof List) {
-					params.put(name, getParameterValues(name));
-				}
-			}
-		}
+        return Collections.enumeration(parameters.keySet());
+    }
 
-		return params;
-	}
-	
-	public List<UploadItem> getUploadItems () {
-		List <UploadItem> uploadItems = new ArrayList<UploadItem>();
-		for (String k : keys) {
-			uploadItems.add(new UploadItem(getFileName(k), getFileSize(k), getFileContentType(k), getFile(k)));
-		}
-		return uploadItems;
-	}
-	
-	public boolean isFormUpload() {
-		return "_richfaces_form_upload".equals(uid);
-	}
-	
-	@Override
-	public String getHeader(String name) {
-		if (!"Accept".equals(name)) {
-			return super.getHeader(name);
-		}else {
-			return BaseXMLFilter.TEXT_HTML;
-		}
-	}
+    public byte[] getFileBytes(String name) {
+        Param p = getParam(name);
 
-	public void stop() {
-		if (canStop) {
-			shouldStop = true;
-		}
-	}
-	
-	public boolean isStopped() {
-		return this.shouldStop;
-	}
-	
-	public boolean isDone() {
-		return !(this.shouldStop && (this.canceled || 
-				this.contentLength != null && this.contentLength.intValue() != this.bytesRead));
-	}
-	
-	@Override
-	public String getContentType() {
-		return "application/x-www-form-urlencoded";
-	}
+        return ((p != null) && (p instanceof FileParam)) ? ((FileParam) p).getData() : null;
+    }
 
-	protected String getUploadId() {
-		return uid;
-	}
-	
-	public void clearRequestData() {
-		String uploadId = getUploadId();
-		
-		if (percentMap != null) {
-			percentMap.remove(uploadId);
-		}
-		
-		if (requestSizeMap != null) {
-			requestSizeMap.remove(uploadId);
-		}
-		
-		if (requestKeysMap != null) {
-			requestKeysMap.remove(uploadId);
-		}
+    public InputStream getFileInputStream(String name) {
+        Param p = getParam(name);
 
-		if (requestRegistry != null) {
-			requestRegistry.removeRequest(requestKey);
-		}
-	}
+        return ((p != null) && (p instanceof FileParam)) ? ((FileParam) p).getInputStream() : null;
+    }
+
+    public String getFileContentType(String name) {
+        Param p = getParam(name);
+
+        return ((p != null) && (p instanceof FileParam)) ? ((FileParam) p).getContentType() : null;
+    }
+
+    public Object getFile(String name) {
+        Param p = getParam(name);
+
+        return ((p != null) && (p instanceof FileParam)) ? ((FileParam) p).getFile() : null;
+    }
+
+    public String getFileName(String name) {
+        Param p = getParam(name);
+
+        return ((p != null) && (p instanceof FileParam)) ? ((FileParam) p).getFilename() : null;
+    }
+
+    public int getFileSize(String name) {
+        Param p = getParam(name);
+
+        return ((p != null) && (p instanceof FileParam)) ? ((FileParam) p).getFileSize() : -1;
+    }
+
+    @Override
+    public String getParameter(String name) {
+        Param p = getParam(name);
+
+        if ((p != null) && (p instanceof ValueParam)) {
+            ValueParam vp = (ValueParam) p;
+
+            if (vp.getValue() instanceof String) {
+                return (String) vp.getValue();
+            }
+        } else if ((p != null) && (p instanceof FileParam)) {
+            return "---BINARY DATA---";
+        } else {
+            return super.getParameter(name);
+        }
+
+        return null;
+    }
+
+    @Override
+    public String[] getParameterValues(String name) {
+        parseRequest();
+
+        Param p = getParam(name);
+
+        if ((p != null) && (p instanceof ValueParam)) {
+            ValueParam vp = (ValueParam) p;
+
+            if (vp.getValue() instanceof List) {
+                List vals = (List) vp.getValue();
+                String[] values = new String[vals.size()];
+
+                vals.toArray(values);
+
+                return values;
+            } else {
+                return new String[] {(String) vp.getValue()};
+            }
+        } else {
+            return super.getParameterValues(name);
+        }
+    }
+
+    @Override
+    public Map getParameterMap() {
+        if (parameters == null) {
+            parseRequest();
+        }
+
+        Map<String, Object> params = new HashMap<String, Object>(super.getParameterMap());
+
+        for (String name : parameters.keySet()) {
+            Param p = parameters.get(name);
+
+            if (p instanceof ValueParam) {
+                ValueParam vp = (ValueParam) p;
+
+                if (vp.getValue() instanceof String) {
+                    params.put(name, vp.getValue());
+                } else if (vp.getValue() instanceof List) {
+                    params.put(name, getParameterValues(name));
+                }
+            }
+        }
+
+        return params;
+    }
+
+    public List<UploadItem> getUploadItems() {
+        List<UploadItem> uploadItems = new ArrayList<UploadItem>();
+
+        for (String k : keys) {
+            uploadItems.add(new UploadItem(getFileName(k), getFileSize(k), getFileContentType(k), getFile(k)));
+        }
+
+        return uploadItems;
+    }
+
+    public boolean isFormUpload() {
+        return "_richfaces_form_upload".equals(uid);
+    }
+
+    @Override
+    public String getHeader(String name) {
+        if (!"Accept".equals(name)) {
+            return super.getHeader(name);
+        } else {
+            return BaseXMLFilter.TEXT_HTML;
+        }
+    }
+
+    public void stop() {
+        if (canStop) {
+            shouldStop = true;
+        }
+    }
+
+    public boolean isStopped() {
+        return this.shouldStop;
+    }
+
+    public boolean isDone() {
+        return !(this.shouldStop
+                 && (this.canceled
+                     || ((this.contentLength != null) && (this.contentLength.intValue() != this.bytesRead))));
+    }
+
+    @Override
+    public String getContentType() {
+        return "application/x-www-form-urlencoded";
+    }
+
+    protected String getUploadId() {
+        return uid;
+    }
+
+    public void clearRequestData() {
+        String uploadId = getUploadId();
+
+        if (percentMap != null) {
+            percentMap.remove(uploadId);
+        }
+
+        if (requestSizeMap != null) {
+            requestSizeMap.remove(uploadId);
+        }
+
+        if (requestKeysMap != null) {
+            requestKeysMap.remove(uploadId);
+        }
+
+        if (requestRegistry != null) {
+            requestRegistry.removeRequest(requestKey);
+        }
+    }
+
+    private class FileParam extends Param {
+        private ByteArrayOutputStream bOut = null;
+        private FileOutputStream fOut = null;
+        private File tempFile = null;
+        private String contentType;
+        private int fileSize;
+        private String filename;
+
+        public FileParam(String name) {
+            super(name);
+            keys.add(name);
+        }
+
+        public Object getFile() {
+            if (null != tempFile) {
+                if (fOut != null) {
+                    try {
+                        fOut.close();
+                    } catch (IOException ex) {
+
+                        // TODO Refactoring
+                    }
+
+                    fOut = null;
+                }
+
+                return tempFile;
+            } else if (null != bOut) {
+                return bOut.toByteArray();
+            }
+
+            return null;
+        }
+
+        public String getFilename() {
+            return filename;
+        }
+
+        public void setFilename(String filename) {
+            this.filename = filename;
+        }
+
+        public String getContentType() {
+            return contentType;
+        }
+
+        public void setContentType(String contentType) {
+            this.contentType = contentType;
+        }
+
+        public int getFileSize() {
+            return fileSize;
+        }
+
+        public File createTempFile() {
+            try {
+                tempFile = File.createTempFile(UUID.randomUUID().toString(), ".upload");
+
+                // tempFile.deleteOnExit();
+                fOut = new FileOutputStream(tempFile);
+            } catch (IOException ex) {
+                throw new FileUploadException("Could not create temporary file");
+            }
+
+            return tempFile;
+        }
+
+        public void deleteFile() {
+            try {
+                if (fOut != null) {
+                    fOut.close();
+
+                    if (tempFile != null) {
+                        tempFile.delete();
+                    }
+                }
+            } catch (Exception e) {
+                throw new FileUploadException("Could not delete temporary file");
+            }
+        }
+
+        @Override
+        public void appendData(byte[] data, int start, int length) throws IOException {
+
+            // read += length;
+            if (fOut != null) {
+                fOut.write(data, start, length);
+                fOut.flush();
+            } else {
+                if (bOut == null) {
+                    bOut = new ByteArrayOutputStream();
+                }
+
+                bOut.write(data, start, length);
+            }
+
+            fileSize += length;
+        }
+
+        public byte[] getData() {
+            if (fOut != null) {
+                try {
+                    fOut.close();
+                } catch (IOException ex) {
+
+                    // TODO Refactoring
+                }
+
+                fOut = null;
+            }
+
+            if (bOut != null) {
+                return bOut.toByteArray();
+            } else if (tempFile != null) {
+                if (tempFile.exists()) {
+                    try {
+                        FileInputStream fIn = new FileInputStream(tempFile);
+                        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
+                        byte[] buf = new byte[512];
+                        int read = fIn.read(buf);
+
+                        while (read != -1) {
+                            bOut.write(buf, 0, read);
+                            read = fIn.read(buf);
+                        }
+
+                        bOut.flush();
+                        fIn.close();
+                        tempFile.delete();
+
+                        return bOut.toByteArray();
+                    } catch (IOException ex) { /* too bad? */
+                    }
+                }
+            }
+
+            return null;
+        }
+
+        public InputStream getInputStream() {
+            if (fOut != null) {
+                try {
+                    fOut.close();
+                } catch (IOException ex) {
+
+                    // TODO Refactoring
+                }
+
+                fOut = null;
+            }
+
+            if (bOut != null) {
+                return new ByteArrayInputStream(bOut.toByteArray());
+            } else if (tempFile != null) {
+                try {
+                    return new FileInputStream(tempFile) {
+                        @Override
+                        public void close() throws IOException {
+                            super.close();
+                            tempFile.delete();
+                        }
+                    };
+                } catch (FileNotFoundException ex) {
+
+                    // TODO Refactoring
+                }
+            }
+
+            return null;
+        }
+    }
+
+
+    private abstract class Param {
+        private String name;
+
+        public Param(String name) {
+            this.name = name;
+        }
+
+        public String getName() {
+            return name;
+        }
+
+        public abstract void appendData(byte[] data, int start, int length) throws IOException;
+    }
+
+
+    private class ValueParam extends Param {
+        private Object value = null;
+        private ByteArrayOutputStream buf = new ByteArrayOutputStream();
+
+        public ValueParam(String name) {
+            super(name);
+        }
+
+        @Override
+        public void appendData(byte[] data, int start, int length) throws IOException {
+
+            // read += length;
+            buf.write(data, start, length);
+        }
+
+        public void complete() throws UnsupportedEncodingException {
+            String val = (encoding == null) ? new String(buf.toByteArray()) : new String(buf.toByteArray(), encoding);
+
+            if (value == null) {
+                value = val;
+            } else {
+                if (!(value instanceof List)) {
+                    List<String> v = new ArrayList<String>();
+
+                    v.add((String) value);
+                    value = v;
+                }
+
+                ((List) value).add(val);
+            }
+
+            buf.reset();
+        }
+
+        public Object getValue() {
+            return value;
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/MultipartRequestRegistry.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/MultipartRequestRegistry.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/MultipartRequestRegistry.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.request;
 
 import java.util.Map;
@@ -32,49 +34,46 @@
  * @author Nick Belaevski
  * @since 3.3.1
  */
+final class MultipartRequestRegistry {
+    private static final String REGISTRY_ATTRIBUTE_NAME = MultipartRequestRegistry.class.getName();
+    private AtomicInteger atomicInteger = new AtomicInteger(0);
+    private String registryId = UUID.randomUUID().toString();
+    private Map<String, MultipartRequest> requestsMap = new ConcurrentHashMap<String, MultipartRequest>();
 
-class MultipartRequestRegistry {
+    private MultipartRequestRegistry() {}
 
-	private AtomicInteger atomicInteger = new AtomicInteger(0);
-	
-	private String registryId = UUID.randomUUID().toString();
-	
-	private Map<String, MultipartRequest> requestsMap = new ConcurrentHashMap<String, MultipartRequest>();
-	
-	private static final String REGISTRY_ATTRIBUTE_NAME = MultipartRequestRegistry.class.getName();
-	
-	private MultipartRequestRegistry() {
-		
-	}
-	
-	public static MultipartRequestRegistry getInstance(FacesContext context) {
-		Map<String, Object> applicationMap = context.getExternalContext().getApplicationMap();
-		MultipartRequestRegistry requestRegistry = (MultipartRequestRegistry) applicationMap.get(REGISTRY_ATTRIBUTE_NAME);
-		if (requestRegistry == null) {
-			synchronized (applicationMap) {
-				requestRegistry = (MultipartRequestRegistry) applicationMap.get(REGISTRY_ATTRIBUTE_NAME);
-				if (requestRegistry == null) {
-					requestRegistry = new MultipartRequestRegistry();
-					applicationMap.put(REGISTRY_ATTRIBUTE_NAME, requestRegistry);
-				}
-			}
-		}
-		
-		return requestRegistry;
-	}
-	
-	public String registerRequest(MultipartRequest request) {
-		String key = registryId + ":" + atomicInteger.incrementAndGet();
-		requestsMap.put(key, request);
+    public static MultipartRequestRegistry getInstance(FacesContext context) {
+        Map<String, Object> applicationMap = context.getExternalContext().getApplicationMap();
+        MultipartRequestRegistry requestRegistry =
+            (MultipartRequestRegistry) applicationMap.get(REGISTRY_ATTRIBUTE_NAME);
 
-		return key;
-	}
-	
-	public void removeRequest(String key) {
-		requestsMap.remove(key);
-	}
-	
-	public MultipartRequest getRequest(String key) {
-		return requestsMap.get(key);
-	}
+        if (requestRegistry == null) {
+            synchronized (applicationMap) {
+                requestRegistry = (MultipartRequestRegistry) applicationMap.get(REGISTRY_ATTRIBUTE_NAME);
+
+                if (requestRegistry == null) {
+                    requestRegistry = new MultipartRequestRegistry();
+                    applicationMap.put(REGISTRY_ATTRIBUTE_NAME, requestRegistry);
+                }
+            }
+        }
+
+        return requestRegistry;
+    }
+
+    public String registerRequest(MultipartRequest request) {
+        String key = registryId + ":" + atomicInteger.incrementAndGet();
+
+        requestsMap.put(key, request);
+
+        return key;
+    }
+
+    public void removeRequest(String key) {
+        requestsMap.remove(key);
+    }
+
+    public MultipartRequest getRequest(String key) {
+        return requestsMap.get(key);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/request/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Implementation of request classes
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/BaseResourceRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/BaseResourceRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/BaseResourceRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,11 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import org.ajax4jsf.Messages;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.Map;
@@ -32,143 +37,146 @@
 import javax.faces.context.FacesContext;
 import javax.faces.context.ResponseWriter;
 
-import org.ajax4jsf.Messages;
-
 /**
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:07 $
- * 
+ *
  */
 public abstract class BaseResourceRenderer implements ResourceRenderer {
+    public void encode(InternetResource resource, FacesContext context, Object data) throws IOException {
+        Map<String, Object> attributes = Collections.emptyMap();
 
-	public void encode(InternetResource resource, FacesContext context,
-			Object data) throws IOException {
-		Map<String, Object> attributes = Collections.emptyMap();
-		this.encodeBegin(resource, context, data, attributes);
-		this.encodeEnd(resource, context, data);
-	}
+        this.encodeBegin(resource, context, data, attributes);
+        this.encodeEnd(resource, context, data);
+    }
 
-	public void encode(InternetResource resource, FacesContext context,
-			Object data, Map<String, Object> attributes) throws IOException {
-		this.encodeBegin(resource, context, data, attributes);
-		this.encodeEnd(resource, context, data);
-	}
+    public void encode(InternetResource resource, FacesContext context, Object data, Map<String, Object> attributes)
+        throws IOException {
+        
+        this.encodeBegin(resource, context, data, attributes);
+        this.encodeEnd(resource, context, data);
+    }
 
-	public void encodeBegin(InternetResource resource, FacesContext context,
-			Object data, Map<String, Object> attributes) throws IOException {
-		if (null != getTag()) {
-			ResponseWriter writer = context.getResponseWriter();
-			writer.startElement(getTag(), null);
-			String attrs[][] = getCommonAttrs();
-			if (null != getHrefAttr()) {
-				writer.writeAttribute(getHrefAttr(), resource.getUri(context,
-						data), null);
-			}
-			if (null != attrs) {
-				for (int i = 0; i < attrs.length; i++) {
-					writer.writeAttribute(attrs[i][0], attrs[i][1], null);
-				}
-			}
-			for (Iterator<Entry<String, Object>> iter = attributes.entrySet().iterator(); iter
-					.hasNext();) {
-				Map.Entry<String, Object> attr = iter.next();
-				writer.writeAttribute(attr.getKey().toString(),
-						attr.getValue(), null);
-			}
-		}
-		this.customEncode(resource, context, data);
-	}
+    public void encodeBegin(InternetResource resource, FacesContext context, Object data,
+            Map<String, Object> attributes) throws IOException {
 
-	public void encodeEnd(InternetResource resource, FacesContext context,
-			Object data) throws IOException {
-		if (null != getTag()) {
-			ResponseWriter writer = context.getResponseWriter();
-			writer.endElement(getTag());
+        if (null != getTag()) {
+            ResponseWriter writer = context.getResponseWriter();
 
-		}
-	}
+            writer.startElement(getTag(), null);
 
-	/**
-	 * Template method for customaize encoding for component. can insert size
-	 * etc. attributes, child tags etc.
-	 * 
-	 * @param resource
-	 * @param context
-	 * @param component
-	 * @throws IOException
-	 */
-	protected void customEncode(InternetResource resource,
-			FacesContext context, Object data) throws IOException {
-		// TODO if concrete renderer need
+            String[][] attrs = getCommonAttrs();
 
-	}
+            if (null != getHrefAttr()) {
+                writer.writeAttribute(getHrefAttr(), resource.getUri(context, data), null);
+            }
 
-	protected abstract String getTag();
+            if (null != attrs) {
+                for (int i = 0; i < attrs.length; i++) {
+                    writer.writeAttribute(attrs[i][0], attrs[i][1], null);
+                }
+            }
 
-	protected abstract String getHrefAttr();
+            for (Iterator<Entry<String, Object>> iter = attributes.entrySet().iterator(); iter.hasNext(); ) {
+                Map.Entry<String, Object> attr = iter.next();
 
-	protected abstract String[][] getCommonAttrs();
+                writer.writeAttribute(attr.getKey().toString(), attr.getValue(), null);
+            }
+        }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceRenderer#send(org.ajax4jsf.resource.InternetResource,
-	 *      org.ajax4jsf.resource.ResourceContext)
-	 */
-	public int send(InternetResource base, ResourceContext context)
-			throws IOException {
-		InputStream in = base.getResourceAsStream(context);
-		OutputStream out = context.getOutputStream();
-		if (null == in) {
-			String message = Messages.getMessage(
-					Messages.NO_INPUT_STREAM_ERROR, base.getKey());
-			throw new IOException(message);
-		}
-		int total = sendStream(in, out);
+        this.customEncode(resource, context, data);
+    }
 
-		return total;
-	}
+    public void encodeEnd(InternetResource resource, FacesContext context, Object data) throws IOException {
+        if (null != getTag()) {
+            ResponseWriter writer = context.getResponseWriter();
 
-	/**
-	 * @param in
-	 * @param out
-	 * @return
-	 * @throws IOException
-	 */
-	protected int sendStream(InputStream in, OutputStream out)
-			throws IOException {
-		int total = 0;
-		byte[] buffer = new byte[InternetResourceBase.BUFFER_SIZE];
-		int length;
-		try {
-			for (length = in.read(buffer); length > 0; length = in.read(buffer)) {
-				out.write(buffer, 0, length);
-				total += length;
-			}
-		} finally {
-			in.close();
-			out.flush();
-			out.close();
-		}
-		return total;
-	}
+            writer.endElement(getTag());
+        }
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceRenderer#requireFacesContext()
-	 */
-	public boolean requireFacesContext() {
-		// TODO Auto-generated method stub
-		return false;
-	}
+    /**
+     * Template method for customaize encoding for component. can insert size
+     * etc. attributes, child tags etc.
+     *
+     * @param resource
+     * @param context
+     * @param component
+     * @throws IOException
+     */
+    protected void customEncode(InternetResource resource, FacesContext context, Object data) throws IOException {
 
-	public Object getData(InternetResource base, FacesContext context,
-			Object data) {
-		// By default, resource dot't provide any data. Can be used in
-		// Template-based or other
-		// configurable resources ( like weblets configuration ).
-		return null;
-	}
+        // TODO if concrete renderer need
+    }
 
+    protected abstract String getTag();
+
+    protected abstract String getHrefAttr();
+
+    protected abstract String[][] getCommonAttrs();
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceRenderer#send(org.ajax4jsf.resource.InternetResource,
+     *      org.ajax4jsf.resource.ResourceContext)
+     */
+    public int send(InternetResource base, ResourceContext context) throws IOException {
+        InputStream in = base.getResourceAsStream(context);
+        OutputStream out = context.getOutputStream();
+
+        if (null == in) {
+            String message = Messages.getMessage(Messages.NO_INPUT_STREAM_ERROR, base.getKey());
+
+            throw new IOException(message);
+        }
+
+        int total = sendStream(in, out);
+
+        return total;
+    }
+
+    /**
+     * @param in
+     * @param out
+     * @return
+     * @throws IOException
+     */
+    protected int sendStream(InputStream in, OutputStream out) throws IOException {
+        int total = 0;
+        byte[] buffer = new byte[InternetResourceBase.BUFFER_SIZE];
+        int length;
+
+        try {
+            for (length = in.read(buffer); length > 0; length = in.read(buffer)) {
+                out.write(buffer, 0, length);
+                total += length;
+            }
+        } finally {
+            in.close();
+            out.flush();
+            out.close();
+        }
+
+        return total;
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceRenderer#requireFacesContext()
+     */
+    public boolean requireFacesContext() {
+
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    public Object getData(InternetResource base, FacesContext context, Object data) {
+
+        // By default, resource dot't provide any data. Can be used in
+        // Template-based or other
+        // configurable resources ( like weblets configuration ).
+        return null;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CacheContext.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CacheContext.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CacheContext.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,31 +18,34 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.resource;
 
-
 /**
  * @author Nick - mailto:nbelaevski at exadel.com
  * created 01.05.2007
- * 
+ *
  */
 public class CacheContext {
-	private CachedResourceContext resourceContext;
     private InternetResource resource;
-	public CacheContext(CachedResourceContext resourceContext,
-			InternetResource resource) {
-		super();
-		this.resourceContext = resourceContext;
-		this.resource = resource;
-	}
-	/**
-	 * @return the resourceContext
-	 */
-	public CachedResourceContext getResourceContext() {
-		return resourceContext;
-	}
-	public InternetResource getResource() {
-		return resource;
-	}
-	
+    private CachedResourceContext resourceContext;
+
+    public CacheContext(CachedResourceContext resourceContext, InternetResource resource) {
+        super();
+        this.resourceContext = resourceContext;
+        this.resource = resource;
+    }
+
+    /**
+     * @return the resourceContext
+     */
+    public CachedResourceContext getResourceContext() {
+        return resourceContext;
+    }
+
+    public InternetResource getResource() {
+        return resource;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CachedResourceContext.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CachedResourceContext.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CachedResourceContext.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,172 +19,197 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import org.ajax4jsf.webapp.CacheContent;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.PrintWriter;
+
 import java.net.MalformedURLException;
 import java.net.URL;
+
 import java.util.Set;
 
-import org.ajax4jsf.resource.ResourceContext;
-import org.ajax4jsf.webapp.CacheContent;
-
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:56:59 $
  *
  */
 public class CachedResourceContext extends ResourceContext {
-	private ResourceContext parent;
-	private CacheContent content;
+    private CacheContent content;
+    private ResourceContext parent;
 
-	/**
-	 * @param parent
-	 */
-	public CachedResourceContext(ResourceContext parent) {
-		this.setCacheEnabled(true);
-		this.parent = parent;
-		this.content = new CacheContent();
-	}
+    /**
+     * @param parent
+     */
+    public CachedResourceContext(ResourceContext parent) {
+        this.setCacheEnabled(true);
+        this.parent = parent;
+        this.content = new CacheContent();
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getOutputStream()
-	 */
-	public OutputStream getOutputStream() throws IOException {
-		return content.getOutputStream();
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getOutputStream()
+     */
+    public OutputStream getOutputStream() throws IOException {
+        return content.getOutputStream();
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getPathInfo()
-	 */
-	public String getPathInfo() {
-		return this.parent.getPathInfo();
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getPathInfo()
+     */
+    public String getPathInfo() {
+        return this.parent.getPathInfo();
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getQueryString()
-	 */
-	public String getQueryString() {
-		return this.parent.getQueryString();
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getQueryString()
+     */
+    public String getQueryString() {
+        return this.parent.getQueryString();
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getRequestParameter(java.lang.String)
-	 */
-	public String getRequestParameter(String data_parameter) {
-		return this.parent.getRequestParameter(data_parameter);
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getRequestParameter(java.lang.String)
+     */
+    @Override
+    public String getRequestParameter(String dataParameter) {
+        return this.parent.getRequestParameter(dataParameter);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getResourceAsStream(java.lang.String)
-	 */
-	public InputStream getResourceAsStream(String path) {
-		return this.parent.getResourceAsStream(path);
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getResourceAsStream(java.lang.String)
+     */
+    @Override
+    public InputStream getResourceAsStream(String path) {
+        return this.parent.getResourceAsStream(path);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getSessionAttribute(java.lang.String)
-	 */
-	public Object getSessionAttribute(String name) {
-		return this.parent.getSessionAttribute(name);
-	}
-	
-	
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getSessionAttribute(java.lang.String)
+     */
+    @Override
+    public Object getSessionAttribute(String name) {
+        return this.parent.getSessionAttribute(name);
+    }
 
-	/**
-	 * @param name
-	 * @return
-	 * @see org.ajax4jsf.resource.ResourceContext#getContextAttribute(java.lang.String)
-	 */
-	public Object getContextAttribute(String name) {
-		return parent.getContextAttribute(name);
-	}
+    /**
+     * @param name
+     * @return
+     * @see org.ajax4jsf.resource.ResourceContext#getContextAttribute(java.lang.String)
+     */
+    @Override
+    public Object getContextAttribute(String name) {
+        return parent.getContextAttribute(name);
+    }
 
-	/**
-	 * @param path
-	 * @return
-	 * @throws MalformedURLException
-	 * @see org.ajax4jsf.resource.ResourceContext#getResource(java.lang.String)
-	 */
-	public URL getResource(String path) throws MalformedURLException {
-		return parent.getResource(path);
-	}
+    /**
+     * @param path
+     * @return
+     * @throws MalformedURLException
+     * @see org.ajax4jsf.resource.ResourceContext#getResource(java.lang.String)
+     */
+    @Override
+    public URL getResource(String path) throws MalformedURLException {
+        return parent.getResource(path);
+    }
 
-	/**
-	 * @param path
-	 * @return
-	 * @see org.ajax4jsf.resource.ResourceContext#getResourcePaths(java.lang.String)
-	 */
-	public Set<String> getResourcePaths(String path) {
-		return parent.getResourcePaths(path);
-	}
+    /**
+     * @param path
+     * @return
+     * @see org.ajax4jsf.resource.ResourceContext#getResourcePaths(java.lang.String)
+     */
+    @Override
+    public Set<String> getResourcePaths(String path) {
+        return parent.getResourcePaths(path);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#setDateHeader(java.lang.String, long)
-	 */
-	public void setDateHeader(String name, long value) {
-		this.content.setDateHeader(name,value);
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#setDateHeader(java.lang.String, long)
+     */
+    @Override
+    public void setDateHeader(String name, long value) {
+        this.content.setDateHeader(name, value);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#setHeader(java.lang.String, java.lang.String)
-	 */
-	public void setHeader(String name, String value) {
-		this.content.setHeader(name,value);
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#setHeader(java.lang.String, java.lang.String)
+     */
+    @Override
+    public void setHeader(String name, String value) {
+        this.content.setHeader(name, value);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#setIntHeader(java.lang.String, int)
-	 */
-	public void setIntHeader(String name, int value) {
-		this.content.setIntHeader(name,value);
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#setIntHeader(java.lang.String, int)
+     */
+    @Override
+    public void setIntHeader(String name, int value) {
+        this.content.setIntHeader(name, value);
+    }
 
-	/**
-	 * @return Returns the content.
-	 */
-	public CacheContent getContent() {
-		return this.content;
-	}
+    /**
+     * @return Returns the content.
+     */
+    public CacheContent getContent() {
+        return this.content;
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getWriter()
-	 */
-	public PrintWriter getWriter() throws IOException {
-		return content.getWriter();
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getWriter()
+     */
+    @Override
+    public PrintWriter getWriter() throws IOException {
+        return content.getWriter();
+    }
 
-	public void setContentType(String contentType) {
-		this.content.setContentType(contentType);
-	}
-	
-	public void setContentLength(int contentLength) {
-		this.content.setContentLength(contentLength);
-	}
+    @Override
+    public void setContentType(String contentType) {
+        this.content.setContentType(contentType);
+    }
 
-	public Object getResourceData() {
-		return parent.getResourceData();
-	}
+    @Override
+    public void setContentLength(int contentLength) {
+        this.content.setContentLength(contentLength);
+    }
 
-	public void setResourceData(Object codec) {
-		parent.setResourceData(codec);
-		
-	}
-	
-	public String getInitParameter(String name) {
-		return parent.getInitParameter(name);
-	}
+    @Override
+    public Object getResourceData() {
+        return parent.getResourceData();
+    }
 
-	public String getServletPath() {
-		return parent.getServletPath();
-	}
-	
-	public void release() {
-		super.release();
-	}
-	
+    @Override
+    public void setResourceData(Object codec) {
+        parent.setResourceData(codec);
+    }
+
+    @Override
+    public String getInitParameter(String name) {
+        return parent.getInitParameter(name);
+    }
+
+    @Override
+    public String getServletPath() {
+        return parent.getServletPath();
+    }
+
+    @Override
+    public void release() {
+        super.release();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CompressedScriptRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CompressedScriptRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CompressedScriptRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,6 +18,9 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.resource;
 
 /**
@@ -25,26 +28,29 @@
  *
  */
 public class CompressedScriptRenderer extends OneTimeRenderer {
+    protected String getTag() {
 
-	protected String getTag() {
-		// TODO Auto-generated method stub
-		return "script";
-	}
+        // TODO Auto-generated method stub
+        return "script";
+    }
 
-	protected String getHrefAttr() {
-		// TODO Auto-generated method stub
-		return "src";
-	}
+    protected String getHrefAttr() {
 
-	protected String[][] getCommonAttrs() {
-		// TODO Auto-generated method stub
-		return new String[][]{{"type",getContentType()}};
-	}
+        // TODO Auto-generated method stub
+        return "src";
+    }
 
-	public String getContentType() {
-		// TODO - use configurable encoding ?
-		return "text/javascript";
-	}
+    protected String[][] getCommonAttrs() {
 
+        // TODO Auto-generated method stub
+        return new String[][] {
+            {"type", getContentType()}
+        };
+    }
 
+    public String getContentType() {
+
+        // TODO - use configurable encoding ?
+        return "text/javascript";
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CountingOutputWriter.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CountingOutputWriter.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/CountingOutputWriter.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,6 +18,9 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.resource;
 
 import java.io.IOException;
@@ -29,97 +32,108 @@
  * @author Andrey Markavtsov
  */
 public class CountingOutputWriter extends Writer {
-	
-	/** count of written bytes */
-	private int written = 0;
-	
-	/** Size of char type */
-	public static final int sizeOfChar = 1;
-	
-	/** Size of int type */
-	public static final int sizeOfInt = 2;
-	
-	/** Buffer to store bytes written */
-	private StringBuffer buffer; 
-			
-	/**
-	 * Default constructor 
-	 */
-	public CountingOutputWriter() {
-   	
-		super();
-		this.buffer = new StringBuffer();
-	}
 
-	/* (non-Javadoc)
-	 * @see java.io.Writer#close()
-	 */
-	public void close() throws IOException {
-		;
-	}
+    /** Size of char type */
+    public static final int SIZE_OF_CHAR = 1;
 
-	/* (non-Javadoc)
-	 * @see java.io.Writer#flush()
-	 */
-	public void flush() throws IOException {
-		;
-	}
+    /** Size of int type */
+    public static final int SIZE_OF_INT = 2;
 
-    /** Methods appends chars written to buffer
-	 *  @param cbuf - chars to be written
-	 *  @param off  - offset
-	 *  @param len  - length of bytes 
-	 */ 
-	public void write(char[] cbuf, int off, int len) throws IOException {
-		buffer.append(cbuf, off, len);
-		written += len; // * sizeOfChar;
-	}
+    /** count of written bytes */
+    private int written = 0;
 
-	/** Methods appends chars written to buffer
-	 *  @param cbuf - chars to be written
-	 */ 
-	public void write(char[] cbuf) throws IOException {
-		buffer.append(cbuf);
-		written += cbuf.length; // * sizeOfChar;
-	}
+    /** Buffer to store bytes written */
+    private StringBuffer buffer;
 
-    /** Methods appends int written to buffer
-	 *  @param c - int to be written
-	 */ 
-	public void write(int c) throws IOException {
-		buffer.append(Character.toChars(c));
-		written += sizeOfInt;
-	}
+    /**
+     * Default constructor
+     */
+    public CountingOutputWriter() {
+        super();
+        this.buffer = new StringBuffer();
+    }
 
-	 /** Methods appends string written to buffer
-	 *  @param str  - string to be written
-	 *  @param off  - offset
-	 *  @param len  - length of bytes 
-	 */ 
-	public void write(String str, int off, int len) throws IOException {
-		buffer.append(str, off, len);
-		written += len;// * sizeOfChar;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see java.io.Writer#close()
+     */
+    @Override
+    public void close() throws IOException {}
 
-	/** Methods appends string written to buffer
-	 *  @param str - string to be written
+    /*
+     *  (non-Javadoc)
+     * @see java.io.Writer#flush()
      */
-	public void write(String str) throws IOException {
-		buffer.append(str);
-		written += str.length();// * sizeOfChar;
-	}
+    @Override
+    public void flush() throws IOException {}
 
-	/** Methods gets written bytes count
-	 *  @return written count of bytes 
-	 */
-	public int getWritten() {
-		return written;
-	}
-	
-	/** Methods gets content of written bytes
-	 *  @return buffer  
-	 */
-	public StringBuffer getContent () {
-		return buffer;
-	}
-}
\ No newline at end of file
+    /**
+     * Methods appends chars written to buffer
+     *  @param cbuf - chars to be written
+     *  @param off  - offset
+     *  @param len  - length of bytes
+     */
+    @Override
+    public void write(char[] cbuf, int off, int len) throws IOException {
+        buffer.append(cbuf, off, len);
+        written += len; // * SIZE_OF_CHAR;
+    }
+
+    /**
+     * Methods appends chars written to buffer
+     *  @param cbuf - chars to be written
+     */
+    @Override
+    public void write(char[] cbuf) throws IOException {
+        buffer.append(cbuf);
+        written += cbuf.length; // * SIZE_OF_CHAR;
+    }
+
+    /**
+     * Methods appends int written to buffer
+     *  @param c - int to be written
+     */
+    @Override
+    public void write(int c) throws IOException {
+        buffer.append(Character.toChars(c));
+        written += SIZE_OF_INT;
+    }
+
+    /**
+     * Methods appends string written to buffer
+     *  @param str  - string to be written
+     *  @param off  - offset
+     *  @param len  - length of bytes
+     */
+    @Override
+    public void write(String str, int off, int len) throws IOException {
+        buffer.append(str, off, len);
+        written += len; // * SIZE_OF_CHAR;
+    }
+
+    /**
+     * Methods appends string written to buffer
+     *  @param str - string to be written
+     */
+    @Override
+    public void write(String str) throws IOException {
+        buffer.append(str);
+        written += str.length(); // * SIZE_OF_CHAR;
+    }
+
+    /**
+     * Methods gets written bytes count
+     *  @return written count of bytes
+     */
+    public int getWritten() {
+        return written;
+    }
+
+    /**
+     * Methods gets content of written bytes
+     *  @return buffer
+     */
+    public StringBuffer getContent() {
+        return buffer;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/FacesResourceContext.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/FacesResourceContext.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/FacesResourceContext.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,183 +19,183 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import org.richfaces.util.Util;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.Writer;
+
 import java.net.MalformedURLException;
 import java.net.URL;
+
 import java.util.Set;
 
 import javax.faces.context.ExternalContext;
 import javax.faces.context.FacesContext;
 
-import org.richfaces.util.Util;
-
 /**
  * @author asmirnov at exadel.com (latest modification by $Author: nick_belaevski $)
  * @version $Revision: 1.1.2.2 $ $Date: 2007/01/11 16:52:14 $
- * 
+ *
  */
 public class FacesResourceContext extends ResourceContext {
+    private ExternalContext externalContext;
+    private FacesContext facesContext;
 
-	private FacesContext facesContext;
+    /**
+     * @param facesContext
+     */
+    public FacesResourceContext(FacesContext facesContext) {
+        this.facesContext = facesContext;
+        this.externalContext = facesContext.getExternalContext();
+    }
 
-	private ExternalContext externalContext;
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceContext#setHeader(java.lang.String,
+     *      java.lang.String)
+     */
+    public void setHeader(String name, String value) {
+        externalContext.setResponseHeader(name, value);
+    }
 
-	/**
-	 * @param facesContext
-	 */
-	public FacesResourceContext(FacesContext facesContext) {
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceContext#setIntHeader(java.lang.String,
+     *      int)
+     */
+    public void setIntHeader(String name, int value) {
+        externalContext.setResponseHeader(name, String.valueOf(value));
+    }
 
-		this.facesContext = facesContext;
-		this.externalContext = facesContext.getExternalContext();
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceContext#setDateHeader(java.lang.String,
+     *      long)
+     */
+    public void setDateHeader(String name, long value) {
+        externalContext.setResponseHeader(name, Util.formatHttpDate(value));
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceContext#setHeader(java.lang.String,
-	 *      java.lang.String)
-	 */
-	public void setHeader(String name, String value) {
-		externalContext.setResponseHeader(name, value);
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceContext#getOutputStream()
+     */
+    public OutputStream getOutputStream() throws IOException {
+        return externalContext.getResponseOutputStream();
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceContext#setIntHeader(java.lang.String,
-	 *      int)
-	 */
-	public void setIntHeader(String name, int value) {
-		externalContext.setResponseHeader(name, String.valueOf(value));
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceContext#getWriter()
+     */
+    public Writer getWriter() throws IOException {
+        return externalContext.getResponseOutputWriter();
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceContext#setDateHeader(java.lang.String,
-	 *      long)
-	 */
-	public void setDateHeader(String name, long value) {
-		externalContext.setResponseHeader(name, Util.formatHttpDate(value));
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceContext#getQueryString()
+     */
+    public String getQueryString() {
+        throw new UnsupportedOperationException();
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceContext#getOutputStream()
-	 */
-	public OutputStream getOutputStream() throws IOException {
-		return externalContext.getResponseOutputStream();
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceContext#getPathInfo()
+     */
+    public String getPathInfo() {
+        return externalContext.getRequestPathInfo();
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceContext#getWriter()
-	 */
-	public Writer getWriter() throws IOException {
-		return externalContext.getResponseOutputWriter();
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.ResourceContext#getSessionAttribute(java.lang.String)
+     */
+    public Object getSessionAttribute(String name) {
+        return externalContext.getSessionMap().get(name);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceContext#getQueryString()
-	 */
-	public String getQueryString() {
-		throw new UnsupportedOperationException();
-	}
+    public InputStream getResourceAsStream(String path) {
+        return externalContext.getResourceAsStream(path);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceContext#getPathInfo()
-	 */
-	public String getPathInfo() {
-		return externalContext.getRequestPathInfo();
-	}
+    public String getRequestParameter(String dataParameter) {
+        return (String) externalContext.getRequestParameterMap().get(dataParameter);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.ResourceContext#getSessionAttribute(java.lang.String)
-	 */
-	public Object getSessionAttribute(String name) {
-		return externalContext.getSessionMap().get(name);
-	}
+    public void setContentType(String contentType) {
+        externalContext.setResponseContentType(contentType);
+    }
 
-	public InputStream getResourceAsStream(String path) {
+    @Override
+    public Object getContextAttribute(String name) {
+        return externalContext.getApplicationMap().get(name);
+    }
 
-		return externalContext.getResourceAsStream(path);
-	}
+    public void setContentLength(int contentLength) {
+        externalContext.setResponseContentLength(contentLength);
+    }
 
-	public String getRequestParameter(String data_parameter) {
+    public String getInitParameter(String name) {
 
-		return (String) externalContext.getRequestParameterMap().get(
-				data_parameter);
-	}
+        // TODO Auto-generated method stub
+        return externalContext.getInitParameter(name);
+    }
 
-	public void setContentType(String contentType) {
-		externalContext.setResponseContentType(contentType);
-	}
-
-    @Override
-    public Object getContextAttribute(String name) {
-    	return externalContext.getApplicationMap().get(name);
+    /**
+     * @param path
+     * @return
+     * @throws MalformedURLException
+     * @see javax.faces.context.ExternalContext#getResource(java.lang.String)
+     */
+    public URL getResource(String path) throws MalformedURLException {
+        return externalContext.getResource(path);
     }
 
-    
-	public void setContentLength(int contentLength) {
-		externalContext.setResponseContentLength(contentLength);
-	}
+    public String getServletPath() {
 
-	public String getInitParameter(String name) {
-		// TODO Auto-generated method stub
-		return externalContext.getInitParameter(name);
-	}
+        // TODO Auto-generated method stub
+        return externalContext.getRequestServletPath();
+    }
 
-	/**
-	 * @param path
-	 * @return
-	 * @throws MalformedURLException
-	 * @see javax.faces.context.ExternalContext#getResource(java.lang.String)
-	 */
-	public URL getResource(String path) throws MalformedURLException {
-		return externalContext.getResource(path);
-	}
+    /**
+     * @param path
+     * @return
+     * @see javax.faces.context.ExternalContext#getResourcePaths(java.lang.String)
+     */
+    public Set<String> getResourcePaths(String path) {
+        return externalContext.getResourcePaths(path);
+    }
 
-	public String getServletPath() {
-		// TODO Auto-generated method stub
-		return externalContext.getRequestServletPath();
-	}
+    public void release() {
+        super.release();
+        externalContext = null;
+        facesContext = null;
+    }
 
-	/**
-	 * @param path
-	 * @return
-	 * @see javax.faces.context.ExternalContext#getResourcePaths(java.lang.String)
-	 */
-	public Set<String> getResourcePaths(String path) {
-		return externalContext.getResourcePaths(path);
-	}
+    // added by nick 11.01.2007 - getters for contexts added
+    public FacesContext getFacesContext() {
+        return facesContext;
+    }
 
-	public void release() {
-		super.release();
-		externalContext = null;
-		facesContext = null;
-	}
+    public ExternalContext getExternalContext() {
+        return externalContext;
+    }
 
-	// added by nick 11.01.2007 - getters for contexts added
-	public FacesContext getFacesContext() {
-		return facesContext;
-	}
-
-	public ExternalContext getExternalContext() {
-		return externalContext;
-	}
-	// by nick
+    // by nick
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/HTMLRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/HTMLRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/HTMLRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,16 +19,15 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import javax.faces.context.FacesContext;
+
 import java.io.IOException;
 import java.io.InputStream;
 
-import javax.faces.context.FacesContext;
-
-import org.ajax4jsf.resource.InternetResource;
-import org.ajax4jsf.resource.ResourceContext;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:03 $
@@ -36,53 +35,71 @@
  */
 public class HTMLRenderer extends BaseResourceRenderer {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getTag()
-	 */
-	protected String getTag() {
-		// TODO Auto-generated method stub
-		return "span";
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getTag()
+     */
+    @Override
+    protected String getTag() {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getHrefAttr()
-	 */
-	protected String getHrefAttr() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+        // TODO Auto-generated method stub
+        return "span";
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getCommonAttrs()
-	 */
-	protected String[][] getCommonAttrs() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getHrefAttr()
+     */
+    @Override
+    protected String getHrefAttr() {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceRenderer#getContentType()
-	 */
-	public String getContentType() {
-		// TODO Auto-generated method stub
-		return "text/html";
-	}
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#customEncode(org.ajax4jsf.resource.InternetResource, javax.faces.context.FacesContext, java.lang.Object)
-	 */
-	protected void customEncode(InternetResource resource, FacesContext context, Object data) throws IOException {
-		// Encode style in page - read from resource.
-		ResourceContext resourceContext = new FacesResourceContext(context);
-		InputStream in = resource.getResourceAsStream(resourceContext);
-		StringBuffer buff = new StringBuffer();
-		int input;
-		while((input = in.read())>0){
-			buff.append((char)input);
-		}
-		in.close();
-		//  MyFaces & RI have different beahvior for style element, in RI best use writeComment ?
-		// TODO - detect page content type ?
-		context.getResponseWriter().writeText(buff,resource.getKey());
-	}
+        // TODO Auto-generated method stub
+        return null;
+    }
 
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getCommonAttrs()
+     */
+    @Override
+    protected String[][] getCommonAttrs() {
+
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceRenderer#getContentType()
+     */
+    public String getContentType() {
+
+        // TODO Auto-generated method stub
+        return "text/html";
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#customEncode(org.ajax4jsf.resource.InternetResource,
+     * javax.faces.context.FacesContext, java.lang.Object)
+     */
+    @Override
+    protected void customEncode(InternetResource resource, FacesContext context, Object data) throws IOException {
+
+        // Encode style in page - read from resource.
+        ResourceContext resourceContext = new FacesResourceContext(context);
+        InputStream in = resource.getResourceAsStream(resourceContext);
+        StringBuffer buff = new StringBuffer();
+        int input;
+
+        while ((input = in.read()) > 0) {
+            buff.append((char) input);
+        }
+
+        in.close();
+
+        // MyFaces & RI have different beahvior for style element, in RI best use writeComment ?
+        // TODO - detect page content type ?
+        context.getResponseWriter().writeText(buff, resource.getKey());
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceBase.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceBase.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceBase.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,424 +19,434 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import org.ajax4jsf.Messages;
+
+import org.richfaces.log.RichfacesLogger;
+import org.richfaces.util.Util;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
 import java.io.InputStream;
+
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
 
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.Messages;
-import org.richfaces.log.RichfacesLogger;
-import org.richfaces.util.Util;
-import org.slf4j.Logger;
-
 /**
  * Base class for all Html page resources - images, scripts, styles etc. Realise
  * as "brige" pattern - different subclasses for different resource source
  * (static,jar,soft generator ) and customaized with differernt renderers for
  * image, script, style ( linked ir inline ). must operate with different
  * sources - application context, classpath, software generator.
- * 
+ *
  * @author shura (latest modification by $Author: nick_belaevski $)
  * @version $Revision: 1.1.2.2 $ $Date: 2007/01/11 16:52:15 $
- * 
+ *
  */
 public abstract class InternetResourceBase implements InternetResource {
+    static final int BUFFER_SIZE = 1024;
+    private static final Logger LOG = RichfacesLogger.RESOURCE.getLogger();
 
-	private static final Logger log = RichfacesLogger.RESOURCE.getLogger();
+    // Hours
+    private int contentLength = -1;
+    private Date lastModified = new Date(System.currentTimeMillis());
+    private long expired = Long.MIN_VALUE;
+    private boolean cacheable = true;
+    private ResourceRenderer renderer = null;
+    private boolean sessionAware = true;
+    private Map<Object, Object> customProperties = new HashMap<Object, Object>();
+    private String key;
 
-	static final int BUFFER_SIZE = 1024;
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.chameleon.resource.InternetResource#getContentLength()
+     */
+    public int getContentLength(ResourceContext resourceContext) {
+        return contentLength;
+    }
 
-	// Hours
+    /**
+     * @param contentLength
+     *            The contentLength to set.
+     */
+    protected void setContentLength(int contentLength) {
+        this.contentLength = contentLength;
+    }
 
-	private int contentLength = -1;
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.chameleon.resource.InternetResource#getExpired()
+     */
+    public long getExpired(ResourceContext resourceContext) {
+        if (expired == Long.MIN_VALUE) {
+            expired = -1;
 
-	private Date lastModified = new Date(System.currentTimeMillis());
+            String defaultExpireParameter = resourceContext.getInitParameter(InternetResource.DEFAULT_EXPITE_PARAMETER);
 
-	private long expired = Long.MIN_VALUE;
+            if (null != defaultExpireParameter) {
+                expired = Long.parseLong(defaultExpireParameter) * 1000L;
+            }
+        }
 
-	private boolean cacheable = true;
+        return expired;
+    }
 
-	private boolean sessionAware = true;
+    /**
+     * @param expired
+     *            The expired to set.
+     */
+    public void setExpired(long expired) {
+        this.expired = expired;
+    }
 
-	private ResourceRenderer renderer = null;
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.chameleon.resource.InternetResource#getLastModified()
+     */
+    public Date getLastModified(ResourceContext resourceContext) {
+        if (null != lastModified) {
+            return lastModified;
+        } else {
+            return new Date(System.currentTimeMillis());
+        }
+    }
 
-	private Map<Object,Object> customProperties = new HashMap<Object, Object>();
+    /**
+     * @param lastModified
+     *            The lastModified to set.
+     */
+    public void setLastModified(Date lastModified) {
+        this.lastModified = lastModified;
+    }
 
-	private String key;
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.chameleon.resource.InternetResource#isCacheable()
+     */
+    public boolean isCacheable(ResourceContext resourceContext) {
+        return cacheable;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.chameleon.resource.InternetResource#getContentLength()
-	 */
-	public int getContentLength(ResourceContext resourceContext) {
-		return contentLength;
-	}
+    /**
+     * @param cacheable
+     *            The cacheable to set.
+     */
+    public void setCacheable(boolean cacheable) {
+        this.cacheable = cacheable;
+    }
 
-	/**
-	 * @param contentLength
-	 *            The contentLength to set.
-	 */
-	protected void setContentLength(int contentLength) {
-		this.contentLength = contentLength;
-	}
+    /**
+     * @return Returns the sessionAware.
+     */
+    public boolean isSessionAware() {
+        return requireFacesContext();
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.chameleon.resource.InternetResource#getExpired()
-	 */
-	public long getExpired(ResourceContext resourceContext) {
-		if( expired == Long.MIN_VALUE ){
-			expired = -1;
-			String defaultExpireParameter = resourceContext.getInitParameter(InternetResource.DEFAULT_EXPITE_PARAMETER);
-			if(null != defaultExpireParameter){
-				expired = Long.parseLong(defaultExpireParameter)*1000L;
-			}
-		}			
-		return expired;
-	}
+    /**
+     * @param sessionAware
+     *            The sessionAware to set.
+     */
+    public void setSessionAware(boolean sessionAware) {
+        this.sessionAware = sessionAware;
+    }
 
-	/**
-	 * @param expired
-	 *            The expired to set.
-	 */
-	public void setExpired(long expired) {
-		this.expired = expired;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.chameleon.resource.InternetResource#getContentType()
+     */
+    public String getContentType(ResourceContext resourceContext) {
+        return getRenderer(resourceContext).getContentType();
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.chameleon.resource.InternetResource#getLastModified()
-	 */
-	public Date getLastModified(ResourceContext resourceContext) {
+    /**
+     * @return Returns the renderer.
+     */
+    public ResourceRenderer getRenderer(ResourceContext resourceContext) {
+        return renderer;
+    }
 
-		if (null != lastModified) {
-			return lastModified;
-		} else {
-			return new Date(System.currentTimeMillis());
-		}
-	}
+    /**
+     * @param renderer
+     *            The renderer to set.
+     */
+    public void setRenderer(ResourceRenderer renderer) {
+        this.renderer = renderer;
+    }
 
-	/**
-	 * @param lastModified
-	 *            The lastModified to set.
-	 */
-	public void setLastModified(Date lastModified) {
-		this.lastModified = lastModified;
-	}
+    /**
+     * Key for wich resource registered in resource builder.
+     *
+     * @return Returns the key.
+     */
+    public String getKey() {
+        return key;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.chameleon.resource.InternetResource#isCacheable()
-	 */
-	public boolean isCacheable(ResourceContext resourceContext) {
-		return cacheable;
-	}
+    /**
+     * Set registration key ( by {@link InternetResourceBuilder} for this
+     * resource.
+     *
+     * @param key
+     *            The key to set.
+     */
+    public void setKey(String key) {
+        this.key = key;
+    }
 
-	/**
-	 * @param cacheable
-	 *            The cacheable to set.
-	 */
-	public void setCacheable(boolean cacheable) {
-		this.cacheable = cacheable;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#getUri(javax.faces.context.FacesContext,
+     *      java.lang.Object)
+     */
+    public String getUri(final FacesContext context, Object data) {
 
-	/**
-	 * @return Returns the sessionAware.
-	 */
-	public boolean isSessionAware() {
-		return requireFacesContext();
-	}
+        /*
+         * return InternetResourceBuilder.getInstance().getUri(this, context,
+         *       getDataToStore(context, data));
+         */
+        return null;
+    }
 
-	/**
-	 * @param sessionAware
-	 *            The sessionAware to set.
-	 */
-	public void setSessionAware(boolean sessionAware) {
-		this.sessionAware = sessionAware;
-	}
+    /**
+     * Template method to construct resource-specific data ( to store in
+     * resource URI ). If resource must store any data in session or other
+     * cache, it must be done here. Since lightweight realisation, information
+     * for restore such data muct be returned by this method.
+     *
+     * @param context -
+     *            current faces context.
+     * @param data -
+     *            data for build information, usually current
+     *            {@link javax.faces.component.UIComponent}
+     * @return - any {@link java.io.Serializable} object, or null.
+     */
+    protected Object getDataToStore(FacesContext context, Object data) {
+        return getRenderer(new FacesResourceContext(context)).getData(this, context, data);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.chameleon.resource.InternetResource#getContentType()
-	 */
-	public String getContentType(ResourceContext resourceContext) {
-		return getRenderer(resourceContext).getContentType();
-	}
+    /**
+     * Restore data object from resource URI request parameter ( same object as
+     * returned in getDataToStore method )
+     *
+     * @param context
+     * @return restored data, or null.
+     */
+    protected Object restoreData(ResourceContext context) {
+        Object data = context.getResourceData();
 
-	/**
-	 * @return Returns the renderer.
-	 */
-	public ResourceRenderer getRenderer(ResourceContext resourceContext) {
-		return renderer;
-	}
+        if (data instanceof byte[]) {
+            byte[] objectArray = (byte[]) data;
 
-	/**
-	 * @param renderer
-	 *            The renderer to set.
-	 */
-	public void setRenderer(ResourceRenderer renderer) {
-		this.renderer = renderer;
-	}
+            data = deserializeData(objectArray);
+        }
 
-	/**
-	 * Key for wich resource registered in resource builder.
-	 * 
-	 * @return Returns the key.
-	 */
-	public String getKey() {
-		return key;
-	}
+        return data;
+    }
 
-	/**
-	 * Set registration key ( by {@link InternetResourceBuilder} for this
-	 * resource.
-	 * 
-	 * @param key
-	 *            The key to set.
-	 */
-	public void setKey(String key) {
-		this.key = key;
-	}
+    /**
+     * Deserialize parameters object from byte array. By default, used Java
+     * de-serialisation from ObjectOutputStream , but implementations can
+     * override this method ( togewer with getDataToStore ) for implement short
+     * version.
+     *
+     * @param objectArray
+     * @return
+     * @throws IOException
+     * @throws ClassNotFoundException
+     */
+    protected Object deserializeData(byte[] objectArray) {
+        return objectArray;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#getUri(javax.faces.context.FacesContext,
-	 *      java.lang.Object)
-	 */
-	public String getUri(final FacesContext context, Object data) {
-		/*return InternetResourceBuilder.getInstance().getUri(this, context,
-				getDataToStore(context, data));*/
-	
-		return null;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.chameleon.resource.InternetResource#getResourceAsStream()
+     */
+    public InputStream getResourceAsStream(ResourceContext context) {
+        throw new UnsupportedOperationException(Messages.getMessage(Messages.METHOD_NOT_IMPLEMENTED,
+                "getResourceAsStream"));
+    }
 
-	/**
-	 * Template method to construct resource-specific data ( to store in
-	 * resource URI ). If resource must store any data in session or other
-	 * cache, it must be done here. Since lightweight realisation, information
-	 * for restore such data muct be returned by this method.
-	 * 
-	 * @param context -
-	 *            current faces context.
-	 * @param data -
-	 *            data for build information, usually current
-	 *            {@link javax.faces.component.UIComponent}
-	 * @return - any {@link java.io.Serializable} object, or null.
-	 */
-	protected Object getDataToStore(FacesContext context, Object data) {
-		return getRenderer(new FacesResourceContext(context)).getData(this, context, data);
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#getProperty(java.lang.Object)
+     */
+    public Object getProperty(Object key) {
 
-	/**
-	 * Restore data object from resource URI request parameter ( same object as
-	 * returned in getDataToStore method )
-	 * 
-	 * @param context
-	 * @return restored data, or null.
-	 */
-	protected Object restoreData(ResourceContext context) {
+        // TODO Auto-generated method stub
+        return customProperties.get(key);
+    }
 
-		Object data = context.getResourceData();
-		if (data instanceof byte[]) {
-			byte[] objectArray = (byte[]) data;
-			data = deserializeData(objectArray);
-		}
-		return data;
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#setProperty(java.lang.Object,
+     *      java.lang.Object)
+     */
+    public void setProperty(Object key, Object value) {
+        customProperties.put(key, value);
+    }
 
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#encode(javax.faces.context.FacesContext,
+     *      javax.faces.component.UIComponent)
+     */
+    public void encode(FacesContext context, Object data) throws IOException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.ENCODE_HTML_INFO, getKey()));
+        }
 
-	/**
-	 * Deserialize parameters object from byte array. By default, used Java
-	 * de-serialisation from ObjectOutputStream , but implementations can
-	 * override this method ( togewer with getDataToStore ) for implement short
-	 * version.
-	 * 
-	 * @param objectArray
-	 * @return
-	 * @throws IOException
-	 * @throws ClassNotFoundException
-	 */
-	protected Object deserializeData(byte[] objectArray) {
-		return objectArray;
-	}
+        getRenderer(new FacesResourceContext(context)).encode(this, context, data);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.chameleon.resource.InternetResource#getResourceAsStream()
-	 */
-	public InputStream getResourceAsStream(ResourceContext context) {
-		throw new UnsupportedOperationException(Messages.getMessage(
-				Messages.METHOD_NOT_IMPLEMENTED, "getResourceAsStream"));
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#encode(javax.faces.context.FacesContext,
+     *      java.lang.Object, java.util.Map)
+     */
+    public void encode(FacesContext context, Object data, Map<String, Object> attributes) throws IOException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.ENCODE_HTML_INFO_2, getKey(), attributes));
+        }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#getProperty(java.lang.Object)
-	 */
-	public Object getProperty(Object key) {
-		// TODO Auto-generated method stub
-		return customProperties.get(key);
-	}
+        getRenderer(new FacesResourceContext(context)).encodeBegin(this, context, data, attributes);
+        getRenderer(new FacesResourceContext(context)).encodeEnd(this, context, data);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#setProperty(java.lang.Object,
-	 *      java.lang.Object)
-	 */
-	public void setProperty(Object key, Object value) {
-		customProperties.put(key, value);
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#encodeBegin(javax.faces.context.FacesContext,
+     *      javax.faces.component.UIComponent, java.util.Map)
+     */
+    public void encodeBegin(FacesContext context, Object component, Map<String, Object> attrs) throws IOException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.ENCODE_BEGIN_HTML_INFO, getKey(), attrs));
+        }
 
-	}
+        getRenderer(new FacesResourceContext(context)).encodeBegin(this, context, component, attrs);
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#encode(javax.faces.context.FacesContext,
-	 *      javax.faces.component.UIComponent)
-	 */
-	public void encode(FacesContext context, Object data) throws IOException {
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.ENCODE_HTML_INFO, getKey()));
-		}
-		getRenderer(new FacesResourceContext(context)).encode(this, context, data);
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#encodeEnd(javax.faces.context.FacesContext,
+     *      javax.faces.component.UIComponent, java.util.Map)
+     */
+    public void encodeEnd(FacesContext context, Object component) throws IOException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.ENCODE_END_HTML_INFO, getKey()));
+        }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#encode(javax.faces.context.FacesContext,
-	 *      java.lang.Object, java.util.Map)
-	 */
-	public void encode(FacesContext context, Object data, Map<String, Object> attributes)
-			throws IOException {
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.ENCODE_HTML_INFO_2,
-					getKey(), attributes));
-		}
-		getRenderer(new FacesResourceContext(context)).encodeBegin(this, context, data, attributes);
-		getRenderer(new FacesResourceContext(context)).encodeEnd(this, context, data);
+        getRenderer(new FacesResourceContext(context)).encodeEnd(this, context, component);
+    }
 
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#send(javax.faces.context.FacesContext,
+     *      java.lang.Object)
+     */
+    public void send(ResourceContext context) throws IOException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.SEND_CONTENT_INFO, getKey()));
+        }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#encodeBegin(javax.faces.context.FacesContext,
-	 *      javax.faces.component.UIComponent, java.util.Map)
-	 */
-	public void encodeBegin(FacesContext context, Object component, Map<String, Object> attrs)
-			throws IOException {
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.ENCODE_BEGIN_HTML_INFO,
-					getKey(), attrs));
-		}
-		getRenderer(new FacesResourceContext(context)).encodeBegin(this, context, component, attrs);
+        int total = getRenderer(context).send(this, context);
 
-	}
+        // For cacheable resources, store size.
+        if (isCacheable(context)) {
+            if (context instanceof CachedResourceContext) {
+                CachedResourceContext cachedContext = (CachedResourceContext) context;
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#encodeEnd(javax.faces.context.FacesContext,
-	 *      javax.faces.component.UIComponent, java.util.Map)
-	 */
-	public void encodeEnd(FacesContext context, Object component)
-			throws IOException {
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.ENCODE_END_HTML_INFO,
-					getKey()));
-		}
-		getRenderer(new FacesResourceContext(context)).encodeEnd(this, context, component);
-	}
+                cachedContext.getContent().setContentLength(total);
+            } else {
+                setContentLength(total);
+            }
+        }
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#send(javax.faces.context.FacesContext,
-	 *      java.lang.Object)
-	 */
-	public void send(ResourceContext context) throws IOException {
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.SEND_CONTENT_INFO,getKey()));
-		}
-		int total = getRenderer(context).send(this, context);
-		// For cacheable resources, store size.
-		if (isCacheable(context)) {
-			if (context instanceof CachedResourceContext) {
-				CachedResourceContext cachedContext = (CachedResourceContext) context;
-				cachedContext.getContent().setContentLength(total);
-			} else {
-				setContentLength(total);
-			}
-		}
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.chameleon.resource.InternetResource#sendHeaders(javax.servlet.http.HttpServletResponse)
+     */
+    public void sendHeaders(ResourceContext context) {
+        boolean cached = context.isCacheEnabled() && isCacheable(context);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.chameleon.resource.InternetResource#sendHeaders(javax.servlet.http.HttpServletResponse)
-	 */
-	public void sendHeaders(ResourceContext context) {
-		boolean cached = context.isCacheEnabled() && isCacheable(context);
-		if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.SET_RESPONSE_HEADERS_INFO,
-					getKey()));
-		}
-		// context.setHeader("Content-Type",getContentType());
-		context.setContentType(getContentType(context));
-		Date lastModified = getLastModified(context);
-		if (lastModified != null) {
-			context.setHeader("Last-Modified", Util.formatHttpDate(lastModified.getTime()));
-			//context.setDateHeader("Last-Modified", lastModified.getTime());
-		}
-		int contentLength = getContentLength(context);
-		if (cached) {
-			if (contentLength > 0) {
-				context.setContentLength(contentLength);
-			}
-			long expired = getExpired(context);
-			if (expired < 0 ) {
-				expired = DEFAULT_EXPIRE;
-			}
-				context.setHeader("Expires", Util.formatHttpDate(System.currentTimeMillis()
-						+ expired));
-//				context.setDateHeader("Expires", System.currentTimeMillis()
-//						+ expired);
-				context.setHeader("Cache-Control", "max-age=" + (expired / 1000L));
-		} else {
-			if (contentLength > 0) {
-				context.setContentLength(contentLength);
-//			} else {
-//				context.setHeader("Transfer-Encoding", "chunked");
-			}
-			context.setHeader("Cache-Control", "max-age=0, no-store, no-cache");
-			context.setHeader("Pragma", "no-cache");
-			context.setIntHeader("Expires", 0);
-		}
-	}
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.SET_RESPONSE_HEADERS_INFO, getKey()));
+        }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.resource.InternetResource#requireFacesContext()
-	 */
-	public boolean requireFacesContext() {
-		// by default, send data in ordinary Http request.
-		return getRenderer(null).requireFacesContext();
-	}
+        // context.setHeader("Content-Type",getContentType());
+        context.setContentType(getContentType(context));
 
+        Date lastModified = getLastModified(context);
+
+        if (lastModified != null) {
+            context.setHeader("Last-Modified", Util.formatHttpDate(lastModified.getTime()));
+
+            // context.setDateHeader("Last-Modified", lastModified.getTime());
+        }
+
+        int contentLength = getContentLength(context);
+
+        if (cached) {
+            if (contentLength > 0) {
+                context.setContentLength(contentLength);
+            }
+
+            long expired = getExpired(context);
+
+            if (expired < 0) {
+                expired = DEFAULT_EXPIRE;
+            }
+
+            context.setHeader("Expires", Util.formatHttpDate(System.currentTimeMillis() + expired));
+
+//          context.setDateHeader("Expires", System.currentTimeMillis()
+//                  + expired);
+            context.setHeader("Cache-Control", "max-age=" + (expired / 1000L));
+        } else {
+            if (contentLength > 0) {
+                context.setContentLength(contentLength);
+
+//              } else {
+//                  context.setHeader("Transfer-Encoding", "chunked");
+            }
+
+            context.setHeader("Cache-Control", "max-age=0, no-store, no-cache");
+            context.setHeader("Pragma", "no-cache");
+            context.setIntHeader("Expires", 0);
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.resource.InternetResource#requireFacesContext()
+     */
+    public boolean requireFacesContext() {
+
+        // by default, send data in ordinary Http request.
+        return getRenderer(null).requireFacesContext();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceService.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceService.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceService.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,10 +19,26 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.cache.Cache;
+import org.ajax4jsf.cache.CacheFactory;
+import org.ajax4jsf.cache.CacheManager;
+import org.ajax4jsf.cache.ServletContextInitMap;
+import org.ajax4jsf.resource.util.URLToStreamHelper;
+import org.ajax4jsf.webapp.BaseFilter;
+import org.ajax4jsf.webapp.WebXml;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
 import java.io.InputStream;
+
 import java.util.Map;
 import java.util.Properties;
 
@@ -30,6 +46,7 @@
 import javax.faces.FactoryFinder;
 import javax.faces.context.FacesContext;
 import javax.faces.context.FacesContextFactory;
+
 import javax.servlet.FilterConfig;
 import javax.servlet.ServletContext;
 import javax.servlet.ServletException;
@@ -38,287 +55,273 @@
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.cache.Cache;
-import org.ajax4jsf.cache.CacheFactory;
-import org.ajax4jsf.cache.CacheManager;
-import org.ajax4jsf.cache.ServletContextInitMap;
-import org.ajax4jsf.resource.util.URLToStreamHelper;
-import org.ajax4jsf.webapp.BaseFilter;
-import org.ajax4jsf.webapp.WebXml;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 public class InternetResourceService {
-	private static final Logger log = RichfacesLogger.RESOURCE.getLogger();
+    static final String ENABLE_CACHING_PARAMETER = "enable-cache";
+    private static final String RESOURCE_LIFECYCLE_PARAMETER = "org.ajax4jsf.RESOURCE_LIFECYCLE";
+    private static final Logger LOG = RichfacesLogger.RESOURCE.getLogger();
+    private Cache cache = null;
+    private boolean cacheEnabled = true;
 
-	static final String ENABLE_CACHING_PARAMETER = "enable-cache";
+    // private ServletCacheAdministrator cacheAdmin;
+    private FacesContextFactory contextFactory;
+    private FilterConfig filterConfig;
+    private ResourceLifecycle lifecycle;
 
-	private static final String RESOURCE_LIFECYCLE_PARAMETER = "org.ajax4jsf.RESOURCE_LIFECYCLE";
+    // private RenderKitFactory renderKitFactory;
+    private String lifecycleClass;
+    private WebXml webXml;
 
-	private FilterConfig filterConfig;
+    public InternetResourceService() {}
 
-	private boolean cacheEnabled = true;
+    public void setCacheEnabled(boolean b) {
+        cacheEnabled = b;
+    }
 
-	private Cache cache = null;
+    public void init(FilterConfig config) throws ServletException {
+        filterConfig = config;
 
-	// private ServletCacheAdministrator cacheAdmin;
+        ServletContext servletContext = config.getServletContext();
 
-	private FacesContextFactory contextFactory;
+        if ("false".equalsIgnoreCase(config.getInitParameter(ENABLE_CACHING_PARAMETER))) {
+            setCacheEnabled(false);
 
-	// private RenderKitFactory renderKitFactory;
-	private String lifecycleClass;
+            // this.cacheEnabled = false;
+            // this.cacheAdmin = null;
+        } else {
 
-	private ResourceLifecycle lifecycle;
+            // this.cacheAdmin = ServletCacheAdministrator.getInstance(
+            // servletContext, cacheProperties);
+            CacheManager cacheManager = CacheManager.getInstance();
+            Map<String, String> env = new ServletContextInitMap(servletContext);
+            CacheFactory cacheFactory = cacheManager.getCacheFactory(env);
 
-	private WebXml webXml;
+            this.cache = cacheFactory.createCache(env);
+        }
 
-	public InternetResourceService() {
-	}
+        // Create Resource-specific Faces Lifecycle instance.
+        lifecycleClass = servletContext.getInitParameter(RESOURCE_LIFECYCLE_PARAMETER);
 
-	public void setCacheEnabled(boolean b) {
-		cacheEnabled = b;
-	}
+        if (lifecycleClass != null) {
+            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
 
-	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 {
-			// this.cacheAdmin = ServletCacheAdministrator.getInstance(
-			// servletContext, cacheProperties);
-			CacheManager cacheManager = CacheManager.getInstance();
-			Map<String, String> env = new ServletContextInitMap(servletContext);
-			CacheFactory cacheFactory = cacheManager.getCacheFactory(env);
-			this.cache = cacheFactory.createCache(env);
-		}
-		// 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");
-		}
-	}
+            try {
+                Class<?> clazz = classLoader.loadClass(lifecycleClass);
 
-	/*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;
-	}*/
+                lifecycle = (ResourceLifecycle) clazz.newInstance();
+            } catch (Exception e) {
+                throw new FacesException("Error create instance of resource Lifecycle " + lifecycleClass, e);
+            }
+        } else {
+            lifecycle = new ResourceLifecycle();
+        }
 
-	/*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);
+        webXml = new WebXml();
+        webXml.init(servletContext, filterConfig.getFilterName());
 
-		ResourceContext resourceContext = getResourceContext(resource, request,
-				response);
-		resourceContext.setResourceData(resourceDataForKey);
-		try {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Resources service initialized");
+        }
+    }
 
-			if (resource.isCacheable(resourceContext) && 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(
-								resourceContext).getTime() - 1000;
-						if (lastModified <= ifModifiedSince) {
-							response.setStatus(304);
-							return;
-						}
-					}
-				} catch (IllegalArgumentException e) {
-					log
-							.warn(
-									Messages
-											.getMessage(Messages.PARSING_IF_MODIFIED_SINCE_WARNING),
-									e);
-				}
-				
-				try {
-					String cacheKey = resourceKey;
-					CachedResourceContext cachedResourceContext = new CachedResourceContext(
-							resourceContext);
-	
-					CacheContext cacheLoaderContext = new CacheContext(
-							cachedResourceContext, resource);
-	
-					CacheContent content = (CacheContent) cache.get(cacheKey);
-					
-					long expiredTime = resource.getExpired(resourceContext);
-					if (content == null) {
-						try {
-							getLifecycle().send(cachedResourceContext, resource);
-						} catch (IOException e) {
-							throw new FacesException(e.getMessage(), e);
-						}
-	
-						content = cachedResourceContext.getContent();
-						Date expired = null;
-						if (expiredTime > 0) {
-							expired = new Date(expiredTime);
-						}
-						cache.put(resourceKey, content, expired);
-					}
-					
-					if (log.isDebugEnabled()) {
-						log
-								.debug(Messages.getMessage(
-										Messages.GET_CONTENT_FROM_CACHE_INFO,
-										cacheKey));
-					}
-					content.sendHeaders(response);
-					// Correct expires date for resource.
-					long expired = expiredTime;
-					if (expired < 0 ) {
-						expired = InternetResource.DEFAULT_EXPIRE;
-					} 
-						response.setDateHeader("Expires", System
-								.currentTimeMillis()
-								+ expired);
-	//						response.addHeader("Cache-control", "max-age="
-	//								+ (expired / 1000L));
-					if (!request.getMethod().equals("HEAD")) {
-						content.send(response);
-					}
-					content.flush(response);
-				} catch (Exception e) {
-					log.error(
-							Messages.getMessage(Messages.SEND_RESOURCE_ERROR),
-							e);
-					throw new ServletException(Messages.getMessage(
-							Messages.SEND_RESOURCE_ERROR_2, e.getMessage()), e);
-				}
-			} else {
-				getLifecycle().send(resourceContext, resource);
-				// sendResource(resource, request, response,
-				// resourceDataForKey);
-			}
+    /*
+     * 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;
+     * }
+     */
 
-		} finally {
-			resourceContext.release();
-		}
-	}*/
+    /*
+     * 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);
+     *
+     *   ResourceContext resourceContext = getResourceContext(resource, request,
+     *           response);
+     *   resourceContext.setResourceData(resourceDataForKey);
+     *   try {
+     *
+     *       if (resource.isCacheable(resourceContext) && 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(
+     *                           resourceContext).getTime() - 1000;
+     *                   if (lastModified <= ifModifiedSince) {
+     *                       response.setStatus(304);
+     *                       return;
+     *                   }
+     *               }
+     *           } catch (IllegalArgumentException e) {
+     *               log
+     *                       .warn(
+     *                               Messages
+     *                                       .getMessage(Messages.PARSING_IF_MODIFIED_SINCE_WARNING),
+     *                               e);
+     *           }
+     *
+     *           try {
+     *               String cacheKey = resourceKey;
+     *               CachedResourceContext cachedResourceContext = new CachedResourceContext(
+     *                       resourceContext);
+     *
+     *               CacheContext cacheLoaderContext = new CacheContext(
+     *                       cachedResourceContext, resource);
+     *
+     *               CacheContent content = (CacheContent) cache.get(cacheKey);
+     *
+     *               long expiredTime = resource.getExpired(resourceContext);
+     *               if (content == null) {
+     *                   try {
+     *                       getLifecycle().send(cachedResourceContext, resource);
+     *                   } catch (IOException e) {
+     *                       throw new FacesException(e.getMessage(), e);
+     *                   }
+     *
+     *                   content = cachedResourceContext.getContent();
+     *                   Date expired = null;
+     *                   if (expiredTime > 0) {
+     *                       expired = new Date(expiredTime);
+     *                   }
+     *                   cache.put(resourceKey, content, expired);
+     *               }
+     *
+     *               if (log.isDebugEnabled()) {
+     *                   log
+     *                           .debug(Messages.getMessage(
+     *                                   Messages.GET_CONTENT_FROM_CACHE_INFO,
+     *                                   cacheKey));
+     *               }
+     *               content.sendHeaders(response);
+     *               // Correct expires date for resource.
+     *               long expired = expiredTime;
+     *               if (expired < 0 ) {
+     *                   expired = InternetResource.DEFAULT_EXPIRE;
+     *               }
+     *                   response.setDateHeader("Expires", System
+     *                           .currentTimeMillis()
+     *                           + expired);
+     * //                      response.addHeader("Cache-control", "max-age="
+     * //                              + (expired / 1000L));
+     *               if (!request.getMethod().equals("HEAD")) {
+     *                   content.send(response);
+     *               }
+     *               content.flush(response);
+     *           } catch (Exception e) {
+     *               log.error(
+     *                       Messages.getMessage(Messages.SEND_RESOURCE_ERROR),
+     *                       e);
+     *               throw new ServletException(Messages.getMessage(
+     *                       Messages.SEND_RESOURCE_ERROR_2, e.getMessage()), e);
+     *           }
+     *       } else {
+     *           getLifecycle().send(resourceContext, resource);
+     *           // sendResource(resource, request, response,
+     *           // resourceDataForKey);
+     *       }
+     *
+     *   } finally {
+     *       resourceContext.release();
+     *   }
+     * }
+     */
 
-	/**
-	 * @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);
-		}
-		return resourceContext;
-	}
+    /**
+     * @param resource
+     * @param request
+     * @param response
+     * @return
+     * @throws ServletException
+     * @throws FacesException
+     */
+    protected ResourceContext getResourceContext(InternetResource resource, HttpServletRequest request,
+            HttpServletResponse response) throws FacesException {
 
-	/**
-	 * Get properties file from classpath
-	 * 
-	 * @param name
-	 * @return
-	 */
-	protected Properties getProperties(String name) {
-		Properties properties = new Properties();
-		InputStream props = URLToStreamHelper.urlToStreamSafe(BaseFilter.class.getResource(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;
+        ResourceContext resourceContext;
+        if (resource.requireFacesContext()) {
+            resourceContext = new FacesResourceContext(getFacesContext(request, response));
+        } else {
+            resourceContext = new ServletResourceContext(getServletContext(), request, response);
+        }
 
-	}
+        return resourceContext;
+    }
 
-	/**
-	 * @return Returns the servletContext.
-	 */
-	protected ServletContext getServletContext() {
-		return filterConfig.getServletContext();
-	}
+    /**
+     * Get properties file from classpath
+     *
+     * @param name
+     * @return
+     */
+    protected Properties getProperties(String name) {
+        Properties properties = new Properties();
+        InputStream props = URLToStreamHelper.urlToStreamSafe(BaseFilter.class.getResource(name));
 
-	/**
-	 * @return the lifecycle
-	 * @throws ServletException
-	 */
-	protected ResourceLifecycle getLifecycle() throws FacesException {
-		return lifecycle;
-	}
+        if (null != props) {
+            try {
+                properties.load(props);
+            } catch (IOException e) {
 
-	/**
-	 * @return the contextFactory
-	 */
-	protected synchronized FacesContextFactory getContextFactory() {
-		if (contextFactory == null) {
-			contextFactory = (FacesContextFactory) FactoryFinder
-					.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
-		}
+                // TODO Auto-generated catch block
+                LOG.warn(Messages.getMessage(Messages.READING_PROPERTIES_ERROR, name), e);
+            } finally {
+                try {
+                    props.close();
+                } catch (IOException e) {
 
-		return contextFactory;
-	}
+                    // Can be ignored
+                }
+            }
+        }
 
-	protected FacesContext getFacesContext(ServletRequest request,
-			ServletResponse response) throws FacesException {
-		return getContextFactory().getFacesContext(getServletContext(),
-				request, response, getLifecycle());
-	}
+        return properties;
+    }
 
+    /**
+     * @return Returns the servletContext.
+     */
+    protected ServletContext getServletContext() {
+        return filterConfig.getServletContext();
+    }
+
+    /**
+     * @return the lifecycle
+     * @throws ServletException
+     */
+    protected ResourceLifecycle getLifecycle() throws FacesException {
+        return lifecycle;
+    }
+
+    /**
+     * @return the contextFactory
+     */
+    protected synchronized FacesContextFactory getContextFactory() {
+        if (contextFactory == null) {
+            contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
+        }
+
+        return contextFactory;
+    }
+
+    protected FacesContext getFacesContext(ServletRequest request, ServletResponse response) throws FacesException {
+        return getContextFactory().getFacesContext(getServletContext(), request, response, getLifecycle());
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/JarResource.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/JarResource.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/JarResource.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,12 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.resource;
 
-import java.io.InputStream;
 
+package org.ajax4jsf.resource;
+
 import org.ajax4jsf.resource.util.URLToStreamHelper;
 
+import java.io.InputStream;
 
 /**
  * Class stoped all resources in application classpath.
@@ -34,40 +35,37 @@
  *
  */
 public class JarResource extends InternetResourceBase {
-	
-	/**
-	 * Default place for all static resources in Jar.
-	 * to avoid access to any class in application, only allowed subpackages for
-	 * META-INF/resources
-	 */
-	public static final String RESOURCES_ROOT="META-INF/resources";
 
-	private String path;
-	
-	public JarResource(){
-		
-	}
+    /**
+     * Default place for all static resources in Jar.
+     * to avoid access to any class in application, only allowed subpackages for
+     * META-INF/resources
+     */
+    public static final String RESOURCES_ROOT = "META-INF/resources";
+    private String path;
 
-	public JarResource(String path) {
-		this.path = path;
-	}
+    public JarResource() {}
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.InternetResourceBase#getResourceAsStream(javax.faces.context.FacesContext, java.lang.Object)
-	 */
-	public InputStream getResourceAsStream(ResourceContext context) {
-		ClassLoader loader = Thread.currentThread().getContextClassLoader();
-		return URLToStreamHelper.urlToStreamSafe(loader.getResource(path));
-	}
+    public JarResource(String path) {
+        this.path = path;
+    }
 
-	public String getPath() {
-		return path;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.InternetResourceBase#getResourceAsStream(javax.faces.context.FacesContext,
+     * java.lang.Object)
+     */
+    public InputStream getResourceAsStream(ResourceContext context) {
+        ClassLoader loader = Thread.currentThread().getContextClassLoader();
 
-	public void setPath(String path) {
-		this.path = path;
-	}
+        return URLToStreamHelper.urlToStreamSafe(loader.getResource(path));
+    }
 
+    public String getPath() {
+        return path;
+    }
 
-	
+    public void setPath(String path) {
+        this.path = path;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/Java2Dresource.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/Java2Dresource.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/Java2Dresource.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,12 +19,20 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import org.ajax4jsf.util.NumericDataInputStream;
+import org.ajax4jsf.util.NumericDataOutputStream;
+
+import org.richfaces.resource.AbstractBaseResource;
+
 import java.awt.Dimension;
 import java.awt.Graphics2D;
 import java.awt.image.BufferedImage;
 import java.awt.image.IndexColorModel;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
@@ -32,196 +40,195 @@
 
 import javax.faces.component.StateHolder;
 import javax.faces.context.FacesContext;
+
 import javax.imageio.ImageIO;
 
-import org.ajax4jsf.util.NumericDataInputStream;
-import org.ajax4jsf.util.NumericDataOutputStream;
-import org.richfaces.resource.AbstractBaseResource;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.3 $ $Date: 2007/02/01 15:31:57 $
- * 
+ *
  */
 public abstract class Java2Dresource extends AbstractBaseResource implements StateHolder {
+    private ImageType imageType;
 
-	private ImageType imageType;
-	
-	public Java2Dresource(ImageType imageType) {
-		super();
-		this.imageType = imageType;
-	}
+    public Java2Dresource(ImageType imageType) {
+        super();
+        this.imageType = imageType;
+    }
 
-	public static enum ImageType {
-		GIF("gif") {
-			@Override
-			public BufferedImage createImage(int width, int height) {
-				return createARGBImage(width, height);
-			}
-		}, 
-		PNG("png") {
-			@Override
-			public BufferedImage createImage(int width, int height) {
-				return createARGBImage(width, height);
-			}
-		}, 
-		PNG8("png") {
-			@Override
-			public BufferedImage createImage(int width, int height) {
-				return new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, 
-					SAFE_WEB_COLORS_MODEL);
-			}
-		}, 
-		
-		//TODO - add common png8
-		
-		JPEG("jpeg") {
-			@Override
-			public BufferedImage createImage(int width, int height) {
-				return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
-			}
-		};
-		
-		/**
-		 * Default web safe colors color model
-		 */
-		protected static final IndexColorModel SAFE_WEB_COLORS_MODEL;
+    public static enum ImageType {
+        GIF("gif") {
+            @Override
+            public BufferedImage createImage(int width, int height) {
+                return createARGBImage(width, height);
+            }
+        },
+        PNG("png") {
+            @Override
+            public BufferedImage createImage(int width, int height) {
+                return createARGBImage(width, height);
+            }
+        },
+        PNG8("png") {
+            @Override
+            public BufferedImage createImage(int width, int height) {
+                return new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, SAFE_WEB_COLORS_MODEL);
+            }
+        },
 
-		// Build web safe 6x6x6 cube color model.
-		static {
-			byte[] webLevels = { 0, 51, 102, (byte) 153, (byte) 204, (byte) 255 };
-			int colorsNumber = webLevels.length * webLevels.length * webLevels.length; /* 216 colors */
-			
-			byte[] r = new byte[colorsNumber];
-			byte[] g = new byte[colorsNumber];
-			byte[] b = new byte[colorsNumber];
-			r[0] = g[0] = b[0] = 0;
-			for (int i = 0; i < webLevels.length; i++) {
-				for (int j = 0; j < webLevels.length; j++) {
-					for (int k = 0; k < webLevels.length; k++) {
-						int colorNum = i * webLevels.length * webLevels.length + j
-								* webLevels.length + k;
-						r[colorNum] = webLevels[i];
-						g[colorNum] = webLevels[j];
-						b[colorNum] = webLevels[k];
-					}
-				}
-			}
-			
-			SAFE_WEB_COLORS_MODEL = new IndexColorModel(8, colorsNumber, r, g, b, 0);
-		}
+        // TODO - add common png8
+        JPEG("jpeg") {
+            @Override
+            public BufferedImage createImage(int width, int height) {
+                return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+            }
+        };
 
-		private static BufferedImage createARGBImage(int width, int height) {
-			return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
-		}
+        /**
+         * Default web safe colors color model
+         */
+        protected static final IndexColorModel SAFE_WEB_COLORS_MODEL;
 
-		private String formatName;
-		
-		private String mimeType;
-		
-		private ImageType(String formatName) {
-			this.formatName = formatName;
-			this.mimeType = "image/" + formatName;
-		}
+        // Build web safe 6x6x6 cube color model.
+        static {
+            byte[] webLevels = {
+                0, 51, 102, (byte) 153, (byte) 204, (byte) 255
+            };
+            int colorsNumber = webLevels.length * webLevels.length * webLevels.length; /* 216 colors */
+            byte[] r = new byte[colorsNumber];
+            byte[] g = new byte[colorsNumber];
+            byte[] b = new byte[colorsNumber];
 
-		protected abstract BufferedImage createImage(int width, int height);
+            r[0] = 0;
+            g[0] = 0;
+            b[0] = 0;
 
-		protected String getFormatName() {
-			return formatName;
-		}
+            for (int i = 0; i < webLevels.length; i++) {
+                for (int j = 0; j < webLevels.length; j++) {
+                    for (int k = 0; k < webLevels.length; k++) {
+                        int colorNum = i * webLevels.length * webLevels.length + j * webLevels.length + k;
 
-		protected String getMimeType() {
-			return mimeType;
-		}
-	}
-	
-	/**
-	 * Primary calculation of image dimensions - used when HTML code is
-	 * generated to render IMG's width and height Subclasses should override
-	 * this method to provide correct sizes of rendered images
-	 * 
-	 * @param facesContext
-	 * @return dimensions of the image to be displayed on page
-	 */
-	public abstract Dimension getDimension();
-	
-	/**
-	 * Template method for create image as Applet-like paint.
-	 * 
-	 * @param graphics2D -
-	 *            graphics to paint.
-	 */
-	protected void paint(Graphics2D graphics2D, Dimension dimension) {
-		// TODO Auto-generated method stub
+                        r[colorNum] = webLevels[i];
+                        g[colorNum] = webLevels[j];
+                        b[colorNum] = webLevels[k];
+                    }
+                }
+            }
 
-	}
+            SAFE_WEB_COLORS_MODEL = new IndexColorModel(8, colorsNumber, r, g, b, 0);
+        }
 
-	/* (non-Javadoc)
-	 * @see org.richfaces.resource.AbstractBaseResource#getInputStream()
-	 */
-	@Override
-	public InputStream getInputStream() {
-		Dimension dimension = getDimension();
-		int width = dimension.width;
-		int height = dimension.height;
-		
-		ByteArrayOutputStream baos = new ByteArrayOutputStream();
-		if (width > 0 && height > 0) {
-			BufferedImage image = imageType.createImage(width, height);
-			Graphics2D g2d = image.createGraphics();
-			
-			try {
-				paint(g2d, dimension);
-			} finally {
-				g2d.dispose();
-			}
-			
-			try {
-				ImageIO.write(image, imageType.getFormatName(), baos);
-			} catch (IOException e) {
-				// TODO Auto-generated catch block
-				e.printStackTrace();
-			} finally {
-				try {
-					baos.close();
-				} catch (IOException e) {
-					// TODO Auto-generated catch block
-					e.printStackTrace();
-				}
-			}
+        private String formatName;
+        private String mimeType;
 
-		}
+        private ImageType(String formatName) {
+            this.formatName = formatName;
+            this.mimeType = "image/" + formatName;
+        }
 
-		return new ByteArrayInputStream(baos.toByteArray());
-	}
+        private static BufferedImage createARGBImage(int width, int height) {
+            return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+        }
 
-	@Override
-	public String getContentType() {
-		return imageType.getMimeType();
-	}
-	
-	protected void writeState(FacesContext context, NumericDataOutputStream stream) {
-	}
-	
-	protected void readState(FacesContext context, NumericDataInputStream stream) {
-		
-	}
+        protected abstract BufferedImage createImage(int width, int height);
 
-	public boolean isTransient() {
-		return false;
-	}
+        protected String getFormatName() {
+            return formatName;
+        }
 
-	public void restoreState(FacesContext context, Object state) {
-		readState(context, new NumericDataInputStream((byte[]) state));
-	}
+        protected String getMimeType() {
+            return mimeType;
+        }
+    }
 
-	public Object saveState(FacesContext context) {
-		NumericDataOutputStream stream = new NumericDataOutputStream();
-		writeState(context, stream);
-		return stream.getBytes();
-	}
+    /**
+     * Primary calculation of image dimensions - used when HTML code is
+     * generated to render IMG's width and height Subclasses should override
+     * this method to provide correct sizes of rendered images
+     *
+     * @param facesContext
+     * @return dimensions of the image to be displayed on page
+     */
+    public abstract Dimension getDimension();
 
-	public void setTransient(boolean newTransientValue) {
-		throw new UnsupportedOperationException();
-	}
+    /**
+     * Template method for create image as Applet-like paint.
+     *
+     * @param graphics2D -
+     *            graphics to paint.
+     */
+    protected void paint(Graphics2D graphics2D, Dimension dimension) {
+
+        // TODO Auto-generated method stub
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see org.richfaces.resource.AbstractBaseResource#getInputStream()
+     */
+    @Override
+    public InputStream getInputStream() {
+        Dimension dimension = getDimension();
+        int width = dimension.width;
+        int height = dimension.height;
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+        if ((width > 0) && (height > 0)) {
+            BufferedImage image = imageType.createImage(width, height);
+            Graphics2D g2d = image.createGraphics();
+
+            try {
+                paint(g2d, dimension);
+            } finally {
+                g2d.dispose();
+            }
+
+            try {
+                ImageIO.write(image, imageType.getFormatName(), baos);
+            } catch (IOException e) {
+
+                // TODO Auto-generated catch block
+                e.printStackTrace();
+            } finally {
+                try {
+                    baos.close();
+                } catch (IOException e) {
+
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            }
+        }
+
+        return new ByteArrayInputStream(baos.toByteArray());
+    }
+
+    @Override
+    public String getContentType() {
+        return imageType.getMimeType();
+    }
+
+    protected void writeState(FacesContext context, NumericDataOutputStream stream) {}
+
+    protected void readState(FacesContext context, NumericDataInputStream stream) {}
+
+    public boolean isTransient() {
+        return false;
+    }
+
+    public void restoreState(FacesContext context, Object state) {
+        readState(context, new NumericDataInputStream((byte[]) state));
+    }
+
+    public Object saveState(FacesContext context) {
+        NumericDataOutputStream stream = new NumericDataOutputStream();
+
+        writeState(context, stream);
+
+        return stream.getBytes();
+    }
+
+    public void setTransient(boolean newTransientValue) {
+        throw new UnsupportedOperationException();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/LogfileRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/LogfileRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/LogfileRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,16 +19,15 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import javax.faces.context.FacesContext;
+
 import java.io.IOException;
 import java.io.InputStream;
 
-import javax.faces.context.FacesContext;
-
-import org.ajax4jsf.resource.InternetResource;
-import org.ajax4jsf.resource.ResourceContext;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:02 $
@@ -36,53 +35,71 @@
  */
 public class LogfileRenderer extends BaseResourceRenderer {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getTag()
-	 */
-	protected String getTag() {
-		// TODO Auto-generated method stub
-		return "pre";
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getTag()
+     */
+    @Override
+    protected String getTag() {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getHrefAttr()
-	 */
-	protected String getHrefAttr() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+        // TODO Auto-generated method stub
+        return "pre";
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getCommonAttrs()
-	 */
-	protected String[][] getCommonAttrs() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getHrefAttr()
+     */
+    @Override
+    protected String getHrefAttr() {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceRenderer#getContentType()
-	 */
-	public String getContentType() {
-		// TODO Auto-generated method stub
-		return "text/plain";
-	}
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#customEncode(org.ajax4jsf.resource.InternetResource, javax.faces.context.FacesContext, java.lang.Object)
-	 */
-	protected void customEncode(InternetResource resource, FacesContext context, Object data) throws IOException {
-		// Encode style in page - read from resource.
-		ResourceContext resourceContext = new FacesResourceContext(context);
-		InputStream in = resource.getResourceAsStream(resourceContext);
-		StringBuffer buff = new StringBuffer();
-		int input;
-		while((input = in.read())>0){
-			buff.append((char)input);
-		}
-		in.close();
-		//  MyFaces & RI have different beahvior for style element, in RI best use writeComment ?
-		// TODO - detect page content type ?
-		context.getResponseWriter().writeText(buff,resource.getKey());
-	}
+        // TODO Auto-generated method stub
+        return null;
+    }
 
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getCommonAttrs()
+     */
+    @Override
+    protected String[][] getCommonAttrs() {
+
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceRenderer#getContentType()
+     */
+    public String getContentType() {
+
+        // TODO Auto-generated method stub
+        return "text/plain";
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#customEncode(org.ajax4jsf.resource.InternetResource,
+     * javax.faces.context.FacesContext, java.lang.Object)
+     */
+    @Override
+    protected void customEncode(InternetResource resource, FacesContext context, Object data) throws IOException {
+
+        // Encode style in page - read from resource.
+        ResourceContext resourceContext = new FacesResourceContext(context);
+        InputStream in = resource.getResourceAsStream(resourceContext);
+        StringBuffer buff = new StringBuffer();
+        int input;
+
+        while ((input = in.read()) > 0) {
+            buff.append((char) input);
+        }
+
+        in.close();
+
+        // MyFaces & RI have different beahvior for style element, in RI best use writeComment ?
+        // TODO - detect page content type ?
+        context.getResponseWriter().writeText(buff, resource.getKey());
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/MimeRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/MimeRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/MimeRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,48 +19,49 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
-
 /**
  * @author Nick Belaevski - nbelaevski at exadel.com
  * created 20.11.2006
- * 
+ *
  */
 public class MimeRenderer extends BaseResourceRenderer {
-	
-	private String contentType = null;
-	
-	public MimeRenderer() {
-		
-	}
-	
-	public MimeRenderer(String contentType) {
-		super();
-		this.contentType = contentType;
-	}
+    private String contentType = null;
 
-	public String getContentType() {
-		return this.contentType;
-	}
+    public MimeRenderer() {}
 
-	public void setContentType(String contentType) {
-		this.contentType = contentType;
-	}
-	
-	
+    public MimeRenderer(String contentType) {
+        super();
+        this.contentType = contentType;
+    }
 
-	protected String getTag() {
-		return null;
-	}
+    public String getContentType() {
+        return this.contentType;
+    }
 
-	protected String[][] getCommonAttrs() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+    public void setContentType(String contentType) {
+        this.contentType = contentType;
+    }
 
-	protected String getHrefAttr() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+    @Override
+    protected String getTag() {
+        return null;
+    }
+
+    @Override
+    protected String[][] getCommonAttrs() {
+
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    protected String getHrefAttr() {
+
+        // TODO Auto-generated method stub
+        return null;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/OneTimeRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/OneTimeRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/OneTimeRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,17 +19,22 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import org.ajax4jsf.Messages;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
+
 import java.util.Map;
 
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.Messages;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * Base class for resources, rendered only one time in page ( JavaScript, CSS )
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
@@ -37,43 +42,53 @@
  *
  */
 public abstract class OneTimeRenderer extends BaseResourceRenderer {
+    private static final Logger LOG = RichfacesLogger.RESOURCE.getLogger();
 
-	private static final Logger log = RichfacesLogger.RESOURCE.getLogger();
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#encodeBegin(org.ajax4jsf.resource.InternetResource, javax.faces.context.FacesContext, java.lang.Object, java.util.Map)
-	 */
-	public void encodeBegin(InternetResource resource, FacesContext context, Object data, Map<String,Object> attributes) throws IOException {
-		
-		if (!isRendered(resource,context)) {
-			super.encodeBegin(resource, context, data, attributes);
-		} else if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.SKIP_ENCODE_BEGIN_HTML_INFO_2, resource.getKey()));
-		}
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#encodeBegin(org.ajax4jsf.resource.InternetResource,
+     * javax.faces.context.FacesContext, java.lang.Object, java.util.Map)
+     */
+    @Override
+    public void encodeBegin(InternetResource resource, FacesContext context, Object data,
+            Map<String, Object> attributes) throws IOException {
+        
+        if (!isRendered(resource, context)) {
+            super.encodeBegin(resource, context, data, attributes);
+        } else if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.SKIP_ENCODE_BEGIN_HTML_INFO_2, resource.getKey()));
+        }
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#encodeEnd(org.ajax4jsf.resource.InternetResource, javax.faces.context.FacesContext, java.lang.Object)
-	 */
-	public void encodeEnd(InternetResource resource, FacesContext context, Object data) throws IOException {
-		// TODO Auto-generated method stub
-		if (!isRendered(resource,context)) {
-			super.encodeEnd(resource, context, data);
-			context.getExternalContext().getRequestMap().put(resource.getKey(),Boolean.TRUE);
-			if (log.isDebugEnabled()) {
-					log.debug(Messages.getMessage(Messages.MARK_AS_RENDERED_INFO, resource.getKey()));
-			}
-		} else if (log.isDebugEnabled()) {
-			log.debug(Messages.getMessage(Messages.SKIP_ENCODE_END_HTML_INFO_2, resource.getKey()));
-		}
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#encodeEnd(org.ajax4jsf.resource.InternetResource,
+     * javax.faces.context.FacesContext, java.lang.Object)
+     *
+     */
+    @Override
+    public void encodeEnd(InternetResource resource, FacesContext context, Object data) throws IOException {
 
-	/**
-	 * Detect for resource rendered status. For cacheable, show key parameter in request Map.
-	 * @param resource
-	 * @param context
-	 * @return - true, if resource already rendered.
-	 */
-	private boolean isRendered(InternetResource resource, FacesContext context){
-		return  null != context.getExternalContext().getRequestMap().get(resource.getKey()); // resource.isCacheable() &&
-	}
+        // TODO Auto-generated method stub
+        if (!isRendered(resource, context)) {
+            super.encodeEnd(resource, context, data);
+            context.getExternalContext().getRequestMap().put(resource.getKey(), Boolean.TRUE);
+
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.MARK_AS_RENDERED_INFO, resource.getKey()));
+            }
+        } else if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.SKIP_ENCODE_END_HTML_INFO_2, resource.getKey()));
+        }
+    }
+
+    /**
+     * Detect for resource rendered status. For cacheable, show key parameter in request Map.
+     * @param resource
+     * @param context
+     * @return - true, if resource already rendered.
+     */
+    private boolean isRendered(InternetResource resource, FacesContext context) {
+        return null != context.getExternalContext().getRequestMap().get(resource.getKey()); // resource.isCacheable() &&
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ResourceLifecycle.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ResourceLifecycle.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ResourceLifecycle.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,9 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
+
 import java.util.Locale;
 
 import javax.faces.FacesException;
@@ -35,195 +42,204 @@
 import javax.faces.lifecycle.LifecycleFactory;
 import javax.faces.render.RenderKitFactory;
 
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * Lifecycle for simulate faces request processing for resource.
- * 
+ *
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:56:56 $
- * 
+ *
  */
 public class ResourceLifecycle extends Lifecycle {
+    private static final Logger LOG = RichfacesLogger.RESOURCE.getLogger();
+    private Lifecycle lifecycle;
 
-	private Lifecycle lifecycle;
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#addPhaseListener(javax.faces.event.PhaseListener)
+     */
+    @Override
+    public void addPhaseListener(PhaseListener arg0) {
 
-	private static final Logger _log = RichfacesLogger.RESOURCE.getLogger();
+        // TODO Auto-generated method stub
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#addPhaseListener(javax.faces.event.PhaseListener)
-	 */
-	public void addPhaseListener(PhaseListener arg0) {
-		// TODO Auto-generated method stub
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#execute(javax.faces.context.FacesContext)
+     */
+    @Override
+    public void execute(FacesContext arg0) throws FacesException {
 
-	}
+        // TODO Auto-generated method stub
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#execute(javax.faces.context.FacesContext)
-	 */
-	public void execute(FacesContext arg0) throws FacesException {
-		// TODO Auto-generated method stub
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#getPhaseListeners()
+     */
+    @Override
+    public PhaseListener[] getPhaseListeners() {
 
-	}
+        // TODO Auto-generated method stub
+        return null;
+    }
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#getPhaseListeners()
-	 */
-	public PhaseListener[] getPhaseListeners() {
-		// TODO Auto-generated method stub
-		return null;
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#removePhaseListener(javax.faces.event.PhaseListener)
+     */
+    @Override
+    public void removePhaseListener(PhaseListener arg0) {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#removePhaseListener(javax.faces.event.PhaseListener)
-	 */
-	public void removePhaseListener(PhaseListener arg0) {
-		// TODO Auto-generated method stub
+        // TODO Auto-generated method stub
+    }
 
-	}
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.faces.lifecycle.Lifecycle#render(javax.faces.context.FacesContext)
+     */
+    @Override
+    public void render(FacesContext arg0) throws FacesException {
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see javax.faces.lifecycle.Lifecycle#render(javax.faces.context.FacesContext)
-	 */
-	public void render(FacesContext arg0) throws FacesException {
-		// TODO Auto-generated method stub
+        // TODO Auto-generated method stub
+    }
 
-	}
+    /**
+     * @param context
+     * @param resource
+     * @throws IOException
+     */
+    public void send(ResourceContext resourceContext, InternetResource resource) throws IOException {
+        FacesContext facesContext = FacesContext.getCurrentInstance();
 
-	/**
-	 * @param context
-	 * @param resource
-	 * @throws IOException
-	 */
-	public void send(ResourceContext resourceContext, InternetResource resource)
-			throws IOException {
-		FacesContext facesContext = FacesContext.getCurrentInstance();
-		if (null != facesContext) {
-			Lifecycle facesLifecycle = getFacesLifecycle();
-			PhaseListener[] phaseListeners = facesLifecycle.getPhaseListeners();
-			PhaseEvent restoreViewEvent = new PhaseEvent(facesContext,
-					PhaseId.RESTORE_VIEW, this);
-			processPhaseListeners(phaseListeners, restoreViewEvent, true);
-			// Fix for a http://jira.jboss.org/jira/browse/RF-1056
-			if (facesContext.getResponseComplete()) {
-				return;
-			}
-			// fix for a http://jira.jboss.com/jira/browse/RF-1064 .
-			// viewRoot can be created outside.
-			UIViewRoot savedViewRoot = facesContext.getViewRoot();
-			try {
-				// create "dummy" viewRoot, to avoid problems in phase listeners.
-				UIViewRoot root = new UIViewRoot();
-				String key = resource.getKey();
-				if (null != key && !key.startsWith("/")) {
-					key = "/" + key;
-				}
-				root.setViewId(key);
-				root.setLocale(Locale.getDefault());
-				root.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
-				facesContext.setViewRoot(root);
-				// Invoke after restore view phase listeners
-				processPhaseListeners(phaseListeners, restoreViewEvent, false);
-				// Fix for a http://jira.jboss.org/jira/browse/RF-1056
-				if (!facesContext.getResponseComplete()) {
-					// Invoke before render view phase listeners
-			        PhaseEvent renderViewEvent = new PhaseEvent(facesContext,
-							PhaseId.RENDER_RESPONSE, this);
-					processPhaseListeners(phaseListeners, renderViewEvent, true);
-					sendResource(resourceContext, resource);
-					processPhaseListeners(phaseListeners, renderViewEvent, false);
-				}
+        if (null != facesContext) {
+            Lifecycle facesLifecycle = getFacesLifecycle();
+            PhaseListener[] phaseListeners = facesLifecycle.getPhaseListeners();
+            PhaseEvent restoreViewEvent = new PhaseEvent(facesContext, PhaseId.RESTORE_VIEW, this);
 
-			} finally {
-				if (null != savedViewRoot) {
-					facesContext.setViewRoot(savedViewRoot);
-				}
-			}
-		} else {
-			sendResource(resourceContext, resource);
-		}
-	}
+            processPhaseListeners(phaseListeners, restoreViewEvent, true);
 
-	/**
-	 * Send phase event to all apropriate PhaseListener's
-	 * 
-	 * @param phaseListeners
-	 * @param phaseEvent
-	 * @param beforePhase
-	 *            TODO
-	 */
-	private void processPhaseListeners(PhaseListener[] phaseListeners,
-			PhaseEvent phaseEvent, boolean beforePhase) {
-		if (beforePhase) {
-			// Invoke before phase listeners
-			for (int i = 0; i < phaseListeners.length; i++) {
-				PhaseListener phaseListener = phaseListeners[i];
-				invokePhaseListener(phaseListener, phaseEvent, beforePhase);
-			}
+            // Fix for a http://jira.jboss.org/jira/browse/RF-1056
+            if (facesContext.getResponseComplete()) {
+                return;
+            }
 
-		} else {
-			// Invoke after phase listeners, in reverse order.
-			for (int i = phaseListeners.length - 1; i >= 0; i--) {
-				PhaseListener phaseListener = phaseListeners[i];
-				invokePhaseListener(phaseListener, phaseEvent, beforePhase);
-			}
+            // fix for a http://jira.jboss.com/jira/browse/RF-1064 .
+            // viewRoot can be created outside.
+            UIViewRoot savedViewRoot = facesContext.getViewRoot();
 
-		}
-	}
+            try {
 
-	/**
-	 * @param phaseListener
-	 * @param phaseEvent
-	 * @param beforePhase
-	 */
-	private void invokePhaseListener(PhaseListener phaseListener,
-			PhaseEvent phaseEvent, boolean beforePhase) {
-		if (phaseEvent.getPhaseId().equals(phaseListener.getPhaseId())
-				|| PhaseId.ANY_PHASE.equals(phaseListener.getPhaseId())) {
-			try {
-				if (beforePhase) {
-					phaseListener.beforePhase(phaseEvent);
-				} else {
-					phaseListener.afterPhase(phaseEvent);
-				}
-			} catch (Exception e) {
-				_log.debug("Exception in PhaseListener, phase :" + phaseEvent.getPhaseId().toString()
-							+ (beforePhase ? " : beforePhase" : " : afterPhase"), e);
-			}
-		}
-	}
+                // create "dummy" viewRoot, to avoid problems in phase listeners.
+                UIViewRoot root = new UIViewRoot();
+                String key = resource.getKey();
 
-	/**
-	 * @param resourceContext
-	 * @param resource
-	 * @throws IOException
-	 */
-	private void sendResource(ResourceContext resourceContext,
-			InternetResource resource) throws IOException {
-		resource.sendHeaders(resourceContext);
-		resource.send(resourceContext);
-	}
+                if ((null != key) && !key.startsWith("/")) {
+                    key = "/" + key;
+                }
 
-	protected synchronized Lifecycle getFacesLifecycle() {
-		if (lifecycle == null) {
-			// Acquire our Lifecycle instance
-			LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
-					.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
-			lifecycle = lifecycleFactory
-					.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
-		}
+                root.setViewId(key);
+                root.setLocale(Locale.getDefault());
+                root.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
+                facesContext.setViewRoot(root);
 
-		return lifecycle;
-	}
+                // Invoke after restore view phase listeners
+                processPhaseListeners(phaseListeners, restoreViewEvent, false);
+
+                // Fix for a http://jira.jboss.org/jira/browse/RF-1056
+                if (!facesContext.getResponseComplete()) {
+
+                    // Invoke before render view phase listeners
+                    PhaseEvent renderViewEvent = new PhaseEvent(facesContext, PhaseId.RENDER_RESPONSE, this);
+
+                    processPhaseListeners(phaseListeners, renderViewEvent, true);
+                    sendResource(resourceContext, resource);
+                    processPhaseListeners(phaseListeners, renderViewEvent, false);
+                }
+            } finally {
+                if (null != savedViewRoot) {
+                    facesContext.setViewRoot(savedViewRoot);
+                }
+            }
+        } else {
+            sendResource(resourceContext, resource);
+        }
+    }
+
+    /**
+     * Send phase event to all apropriate PhaseListener's
+     *
+     * @param phaseListeners
+     * @param phaseEvent
+     * @param beforePhase
+     *            TODO
+     */
+    private void processPhaseListeners(PhaseListener[] phaseListeners, PhaseEvent phaseEvent, boolean beforePhase) {
+        if (beforePhase) {
+
+            // Invoke before phase listeners
+            for (int i = 0; i < phaseListeners.length; i++) {
+                PhaseListener phaseListener = phaseListeners[i];
+
+                invokePhaseListener(phaseListener, phaseEvent, beforePhase);
+            }
+        } else {
+
+            // Invoke after phase listeners, in reverse order.
+            for (int i = phaseListeners.length - 1; i >= 0; i--) {
+                PhaseListener phaseListener = phaseListeners[i];
+
+                invokePhaseListener(phaseListener, phaseEvent, beforePhase);
+            }
+        }
+    }
+
+    /**
+     * @param phaseListener
+     * @param phaseEvent
+     * @param beforePhase
+     */
+    private void invokePhaseListener(PhaseListener phaseListener, PhaseEvent phaseEvent, boolean beforePhase) {
+        if (phaseEvent.getPhaseId().equals(phaseListener.getPhaseId())
+                || PhaseId.ANY_PHASE.equals(phaseListener.getPhaseId())) {
+            try {
+                if (beforePhase) {
+                    phaseListener.beforePhase(phaseEvent);
+                } else {
+                    phaseListener.afterPhase(phaseEvent);
+                }
+            } catch (Exception e) {
+                LOG.debug("Exception in PhaseListener, phase :" + phaseEvent.getPhaseId().toString()
+                          + (beforePhase ? " : beforePhase" : " : afterPhase"), e);
+            }
+        }
+    }
+
+    /**
+     * @param resourceContext
+     * @param resource
+     * @throws IOException
+     */
+    private void sendResource(ResourceContext resourceContext, InternetResource resource) throws IOException {
+        resource.sendHeaders(resourceContext);
+        resource.send(resourceContext);
+    }
+
+    protected synchronized Lifecycle getFacesLifecycle() {
+        if (lifecycle == null) {
+
+            // Acquire our Lifecycle instance
+            LifecycleFactory lifecycleFactory =
+                (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
+
+            lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
+        }
+
+        return lifecycle;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ScriptRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ScriptRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ScriptRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,98 +19,109 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
 import org.ajax4jsf.Messages;
 import org.ajax4jsf.javascript.JSMin;
+
 import org.richfaces.log.RichfacesLogger;
+
 import org.slf4j.Logger;
 
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+class CountingOutputStream extends OutputStream {
+    private int written = 0;
+    private OutputStream outputStream;
+
+    CountingOutputStream(OutputStream outputStream) {
+        super();
+        this.outputStream = outputStream;
+    }
+
+    public void close() throws IOException {
+        outputStream.close();
+    }
+
+    public void flush() throws IOException {
+        outputStream.flush();
+    }
+
+    public void write(byte[] b, int off, int len) throws IOException {
+        outputStream.write(b, off, len);
+        written += len;
+    }
+
+    public void write(byte[] b) throws IOException {
+        outputStream.write(b);
+        written += b.length;
+    }
+
+    public void write(int b) throws IOException {
+        outputStream.write(b);
+        written++;
+    }
+
+    int getWritten() {
+        return written;
+    }
+}
+
+
 /**
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:04 $
  *
  */
 public class ScriptRenderer extends CompressedScriptRenderer {
+    private static final String COMPRESS_SCRIPTS_PARAMETER = "org.ajax4jsf.COMPRESS_SCRIPT";
+    private static final Logger LOG = RichfacesLogger.RESOURCE.getLogger();
 
-	private static final String COMPRESS_SCRIPTS_PARAMETER = "org.ajax4jsf.COMPRESS_SCRIPT";
-	
-	private static final Logger _log = RichfacesLogger.RESOURCE.getLogger();
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#send(org.ajax4jsf.resource.InternetResource,
+     * org.ajax4jsf.resource.ResourceContext)
+     */
+    @Override
+    public int send(InternetResource base, ResourceContext context) throws IOException {
+        InputStream in = base.getResourceAsStream(context);
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#send(org.ajax4jsf.resource.InternetResource, org.ajax4jsf.resource.ResourceContext)
-	 */
-	public int send(InternetResource base, ResourceContext context) throws IOException {
-		InputStream in = base.getResourceAsStream(context);
-		if (null == in) {
-			String message = Messages.getMessage(
-					Messages.NO_INPUT_STREAM_ERROR, base.getKey());
-			throw new IOException(message);
-		}
-		OutputStream out = context.getOutputStream();
-		// Compress JavaScript output by JSMin ( true by default )
-		if( ! "false".equalsIgnoreCase(context.getInitParameter(COMPRESS_SCRIPTS_PARAMETER))){
-			CountingOutputStream countingStream = new CountingOutputStream(out);
-			JSMin jsmin = new JSMin(in,countingStream);
-			try {
-				jsmin.jsmin();
-			} catch (Exception e) {
-				_log.error("Error send script to client for resource "+base.getKey(), e);
-			} finally {
-				in.close();
-				countingStream.flush();
-				countingStream.close();
-			}
-			int written = countingStream.getWritten();
-			if(_log.isDebugEnabled()){
-				_log.debug("Send "+written+" bytes to client for JavaScript resource "+base.getKey());
-			}
-			return written;
-		} else {
-			return sendStream(in, out);
-		}
-	}
+        if (null == in) {
+            String message = Messages.getMessage(Messages.NO_INPUT_STREAM_ERROR, base.getKey());
 
-	
-}
+            throw new IOException(message);
+        }
 
-class CountingOutputStream extends OutputStream {
-	private OutputStream outputStream;
-	private int written = 0;
-	
-	CountingOutputStream(OutputStream outputStream) {
-		super();
-		this.outputStream = outputStream;
-	}
+        OutputStream out = context.getOutputStream();
 
-	public void close() throws IOException {
-		outputStream.close();
-	}
+        // Compress JavaScript output by JSMin ( true by default )
+        if (!"false".equalsIgnoreCase(context.getInitParameter(COMPRESS_SCRIPTS_PARAMETER))) {
+            CountingOutputStream countingStream = new CountingOutputStream(out);
+            JSMin jsmin = new JSMin(in, countingStream);
 
-	public void flush() throws IOException {
-		outputStream.flush();
-	}
+            try {
+                jsmin.jsmin();
+            } catch (Exception e) {
+                LOG.error("Error send script to client for resource " + base.getKey(), e);
+            } finally {
+                in.close();
+                countingStream.flush();
+                countingStream.close();
+            }
 
-	public void write(byte[] b, int off, int len) throws IOException {
-		outputStream.write(b, off, len);
-		written += len;
-	}
+            int written = countingStream.getWritten();
 
-	public void write(byte[] b) throws IOException {
-		outputStream.write(b);
-		written += b.length;
-	}
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Send " + written + " bytes to client for JavaScript resource " + base.getKey());
+            }
 
-	public void write(int b) throws IOException {
-		outputStream.write(b);
-		written++;
-	}
-
-	int getWritten() {
-		return written;
-	}
+            return written;
+        } else {
+            return sendStream(in, out);
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ServletResourceContext.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ServletResourceContext.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/ServletResourceContext.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,161 +19,186 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.PrintWriter;
+
 import java.net.MalformedURLException;
 import java.net.URL;
+
 import java.util.Set;
 
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.ajax4jsf.resource.ResourceContext;
-
-
 /**
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:01 $
  *
  */
 public class ServletResourceContext extends ResourceContext {
-	
-	private ServletContext context;
-	private HttpServletRequest request;
-	
-	private HttpServletResponse response;
+    private ServletContext context;
+    private HttpServletRequest request;
+    private HttpServletResponse response;
 
-	/**
-	 * @param request
-	 * @param response
-	 */
-	public ServletResourceContext(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
-		this.context = context;
-		this.request = request;
-		this.response = response;
-	}
+    /**
+     * @param request
+     * @param response
+     */
+    public ServletResourceContext(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
+        this.context = context;
+        this.request = request;
+        this.response = response;
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#setHeader(java.lang.String, java.lang.String)
-	 */
-	public void setHeader(String name, String value) {
-		response.setHeader(name,value);
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#setHeader(java.lang.String, java.lang.String)
+     */
+    @Override
+    public void setHeader(String name, String value) {
+        response.setHeader(name, value);
+    }
 
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#setIntHeader(java.lang.String, int)
+     */
+    public void setIntHeader(String name, int value) {
+        response.setIntHeader(name, value);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#setIntHeader(java.lang.String, int)
-	 */
-	public void setIntHeader(String name, int value) {
-		response.setIntHeader(name,value);
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#setDateHeader(java.lang.String, long)
+     */
+    @Override
+    public void setDateHeader(String name, long value) {
+        response.setDateHeader(name, value);
+    }
 
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getOutputStream()
+     */
+    @Override
+    public OutputStream getOutputStream() throws IOException {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#setDateHeader(java.lang.String, long)
-	 */
-	public void setDateHeader(String name, long value) {
-		response.setDateHeader(name,value);
+        // TODO Auto-generated method stub
+        return response.getOutputStream();
+    }
 
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getQueryString()
+     */
+    @Override
+    public String getQueryString() {
+        return request.getQueryString();
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getOutputStream()
-	 */
-	public OutputStream getOutputStream() throws IOException {
-		// TODO Auto-generated method stub
-		return response.getOutputStream();
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getPathInfo()
+     */
+    @Override
+    public String getPathInfo() {
+        return request.getPathInfo();
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getQueryString()
-	 */
-	public String getQueryString() {
-		return request.getQueryString();
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getSessionAttribute(java.lang.String)
+     */
+    @Override
+    public Object getSessionAttribute(String name) {
+        return request.getSession(false).getAttribute(name);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getPathInfo()
-	 */
-	public String getPathInfo() {
-		return request.getPathInfo();
-	}
+    /**
+     * @param name
+     * @return
+     * @see javax.servlet.ServletContext#getAttribute(java.lang.String)
+     */
+    @Override
+    public Object getContextAttribute(String name) {
+        return context.getAttribute(name);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getSessionAttribute(java.lang.String)
-	 */
-	public Object getSessionAttribute(String name) {
-		return request.getSession(false).getAttribute(name);
-	}
+    /**
+     * @param path
+     * @return
+     * @throws MalformedURLException
+     * @see javax.servlet.ServletContext#getResource(java.lang.String)
+     */
+    @Override
+    public URL getResource(String path) throws MalformedURLException {
+        return context.getResource(path);
+    }
 
-	/**
-	 * @param name
-	 * @return
-	 * @see javax.servlet.ServletContext#getAttribute(java.lang.String)
-	 */
-	public Object getContextAttribute(String name) {
-		return context.getAttribute(name);
-	}
+    /**
+     * @param path
+     * @return
+     * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String)
+     */
+    @Override
+    @SuppressWarnings("unchecked")
+    public Set getResourcePaths(String path) {
+        return context.getResourcePaths(path);
+    }
 
-	/**
-	 * @param path
-	 * @return
-	 * @throws MalformedURLException
-	 * @see javax.servlet.ServletContext#getResource(java.lang.String)
-	 */
-	public URL getResource(String path) throws MalformedURLException {
-		return context.getResource(path);
-	}
+    @Override
+    public InputStream getResourceAsStream(String path) {
 
-	/**
-	 * @param path
-	 * @return
-	 * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String)
-	 */
-	@SuppressWarnings("unchecked")
-    public Set getResourcePaths(String path) {
-		return context.getResourcePaths(path);
-	}
+        // TODO Auto-generated method stub
+        return context.getResourceAsStream(path);
+    }
 
-	public InputStream getResourceAsStream(String path) {
-		// TODO Auto-generated method stub
-		return context.getResourceAsStream(path);
-	}
+    @Override
+    public String getRequestParameter(String dataParameter) {
 
-	public String getRequestParameter(String data_parameter) {
-		// TODO Auto-generated method stub
-		return request.getParameter(data_parameter);
-	}
+        // TODO Auto-generated method stub
+        return request.getParameter(dataParameter);
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceContext#getWriter()
-	 */
-	public PrintWriter getWriter() throws IOException {
-		// TODO Auto-generated method stub
-		return response.getWriter();
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceContext#getWriter()
+     */
+    @Override
+    public PrintWriter getWriter() throws IOException {
 
-	public void setContentType(String contentType) {
-		response.setContentType(contentType);		
-	}
+        // TODO Auto-generated method stub
+        return response.getWriter();
+    }
 
-	public void setContentLength(int contentLength) {
-		response.setContentLength(contentLength);
-	}
-	
-	public String getInitParameter(String name) {
-		// TODO Auto-generated method stub
-		return context.getInitParameter(name);
-	}
+    @Override
+    public void setContentType(String contentType) {
+        response.setContentType(contentType);
+    }
 
-	public String getServletPath() {
-		// TODO Auto-generated method stub
-		return request.getServletPath();
-	}
+    @Override
+    public void setContentLength(int contentLength) {
+        response.setContentLength(contentLength);
+    }
 
+    @Override
+    public String getInitParameter(String name) {
+
+        // TODO Auto-generated method stub
+        return context.getInitParameter(name);
+    }
+
+    @Override
+    public String getServletPath() {
+
+        // TODO Auto-generated method stub
+        return request.getServletPath();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/StaticResource.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/StaticResource.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/StaticResource.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,13 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.resource;
 
-import java.io.InputStream;
 
+package org.ajax4jsf.resource;
+
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.resource.ResourceContext;
+import java.io.InputStream;
 
 /**
  * @author asmirnov at exadel.com (latest modification by $Author: nick_belaevski $)
@@ -33,67 +33,61 @@
  *
  */
 public class StaticResource extends InternetResourceBase {
-	
-	private String path;
-	//private byte[] resourceData = null;
-	
-	/**
-	 * 
-	 */
-	public StaticResource() {
-		super();
-	}
+    private String path;
 
+    // private byte[] resourceData = null;
 
+    /**
+     *
+     */
+    public StaticResource() {
+        super();
+    }
 
-	public StaticResource(String path){
-		this.path = path;
-		setCacheable(true);
-	}
+    public StaticResource(String path) {
+        this.path = path;
+        setCacheable(true);
+    }
 
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.InternetResourceBase#getResourceAsStream(javax.faces.context.FacesContext,
+     * javax.faces.component.UIComponent)
+     */
+    @Override
+    public InputStream getResourceAsStream(ResourceContext context) {
+        return context.getResourceAsStream(path);
+    }
 
-	
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.InternetResourceBase#getResourceAsStream(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
-	 */
-	public InputStream getResourceAsStream(ResourceContext context) {
-		return context.getResourceAsStream(path);
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.InternetResourceBase#isCacheable()
+     */
+    @Override
+    public boolean isCacheable(ResourceContext resourceContext) {
+        return true;
+    }
 
+    @Override
+    public String getUri(FacesContext context, Object data) {
 
+        // perform all encodings, suitable for JSF specification.
+        String src = context.getApplication().getViewHandler().getResourceURL(context, path);
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.InternetResourceBase#isCacheable()
-	 */
-	public boolean isCacheable(ResourceContext resourceContext) {
-		return true;
-	}
+        return context.getExternalContext().encodeResourceURL(src);
+    }
 
+    /**
+     * @return the path
+     */
+    public String getPath() {
+        return path;
+    }
 
-
-	public String getUri(FacesContext context, Object data) {
-		// perform all encodings, suitable for JSF specification.
-		String src = context.getApplication().getViewHandler().getResourceURL(context,path);		
-		return context.getExternalContext().encodeResourceURL(src);
-	}
-
-
-
-
-	/**
-	 * @return the path
-	 */
-	public String getPath() {
-		return path;
-	}
-
-
-
-	/**
-	 * @param path the path to set
-	 */
-	public void setPath(String path) {
-		this.path = path;
-	}
-
+    /**
+     * @param path the path to set
+     */
+    public void setPath(String path) {
+        this.path = path;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/StyleRenderer.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/StyleRenderer.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/StyleRenderer.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,9 +19,10 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
-
 /**
  * Render style element with content in page. Warning - not use for head link element,
  * it must be rendered separate.
@@ -31,52 +32,61 @@
  */
 public class StyleRenderer extends OneTimeRenderer {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getTag()
-	 */
-	protected String getTag() {
-		return "link";
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getTag()
+     */
+    protected String getTag() {
+        return "link";
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getHrefAttr()
-	 */
-	protected String getHrefAttr() {
-		return "href";
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getHrefAttr()
+     */
+    protected String getHrefAttr() {
+        return "href";
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#getCommonAttrs()
-	 */
-	protected String[][] getCommonAttrs() {
-		return new String[][]{{"type","text/css"},{"rel","stylesheet"}};
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#getCommonAttrs()
+     */
+    protected String[][] getCommonAttrs() {
+        return new String[][] {
+            {"type", "text/css"}, {"rel", "stylesheet"}
+        };
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.ResourceRenderer#getContentType()
-	 */
-	public String getContentType() {
-		// TODO use configurable encoding ?
-		return "text/css";
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.ResourceRenderer#getContentType()
+     */
+    public String getContentType() {
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.BaseResourceRenderer#customEncode(org.ajax4jsf.resource.InternetResource, javax.faces.context.FacesContext, java.lang.Object)
-	 */
-	/*
-	protected void customEncode(InternetResource resource, FacesContext context, Object data) throws IOException {
-		// Encode style in page - read from resource.
-		ResourceContext resourceContext = new FacesResourceContext(context);
-		InputStream in = resource.getResourceAsStream(resourceContext);
-		StringBuffer buff = new StringBuffer();
-		int input;
-		while((input = in.read())>0){
-			buff.append((char)input);
-		}
-		in.close();
-		//  MyFaces & RI have different beahvior for style element, in RI best use writeComment ?
-		// TODO - detect page content type ?
-		context.getResponseWriter().writeText(buff,resource.getKey());
-	}
-*/
+        // TODO use configurable encoding ?
+        return "text/css";
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.BaseResourceRenderer#customEncode(org.ajax4jsf.resource.InternetResource, javax.faces.context.FacesContext, java.lang.Object)
+     */
+
+    /*
+     * protected void customEncode(InternetResource resource, FacesContext context, Object data) throws IOException {
+     *   // Encode style in page - read from resource.
+     *   ResourceContext resourceContext = new FacesResourceContext(context);
+     *   InputStream in = resource.getResourceAsStream(resourceContext);
+     *   StringBuffer buff = new StringBuffer();
+     *   int input;
+     *   while((input = in.read())>0){
+     *       buff.append((char)input);
+     *   }
+     *   in.close();
+     *   //  MyFaces & RI have different beahvior for style element, in RI best use writeComment ?
+     *   // TODO - detect page content type ?
+     *   context.getResponseWriter().writeText(buff,resource.getKey());
+     * }
+     */
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/URIInternetResource.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/URIInternetResource.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/URIInternetResource.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,33 +19,32 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
 import javax.faces.context.FacesContext;
 
-
 public class URIInternetResource extends InternetResourceBase {
-	
-	public URIInternetResource() {
-		super();
-	}
-	
-	public URIInternetResource(String uri) {
-		super();
-		
-		setUri(uri);
-	}
-	
-	public String getUri() {
-		return getKey();
-	}
+    public URIInternetResource() {
+        super();
+    }
 
-	public void setUri(String uri) {
-		setKey(uri);
-	}
-	
-	@Override
-	public String getUri(FacesContext context, Object data) {
-		return getUri();
-	}
-}
\ No newline at end of file
+    public URIInternetResource(String uri) {
+        super();
+        setUri(uri);
+    }
+
+    public String getUri() {
+        return getKey();
+    }
+
+    public void setUri(String uri) {
+        setKey(uri);
+    }
+
+    @Override
+    public String getUri(FacesContext context, Object data) {
+        return getUri();
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/UserResource.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/UserResource.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/UserResource.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,16 +19,20 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource;
 
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.Serializable;
+
 import java.util.Date;
 
 import javax.el.ELContext;
 import javax.el.MethodExpression;
 import javax.el.ValueExpression;
+
 import javax.faces.component.UIComponent;
 import javax.faces.component.UIComponentBase;
 import javax.faces.context.FacesContext;
@@ -38,138 +42,197 @@
  *
  */
 public class UserResource extends InternetResourceBase {
+    private String contentType;
 
-	private String contentType;
-	/**
-	 * 
-	 */
-	public UserResource(boolean cacheable, boolean session, String mime) {
-		super();		
-		setCacheable(cacheable);
-		setSessionAware(session);
-		setContentType(mime);
-	}
-	/**
-	 * @return Returns the contentType.
-	 */
-	public String getContentType(ResourceContext resourceContext) {
-		return contentType;
-	}
-	/**
-	 * @param contentType The contentType to set.
-	 */
-	public void setContentType(String contentType) {
-		this.contentType = contentType;
-	}
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.InternetResourceBase#getDataToStore(javax.faces.context.FacesContext, java.lang.Object)
-	 */
-	public Object getDataToStore(FacesContext context, Object data) {
-		UriData dataToStore = null;
-		if (data instanceof ResourceComponent2) {
-			ResourceComponent2 resource = (ResourceComponent2) data;
-			dataToStore = new UriData();
-			dataToStore.value = resource.getValue();
-			dataToStore.createContent = UIComponentBase.saveAttachedState(context,resource.getCreateContentExpression());
-			if (data instanceof UIComponent) {
-				UIComponent component = (UIComponent) data;
-				ValueExpression expires = component.getValueExpression("expires");
-				if (null != expires) {
-					dataToStore.expires = UIComponentBase.saveAttachedState(context,expires);
-				}
-				ValueExpression lastModified = component.getValueExpression("lastModified");
-				if (null != lastModified) {
-					dataToStore.modified = UIComponentBase.saveAttachedState(context,lastModified);
-				}
-			}
-		}
-		return dataToStore;
-	}
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.InternetResourceBase#send(org.ajax4jsf.resource.ResourceContext)
-	 */
-	public void send(ResourceContext context) throws IOException {
-		UriData data = (UriData) restoreData(context);
-		FacesContext facesContext = FacesContext.getCurrentInstance();
-		if (null != data && null != facesContext ) {
-			// Send headers
-			ELContext elContext = facesContext.getELContext();
-//			if(data.expires != null){
-//				ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires);
-//				Date expires = (Date) binding.getValue(elContext);
-//				context.setDateHeader("Expires",expires.getTime());
-//			}
-//			if(data.modified != null){
-//				ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified);
-//				Date modified = (Date) binding.getValue(elContext);
-//				context.setDateHeader("Last-Modified",modified.getTime());
-//			}
-			// Send content
-			OutputStream out = context.getOutputStream();
-			MethodExpression send = (MethodExpression) UIComponentBase.restoreAttachedState(facesContext,data.createContent);
-			send.invoke(elContext,new Object[]{out,data.value});
-		}
-	}
+    /**
+     *
+     */
+    public UserResource(boolean cacheable, boolean session, String mime) {
+        super();
+        setCacheable(cacheable);
+        setSessionAware(session);
+        setContentType(mime);
+    }
 
-	
-	@Override
-	public Date getLastModified(ResourceContext resourceContext) {
-		UriData data = (UriData) restoreData(resourceContext);
-		FacesContext facesContext = FacesContext.getCurrentInstance();
-		if (null != data && null != facesContext ) {
-			// Send headers
-			ELContext elContext = facesContext.getELContext();
-			if(data.modified != null){
-			ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified);
-			Date modified = (Date) binding.getValue(elContext);
-			if (null != modified) {
-				return modified;
-			}
-		}
-		}
-		return super.getLastModified(resourceContext);
-	}
-	
-	
-	@Override
-	public long getExpired(ResourceContext resourceContext) {
-		UriData data = (UriData) restoreData(resourceContext);
-		FacesContext facesContext = FacesContext.getCurrentInstance();
-		if (null != data && null != facesContext ) {
-			// Send headers
-			ELContext elContext = facesContext.getELContext();
-			if(data.expires != null){
-			ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires);
-			Date expires = (Date) binding.getValue(elContext);
-			if (null != expires) {
-				return expires.getTime()-System.currentTimeMillis();
-			}
-		}
-		}
-		return super.getExpired(resourceContext);
-	}
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext()
-	 */
-	public boolean requireFacesContext() {
-		// TODO Auto-generated method stub
-		return true;
-	}
-	
-	public static class UriData implements Serializable {
+    /**
+     * @return Returns the contentType.
+     */
+    public String getContentType(ResourceContext resourceContext) {
+        return contentType;
+    }
 
-		/**
-		 * 
-		 */
-		private static final long serialVersionUID = 1258987L;
-		
-		private Object value;
-		
-		private Object createContent;
-		
-		private Object expires;
-		
-		private Object modified;
-	}
+    /**
+     * @param contentType The contentType to set.
+     */
+    public void setContentType(String contentType) {
+        this.contentType = contentType;
+    }
 
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.InternetResourceBase#getDataToStore(javax.faces.context.FacesContext, java.lang.Object)
+     */
+    public Object getDataToStore(FacesContext context, Object data) {
+        UriData dataToStore = null;
+
+        if (data instanceof ResourceComponent2) {
+            ResourceComponent2 resource = (ResourceComponent2) data;
+
+            dataToStore = new UriData();
+            dataToStore.value = resource.getValue();
+            dataToStore.createContent = UIComponentBase.saveAttachedState(context,
+                    resource.getCreateContentExpression());
+
+            if (data instanceof UIComponent) {
+                UIComponent component = (UIComponent) data;
+                ValueExpression expires = component.getValueExpression("expires");
+
+                if (null != expires) {
+                    dataToStore.expires = UIComponentBase.saveAttachedState(context, expires);
+                }
+
+                ValueExpression lastModified = component.getValueExpression("lastModified");
+
+                if (null != lastModified) {
+                    dataToStore.modified = UIComponentBase.saveAttachedState(context, lastModified);
+                }
+            }
+        }
+
+        return dataToStore;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.InternetResourceBase#send(org.ajax4jsf.resource.ResourceContext)
+     */
+    public void send(ResourceContext context) throws IOException {
+        UriData data = (UriData) restoreData(context);
+        FacesContext facesContext = FacesContext.getCurrentInstance();
+
+        if ((null != data) && (null != facesContext)) {
+
+            // Send headers
+            ELContext elContext = facesContext.getELContext();
+
+//          if(data.expires != null){
+//              ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires);
+//              Date expires = (Date) binding.getValue(elContext);
+//              context.setDateHeader("Expires",expires.getTime());
+//          }
+//          if(data.modified != null){
+//              ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified);
+//              Date modified = (Date) binding.getValue(elContext);
+//              context.setDateHeader("Last-Modified",modified.getTime());
+//          }
+            // Send content
+            OutputStream out = context.getOutputStream();
+            MethodExpression send = (MethodExpression) UIComponentBase.restoreAttachedState(facesContext,
+                                        data.createContent);
+
+            send.invoke(elContext, new Object[] {out, data.value});
+        }
+    }
+
+    @Override
+    public Date getLastModified(ResourceContext resourceContext) {
+        UriData data = (UriData) restoreData(resourceContext);
+        FacesContext facesContext = FacesContext.getCurrentInstance();
+
+        if ((null != data) && (null != facesContext)) {
+
+            // Send headers
+            ELContext elContext = facesContext.getELContext();
+
+            if (data.modified != null) {
+                ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,
+                                              data.modified);
+                Date modified = (Date) binding.getValue(elContext);
+
+                if (null != modified) {
+                    return modified;
+                }
+            }
+        }
+
+        return super.getLastModified(resourceContext);
+    }
+
+    @Override
+    public long getExpired(ResourceContext resourceContext) {
+        UriData data = (UriData) restoreData(resourceContext);
+        FacesContext facesContext = FacesContext.getCurrentInstance();
+
+        if ((null != data) && (null != facesContext)) {
+
+            // Send headers
+            ELContext elContext = facesContext.getELContext();
+
+            if (data.expires != null) {
+                ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,
+                                              data.expires);
+                Date expires = (Date) binding.getValue(elContext);
+
+                if (null != expires) {
+                    return expires.getTime() - System.currentTimeMillis();
+                }
+            }
+        }
+
+        return super.getExpired(resourceContext);
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext()
+     */
+    public boolean requireFacesContext() {
+
+        // TODO Auto-generated method stub
+        return true;
+    }
+
+    public static class UriData implements Serializable {
+
+        /**
+         *
+         */
+        private static final long serialVersionUID = 1258987L;
+        private Object createContent;
+        private Object expires;
+        private Object modified;
+        private Object value;
+
+        public Object getCreateContent() {
+            return createContent;
+        }
+
+        public void setCreateContent(Object createContent) {
+            this.createContent = createContent;
+        }
+
+        public Object getExpires() {
+            return expires;
+        }
+
+        public void setExpires(Object expires) {
+            this.expires = expires;
+        }
+
+        public Object getModified() {
+            return modified;
+        }
+
+        public void setModified(Object modified) {
+            this.modified = modified;
+        }
+
+        public Object getValue() {
+            return value;
+        }
+
+        public void setValue(Object value) {
+            this.value = value;
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/DualLRUMap.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/DualLRUMap.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/DualLRUMap.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource.cached;
 
 import java.util.Collection;
@@ -29,76 +31,71 @@
 import java.util.Set;
 
 class DualLRUMap<K, V> extends LinkedHashMap<K, V> {
-	
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -313747679711995782L;
+    private static final long serialVersionUID = -313747679711995782L;
+    private int capacity;
+    private Map<V, K> reverseMap;
 
-	private Map<V, K> reverseMap;
-	
-	private int capacity;
-	
-	public DualLRUMap(int capacity) {
-		super(capacity, 0.75f, true);
+    public DualLRUMap(int capacity) {
+        super(capacity, 0.75f, true);
+        this.capacity = capacity;
+        this.reverseMap = new HashMap<V, K>(capacity, 0.75f);
+    }
 
-		this.capacity = capacity;
-		
-		this.reverseMap = new HashMap<V, K>(capacity, 0.75f);
-	}
-	
-	public V put(K key, V value) {
-		V v = super.put(key, value);
-		
-		reverseMap.put(value, key);
-		
-		return v;
-	};
-	
-	public V remove(Object key) {
-		V value = super.remove(key);
-	
-		if (value != null) {
-			reverseMap.remove(value);
-		}
-		
-		return value;
-	}
-	
-	public K getKey(Object value) {
-		K key = reverseMap.get(value);
+    @Override
+    public V put(K key, V value) {
+        V v = super.put(key, value);
 
-		if (key != null) {
-			//update LRU
-			get(key);
-		}
-		
-		return key;
-	}
-	
-	@Override
-	protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
-		boolean remove = (size() > capacity);
+        reverseMap.put(value, key);
 
-		if (remove) {
-			reverseMap.remove(eldest.getValue());
-		}
-		
-		return remove;
-	}
-	
-	@Override
-	public Set<java.util.Map.Entry<K, V>> entrySet() {
-		return Collections.unmodifiableSet(super.entrySet());
-	}
+        return v;
+    }
 
-	@Override
-	public Set<K> keySet() {
-		return Collections.unmodifiableSet(super.keySet());
-	}
+    @Override
+    public V remove(Object key) {
+        V value = super.remove(key);
 
-	@Override
-	public Collection<V> values() {
-		return Collections.unmodifiableCollection(super.values());
-	}
-}
\ No newline at end of file
+        if (value != null) {
+            reverseMap.remove(value);
+        }
+
+        return value;
+    }
+
+    public K getKey(Object value) {
+        K key = reverseMap.get(value);
+
+        if (key != null) {
+
+            // update LRU
+            get(key);
+        }
+
+        return key;
+    }
+
+    @Override
+    protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
+        boolean remove = size() > capacity;
+
+        if (remove) {
+            reverseMap.remove(eldest.getValue());
+        }
+
+        return remove;
+    }
+
+    @Override
+    public Set<java.util.Map.Entry<K, V>> entrySet() {
+        return Collections.unmodifiableSet(super.entrySet());
+    }
+
+    @Override
+    public Set<K> keySet() {
+        return Collections.unmodifiableSet(super.keySet());
+    }
+
+    @Override
+    public Collection<V> values() {
+        return Collections.unmodifiableCollection(super.values());
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceBean.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceBean.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceBean.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource.cached;
 
 import java.io.Serializable;
@@ -28,53 +30,54 @@
  *
  */
 public class ResourceBean implements Serializable {
-	
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = 2830008963777271324L;
-	private String key;
 
-	/**
-	 * @return the key
-	 */
-	public String getKey() {
-		return key;
-	}
-	
-	public Object getData(){
-		return null;
-	}
+    /**
+     *
+     */
+    private static final long serialVersionUID = 2830008963777271324L;
+    private String key;
 
-	public ResourceBean(String key) {
-		super();
-		this.key = key;
-	}
+    public ResourceBean(String key) {
+        super();
+        this.key = key;
+    }
 
-	/* (non-Javadoc)
-	 * @see java.lang.Object#equals(java.lang.Object)
-	 */
-	public boolean equals(Object obj) {
-		if (this == obj) {
-			return true;
-		}
-		
-		if (null != obj && obj instanceof ResourceBean) {
-			ResourceBean bean = (ResourceBean) obj;
-			return key.equals(bean.getKey()) && bean.getData() == null;
-		}
-		
-		return false;
-	}
+    /**
+     * @return the key
+     */
+    public String getKey() {
+        return key;
+    }
 
-	/* (non-Javadoc)
-	 * @see java.lang.Object#hashCode()
-	 */
-	public int hashCode() {
-		// TODO Auto-generated method stub
-		return key.hashCode();
-	}
-	
-	
+    public Object getData() {
+        return null;
+    }
 
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#equals(java.lang.Object)
+     */
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+
+        if ((null != obj) && (obj instanceof ResourceBean)) {
+            ResourceBean bean = (ResourceBean) obj;
+
+            return key.equals(bean.getKey()) && (bean.getData() == null);
+        }
+
+        return false;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.lang.Object#hashCode()
+     */
+    public int hashCode() {
+
+        // TODO Auto-generated method stub
+        return key.hashCode();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceBytesDataBean.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceBytesDataBean.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceBytesDataBean.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource.cached;
 
 import java.util.Arrays;
@@ -28,46 +30,51 @@
  *
  */
 public class ResourceBytesDataBean extends ResourceBean {
-	
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -3012554202964229624L;
-	private byte[] data;
-	
-	ResourceBytesDataBean(String key, byte[] data){
-		super(key);
-		this.data = data;
-	}
-	
-	public Object getData() {
-		return data;
-	}
-	/* (non-Javadoc)
-	 * @see com.exadel.vcp.resource.ResourceBean#equals(java.lang.Object)
-	 */
-	public boolean equals(Object obj) {
-		if (this == obj) {
-			return true;
-		}
 
-		if (null != obj && obj instanceof ResourceBytesDataBean) {
-			ResourceBytesDataBean bean = (ResourceBytesDataBean) obj;
-			byte[] beanData = (byte[]) bean.getData();
-			return getKey().equals(bean.getKey()) && Arrays.equals(data, beanData);
-		}
-		
-		return false;
-	}
+    /**
+     *
+     */
+    private static final long serialVersionUID = -3012554202964229624L;
+    private byte[] data;
 
-	/* (non-Javadoc)
-	 * @see com.exadel.vcp.resource.ResourceBean#hashCode()
-	 */
-	public int hashCode() {
-		final int prime = 31;
-		int result = super.hashCode();
-		result = prime * result + Arrays.hashCode(data);
-		return result;
-	}
+    ResourceBytesDataBean(String key, byte[] data) {
+        super(key);
+        this.data = data;
+    }
 
+    public Object getData() {
+        return data;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see com.exadel.vcp.resource.ResourceBean#equals(java.lang.Object)
+     */
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+
+        if ((null != obj) && (obj instanceof ResourceBytesDataBean)) {
+            ResourceBytesDataBean bean = (ResourceBytesDataBean) obj;
+            byte[] beanData = (byte[]) bean.getData();
+
+            return getKey().equals(bean.getKey()) && Arrays.equals(data, beanData);
+        }
+
+        return false;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see com.exadel.vcp.resource.ResourceBean#hashCode()
+     */
+    public int hashCode() {
+        final int prime = 31;
+        int result = super.hashCode();
+
+        result = prime * result + Arrays.hashCode(data);
+
+        return result;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceDataBean.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceDataBean.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/ResourceDataBean.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,58 +19,63 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.resource.cached;
 
-
 /**
  * @author shura
  *
  */
 public class ResourceDataBean extends ResourceBean {
-	
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -6486715556040103424L;
 
-	private Object data;
-	
-	public ResourceDataBean(String key, Object data){
-		super(key);
-		this.data = data;
-	}
+    /**
+     *
+     */
+    private static final long serialVersionUID = -6486715556040103424L;
+    private Object data;
 
-	/* (non-Javadoc)
-	 * @see com.exadel.vcp.resource.ResourceBean#equals(java.lang.Object)
-	 */
-	public boolean equals(Object obj) {
-		if (this == obj) {
-			return true;
-		}
-		
-		if (null != obj && obj instanceof ResourceBean) {
-			ResourceBean bean = (ResourceBean) obj;
-			return getKey().equals(bean.getKey()) && data.equals(bean.getData());
-		}
-		
-		return false;
-	}
+    public ResourceDataBean(String key, Object data) {
+        super(key);
+        this.data = data;
+    }
 
-	/* (non-Javadoc)
-	 * @see com.exadel.vcp.resource.ResourceBean#getData()
-	 */
-	public Object getData() {
-		return data;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see com.exadel.vcp.resource.ResourceBean#equals(java.lang.Object)
+     */
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
 
-	/* (non-Javadoc)
-	 * @see com.exadel.vcp.resource.ResourceBean#hashCode()
-	 */
-	public int hashCode() {
-		final int prime = 31;
-		int result = super.hashCode();
-		result = result * prime + data.hashCode();
-		return result;
-	}
+        if ((null != obj) && (obj instanceof ResourceBean)) {
+            ResourceBean bean = (ResourceBean) obj;
 
+            return getKey().equals(bean.getKey()) && data.equals(bean.getData());
+        }
+
+        return false;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see com.exadel.vcp.resource.ResourceBean#getData()
+     */
+    public Object getData() {
+        return data;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see com.exadel.vcp.resource.ResourceBean#hashCode()
+     */
+    public int hashCode() {
+        final int prime = 31;
+        int result = super.hashCode();
+
+        result = result * prime + data.hashCode();
+
+        return result;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/cached/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Implementation of cached resources
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/image/ImageInfo.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/image/ImageInfo.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/image/ImageInfo.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,37 +19,40 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 /*
- * ImageInfo.java
- *
- * Version 1.5
- *
- * A Java class to determine image width, height and color depth for
- * a number of image file formats.
- *
- * Written by Marco Schmidt 
- * <http://www.geocities.com/marcoschmidt.geo/contact.html>.
- *
- * Contributed to the Public Domain.
- *
- * Last modification 2004-02-29
+* ImageInfo.java
+*
+* Version 1.5
+*
+* A Java class to determine image width, height and color depth for
+* a number of image file formats.
+*
+* Written by Marco Schmidt
+* <http://www.geocities.com/marcoschmidt.geo/contact.html>.
+*
+* Contributed to the Public Domain.
+*
+* Last modification 2004-02-29
  */
-
 package org.ajax4jsf.resource.image;
 
+import org.ajax4jsf.Messages;
+
 import java.io.DataInput;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+
 import java.net.URL;
+
 import java.util.Vector;
 
-import org.ajax4jsf.Messages;
-
 /**
- * Get file format, image resolution, number of bits per pixel and optionally 
- * number of images, comments and physical resolution from 
- * JPEG, GIF, BMP, PCX, PNG, IFF, RAS, PBM, PGM, PPM, PSD and SWF files 
+ * Get file format, image resolution, number of bits per pixel and optionally
+ * number of images, comments and physical resolution from
+ * JPEG, GIF, BMP, PCX, PNG, IFF, RAS, PBM, PGM, PPM, PSD and SWF files
  * (or input streams).
  * <p>
  * Use the class like this:
@@ -62,8 +65,8 @@
  *   System.err.println("Not a supported image file format.");
  *   return;
  * }
- * System.out.println(ii.getFormatName() + ", " + ii.getMimeType() + 
- *   ", " + ii.getWidth() + " x " + ii.getHeight() + " pixels, " + 
+ * System.out.println(ii.getFormatName() + ", " + ii.getMimeType() +
+ *   ", " + ii.getWidth() + " x " + ii.getHeight() + " pixels, " +
  *   ii.getBitsPerPixel() + " bits per pixel, " + ii.getNumberOfImages() +
  *   " image(s), " + ii.getNumberOfComments() + " comment(s).");
  *  // there are other properties, check out the API documentation
@@ -75,12 +78,12 @@
  * </pre>
  * or call it without parameters and pipe data to it:
  * <pre>
- *   java ImageInfo &lt; image.jpg  
+ *   java ImageInfo &lt; image.jpg
  * </pre>
  * <p>
  * Known limitations:
  * <ul>
- * <li>When the determination of the number of images is turned off, GIF bits 
+ * <li>When the determination of the number of images is turned off, GIF bits
  *  per pixel are only read from the global header.
  *  For some GIFs, local palettes change this to a typically larger
  *  value. To be certain to get the correct color depth, call
@@ -95,7 +98,8 @@
  * <li>Java 1.1 or higher</li>
  * </ul>
  * <p>
- * The latest version can be found at <a href="http://www.geocities.com/marcoschmidt.geo/image-info.html">http://www.geocities.com/marcoschmidt.geo/image-info.html</a>.
+ * The latest version can be found at <a href="http://www.geocities.com/marcoschmidt.geo/image-info.html">
+ * http://www.geocities.com/marcoschmidt.geo/image-info.html</a>.
  * <p>
  * Written by <a href="http://www.geocities.com/marcoschmidt.geo/contact.html">Marco Schmidt</a>.
  * <p>
@@ -110,18 +114,20 @@
  * <li><strong>2001-10-13</strong> Added support for the file formats BMP and PCX.</li>
  * <li><strong>2001-10-16</strong> Fixed bug in read(int[], int, int) that returned
  * <li><strong>2002-01-22</strong> Added support for file formats Amiga IFF and Sun Raster (RAS).</li>
- * <li><strong>2002-01-24</strong> Added support for file formats Portable Bitmap / Graymap / Pixmap (PBM, PGM, PPM) and Adobe Photoshop (PSD).
+ * <li><strong>2002-01-24</strong> Added support for file formats Portable Bitmap / Graymap / Pixmap (PBM, PGM, PPM)
+ * and Adobe Photoshop (PSD).
  *   Added new method getMimeType() to return the MIME type associated with a particular file format.</li>
  * <li><strong>2002-03-15</strong> Added support to recognize number of images in file. Only works with GIF.
  *   Use {@link #setDetermineImageNumber} with <code>true</code> as argument to identify animated GIFs
  *   ({@link #getNumberOfImages()} will return a value larger than <code>1</code>).</li>
- * <li><strong>2002-04-10</strong> Fixed a bug in the feature 'determine number of images in animated GIF' introduced with version 1.1.
- *   Thanks to Marcelo P. Lima for sending in the bug report. 
+ * <li><strong>2002-04-10</strong> Fixed a bug in the feature 'determine number of images in animated GIF' introduced
+ * with version 1.1.
+ *   Thanks to Marcelo P. Lima for sending in the bug report.
  *   Released as 1.1.1.</li>
- * <li><strong>2002-04-18</strong> Added {@link #setCollectComments(boolean)}. 
- *  That new method lets the user specify whether textual comments are to be  
+ * <li><strong>2002-04-18</strong> Added {@link #setCollectComments(boolean)}.
+ *  That new method lets the user specify whether textual comments are to be
  *  stored in an internal list when encountered in an input image file / stream.
- *  Added two methods to return the physical width and height of the image in dpi: 
+ *  Added two methods to return the physical width and height of the image in dpi:
  *   {@link #getPhysicalWidthDpi()} and {@link #getPhysicalHeightDpi()}.
  *  If the physical resolution could not be retrieved, these methods return <code>-1</code>.
  *  </li>
@@ -136,1174 +142,1277 @@
  *  Released as 1.4.</li>
  * <li><strong>2004-02-29</strong> Added support for recognizing progressive JPEG and
  *  interlaced PNG and GIF. A new method {@link #isProgressive()} returns whether ImageInfo
- *  has found that the storage type is progressive (or interlaced). 
+ *  has found that the storage type is progressive (or interlaced).
  *  Thanks to Joe Germuska for suggesting the feature.
  *  Bug fix: BMP physical resolution is now correctly determined.
  *  Released as 1.5.</li>
  * </ul>
  */
 public class ImageInfo {
-	/**
-	 * Return value of {@link #getFormat()} for JPEG streams.
-	 * ImageInfo can extract physical resolution and comments
-	 * from JPEGs (only from APP0 headers).
-	 * Only one image can be stored in a file.
-	 * It is determined whether the JPEG stream is progressive 
-	 * (see {@link #isProgressive()}).
-	 */
-	public static final int FORMAT_JPEG = 0;
+    public static final int COLOR_TYPE_BLACK_AND_WHITE = 3;
+    public static final int COLOR_TYPE_GRAYSCALE = 2;
+    public static final int COLOR_TYPE_PALETTED = 1;
+    public static final int COLOR_TYPE_TRUECOLOR_RGB = 0;
+    public static final int COLOR_TYPE_UNKNOWN = -1;
 
-	/**
-	 * Return value of {@link #getFormat()} for GIF streams.
-	 * ImageInfo can extract comments from GIFs and count the number
-	 * of images (GIFs with more than one image are animations).
-	 * If you know of a place where GIFs store the physical resolution
-	 * of an image, please
-	 * <a href="http://www.geocities.com/marcoschmidt.geo/contact.html">send me a mail</a>!
-	 * It is determined whether the GIF stream is interlaced (see {@link #isProgressive()}).
-	 */
-	public static final int FORMAT_GIF = 1;
+    /**
+     * Return value of {@link #getFormat()} for BMP streams.
+     * BMP only supports one image per file.
+     * BMP does not allow for comments.
+     * The physical resolution can be stored.
+     */
+    public static final int FORMAT_BMP = 3;
 
-	/**
-	 * Return value of {@link #getFormat()} for PNG streams.
-	 * PNG only supports one image per file.
-	 * Both physical resolution and comments can be stored with PNG,
-	 * but ImageInfo is currently not able to extract those.
-	 * It is determined whether the PNG stream is interlaced (see {@link #isProgressive()}).
-	 */
-	public static final int FORMAT_PNG = 2;
+    /**
+     * Return value of {@link #getFormat()} for GIF streams.
+     * ImageInfo can extract comments from GIFs and count the number
+     * of images (GIFs with more than one image are animations).
+     * If you know of a place where GIFs store the physical resolution
+     * of an image, please
+     * <a href="http://www.geocities.com/marcoschmidt.geo/contact.html">send me a mail</a>!
+     * It is determined whether the GIF stream is interlaced (see {@link #isProgressive()}).
+     */
+    public static final int FORMAT_GIF = 1;
 
-	/**
-	 * Return value of {@link #getFormat()} for BMP streams.
-	 * BMP only supports one image per file.
-	 * BMP does not allow for comments.
-	 * The physical resolution can be stored.
-	 */
-	public static final int FORMAT_BMP = 3;
+    /**
+     * Return value of {@link #getFormat()} for IFF streams.
+     */
+    public static final int FORMAT_IFF = 5;
 
-	/**
-	 * Return value of {@link #getFormat()} for PCX streams.
-	 * PCX does not allow for comments or more than one image per file.
-	 * However, the physical resolution can be stored.
-	 */
-	public static final int FORMAT_PCX = 4;
+    /**
+     * Return value of {@link #getFormat()} for JPEG streams.
+     * ImageInfo can extract physical resolution and comments
+     * from JPEGs (only from APP0 headers).
+     * Only one image can be stored in a file.
+     * It is determined whether the JPEG stream is progressive
+     * (see {@link #isProgressive()}).
+     */
+    public static final int FORMAT_JPEG = 0;
 
-	/**
-	 * Return value of {@link #getFormat()} for IFF streams.
-	 */
-	public static final int FORMAT_IFF = 5;
+    /**
+     * The names of all supported file formats.
+     * The FORMAT_xyz int constants can be used as index values for
+     * this array.
+     */
+    private static final String[] FORMAT_NAMES = {
+        "JPEG", "GIF", "PNG", "BMP", "PCX", "IFF", "RAS", "PBM", "PGM", "PPM", "PSD", "SWF"
+    };
 
-	/**
-	 * Return value of {@link #getFormat()} for RAS streams.
-	 * Sun Raster allows for one image per file only and is not able to
-	 * store physical resolution or comments.
-	 */
-	public static final int FORMAT_RAS = 6;
+    /**
+     * Return value of {@link #getFormat()} for PBM streams.
+     */
+    public static final int FORMAT_PBM = 7;
 
-	/** Return value of {@link #getFormat()} for PBM streams. */
-	public static final int FORMAT_PBM = 7;
+    /**
+     * Return value of {@link #getFormat()} for PCX streams.
+     * PCX does not allow for comments or more than one image per file.
+     * However, the physical resolution can be stored.
+     */
+    public static final int FORMAT_PCX = 4;
 
-	/** Return value of {@link #getFormat()} for PGM streams. */
-	public static final int FORMAT_PGM = 8;
+    /** Return value of {@link #getFormat()} for PGM streams. */
+    public static final int FORMAT_PGM = 8;
 
-	/** Return value of {@link #getFormat()} for PPM streams. */
-	public static final int FORMAT_PPM = 9;
+    /**
+     * Return value of {@link #getFormat()} for PNG streams.
+     * PNG only supports one image per file.
+     * Both physical resolution and comments can be stored with PNG,
+     * but ImageInfo is currently not able to extract those.
+     * It is determined whether the PNG stream is interlaced (see {@link #isProgressive()}).
+     */
+    public static final int FORMAT_PNG = 2;
 
-	/** Return value of {@link #getFormat()} for PSD streams. */
-	public static final int FORMAT_PSD = 10;
+    /** Return value of {@link #getFormat()} for PPM streams. */
+    public static final int FORMAT_PPM = 9;
 
-	/** Return value of {@link #getFormat()} for SWF (Shockwave) streams. */
-	public static final int FORMAT_SWF = 11;
+    /** Return value of {@link #getFormat()} for PSD streams. */
+    public static final int FORMAT_PSD = 10;
 
-	public static final int COLOR_TYPE_UNKNOWN = -1;
-	public static final int COLOR_TYPE_TRUECOLOR_RGB = 0;
-	public static final int COLOR_TYPE_PALETTED = 1;
-	public static final int COLOR_TYPE_GRAYSCALE= 2;
-	public static final int COLOR_TYPE_BLACK_AND_WHITE = 3;
+    /**
+     * Return value of {@link #getFormat()} for RAS streams.
+     * Sun Raster allows for one image per file only and is not able to
+     * store physical resolution or comments.
+     */
+    public static final int FORMAT_RAS = 6;
 
-	/**
-	 * The names of all supported file formats.
-	 * The FORMAT_xyz int constants can be used as index values for
-	 * this array.
-	 */
-	private static final String[] FORMAT_NAMES =
-		{"JPEG", "GIF", "PNG", "BMP", "PCX", 
-		 "IFF", "RAS", "PBM", "PGM", "PPM", 
-		 "PSD", "SWF"};
+    /** Return value of {@link #getFormat()} for SWF (Shockwave) streams. */
+    public static final int FORMAT_SWF = 11;
 
-	/**
-	 * The names of the MIME types for all supported file formats.
-	 * The FORMAT_xyz int constants can be used as index values for
-	 * this array.
-	 */
-	private static final String[] MIME_TYPE_STRINGS =
-		{"image/jpeg", "image/gif", "image/png", "image/bmp", "image/pcx", 
-		 "image/iff", "image/ras", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", 
-		 "image/psd", "application/x-shockwave-flash"};
+    /**
+     * The names of the MIME types for all supported file formats.
+     * The FORMAT_xyz int constants can be used as index values for
+     * this array.
+     */
+    private static final String[] MIME_TYPE_STRINGS = {
+        "image/jpeg", "image/gif", "image/png", "image/bmp", "image/pcx", "image/iff", "image/ras",
+        "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/psd",
+        "application/x-shockwave-flash"
+    };
+    private int colorType = COLOR_TYPE_UNKNOWN;
+    private boolean collectComments = true;
+    private int bitBuf;
+    private int bitPos;
+    private int bitsPerPixel;
+    private Vector comments;
+    private boolean determineNumberOfImages;
+    private DataInput din;
+    private int format;
+    private int height;
+    private InputStream in;
+    private int numberOfImages;
+    private int physicalHeightDpi;
+    private int physicalWidthDpi;
+    private boolean progressive;
+    private int width;
 
-	private int width;
-	private int height;
-	private int bitsPerPixel;
-	private int colorType = COLOR_TYPE_UNKNOWN;
-	private boolean progressive;
-	private int format;
-	private InputStream in;
-	private DataInput din;
-	private boolean collectComments = true;
-	private Vector comments;
-	private boolean determineNumberOfImages;
-	private int numberOfImages;
-	private int physicalHeightDpi;
-	private int physicalWidthDpi;
-	private int bitBuf;
-	private int bitPos;
+    private void addComment(String s) {
+        if (comments == null) {
+            comments = new Vector();
+        }
 
-	private void addComment(String s) {
-		if (comments == null) {
-			comments = new Vector();
-		}
-		comments.addElement(s);
-	}
+        comments.addElement(s);
+    }
 
-	/**
-	 * Call this method after you have provided an input stream or file
-	 * using {@link #setInput(InputStream)} or {@link #setInput(DataInput)}.
-	 * If true is returned, the file format was known and information
-	 * on the file's content can be retrieved using the various getXyz methods.
-	 * @return if information could be retrieved from input
-	 */
-	public boolean check() {
-		format = -1;
-		width = -1;
-		height = -1;
-		bitsPerPixel = -1;
-		numberOfImages = 1;
-		physicalHeightDpi = -1;
-		physicalWidthDpi = -1;
-		comments = null;
-		try {
-			int b1 = read() & 0xff;
-			int b2 = read() & 0xff;
-			if (b1 == 0x47 && b2 == 0x49) {
-				return checkGif();
-			}
-			else
-			if (b1 == 0x89 && b2 == 0x50) {
-				return checkPng();
-			}
-			else
-			if (b1 == 0xff && b2 == 0xd8) {
-				return checkJpeg();
-			}
-			else
-			if (b1 == 0x42 && b2 == 0x4d) {
-				return checkBmp();
-			}
-			else
-			if (b1 == 0x0a && b2 < 0x06) {
-				return checkPcx();
-			}
-			else
-			if (b1 == 0x46 && b2 == 0x4f) {
-				return checkIff();
-			}
-			else
-			if (b1 == 0x59 && b2 == 0xa6) {
-				return checkRas();
-			}
-			else
-			if (b1 == 0x50 && b2 >= 0x31 && b2 <= 0x36) {
-				return checkPnm(b2 - '0');
-			}
-			else
-			if (b1 == 0x38 && b2 == 0x42) {
-				return checkPsd();
-			}
-			else
-			if (b1 == 0x46 && b2 == 0x57) {
-				return checkSwf();
-			}
-			else {
-				return false;
-			}
-		} catch (IOException ioe) {
-			return false;
-		}
-	}
+    /**
+     * Call this method after you have provided an input stream or file
+     * using {@link #setInput(InputStream)} or {@link #setInput(DataInput)}.
+     * If true is returned, the file format was known and information
+     * on the file's content can be retrieved using the various getXyz methods.
+     * @return if information could be retrieved from input
+     */
+    public boolean check() {
+        format = -1;
+        width = -1;
+        height = -1;
+        bitsPerPixel = -1;
+        numberOfImages = 1;
+        physicalHeightDpi = -1;
+        physicalWidthDpi = -1;
+        comments = null;
 
-	private boolean checkBmp() throws IOException {
-		byte[] a = new byte[44];
-		if (read(a) != a.length) {
-			return false;
-		}
-		width = getIntLittleEndian(a, 16);
-		height = getIntLittleEndian(a, 20);
-		if (width < 1 || height < 1) {
-			return false;
-		}
-		bitsPerPixel = getShortLittleEndian(a, 26);
-		if (bitsPerPixel != 1 && bitsPerPixel != 4 &&
-		    bitsPerPixel != 8 && bitsPerPixel != 16 &&
-		    bitsPerPixel != 24 && bitsPerPixel != 32) {
-		    return false;
-		}
-		int x = (int)(getIntLittleEndian(a, 36) * 0.0254);
-		if (x > 0) {
-			setPhysicalWidthDpi(x);
-		}
-		int y = (int)(getIntLittleEndian(a, 40) * 0.0254);
-		if (y > 0) {
-			setPhysicalHeightDpi(y);
-		}
-		format = FORMAT_BMP;
-		return true;
-	}
+        try {
+            int b1 = read() & 0xff;
+            int b2 = read() & 0xff;
 
-	private boolean checkGif() throws IOException {
-		final byte[] GIF_MAGIC_87A = {0x46, 0x38, 0x37, 0x61};
-		final byte[] GIF_MAGIC_89A = {0x46, 0x38, 0x39, 0x61};
-		byte[] a = new byte[11]; // 4 from the GIF signature + 7 from the global header
-		if (read(a) != 11) {
-			return false;
-		}
-		if ((!equals(a, 0, GIF_MAGIC_89A, 0, 4)) &&
-			(!equals(a, 0, GIF_MAGIC_87A, 0, 4))) {
-			return false;
-		}
-		format = FORMAT_GIF;
-		width = getShortLittleEndian(a, 4);
-		height = getShortLittleEndian(a, 6);
-		int flags = a[8] & 0xff;
-		bitsPerPixel = ((flags >> 4) & 0x07) + 1;
-		progressive = (flags & 0x02) != 0;
-		if (!determineNumberOfImages) {
-			return true;
-		}
-		// skip global color palette
-		if ((flags & 0x80) != 0) {
-			int tableSize = (1 << ((flags & 7) + 1)) * 3;
-			skip(tableSize);
-		}
-		numberOfImages = 0;
-		int blockType;
-		do
-		{
-			blockType = read();
-			switch(blockType)
-			{
-				case(0x2c): // image separator
-				{
-					if (read(a, 0, 9) != 9) {
-						return false;
-					}
-					flags = a[8] & 0xff;
-					int localBitsPerPixel = (flags & 0x07) + 1;
-					if (localBitsPerPixel > bitsPerPixel) {
-						bitsPerPixel = localBitsPerPixel;
-					}
-					if ((flags & 0x80) != 0) {
-						skip((1 << localBitsPerPixel) * 3);
-					}
-					skip(1); // initial code length
-					int n;
-					do
-					{
-						n = read();
-						if (n > 0) {
-							skip(n);
-						}
-						else
-						if (n == -1) {
-							return false;
-						}
-					}
-					while (n > 0);
-					numberOfImages++;
-					break;
-				}
-				case(0x21): // extension
-				{
-					int extensionType = read();
-					if (collectComments && extensionType == 0xfe) {
-						StringBuffer sb = new StringBuffer();
-						int n;
-						do
-						{
-							n = read();
-							if (n == -1) {
-								return false;
-							}
-							if (n > 0) {
-								for (int i = 0; i < n; i++) {
-									int ch = read();
-									if (ch == -1) {
-										return false;
-									}
-									sb.append((char)ch);
-								}
-							}
-						}
-						while (n > 0);
-					} else {
-						int n;
-						do
-						{
-							n = read();
-							if (n > 0) {
-								skip(n);
-							}
-							else
-							if (n == -1) {
-								return false;
-							}
-						}
-						while (n > 0);
-					}
-					break;
-				}
-				case(0x3b): // end of file
-				{
-					break;
-				}
-				default:
-				{
-					return false;
-				}
-			}
-		}
-		while (blockType != 0x3b);
-		return true;
-	}
+            if ((b1 == 0x47) && (b2 == 0x49)) {
+                return checkGif();
+            } else if ((b1 == 0x89) && (b2 == 0x50)) {
+                return checkPng();
+            } else if ((b1 == 0xff) && (b2 == 0xd8)) {
+                return checkJpeg();
+            } else if ((b1 == 0x42) && (b2 == 0x4d)) {
+                return checkBmp();
+            } else if ((b1 == 0x0a) && (b2 < 0x06)) {
+                return checkPcx();
+            } else if ((b1 == 0x46) && (b2 == 0x4f)) {
+                return checkIff();
+            } else if ((b1 == 0x59) && (b2 == 0xa6)) {
+                return checkRas();
+            } else if ((b1 == 0x50) && (b2 >= 0x31) && (b2 <= 0x36)) {
+                return checkPnm(b2 - '0');
+            } else if ((b1 == 0x38) && (b2 == 0x42)) {
+                return checkPsd();
+            } else if ((b1 == 0x46) && (b2 == 0x57)) {
+                return checkSwf();
+            } else {
+                return false;
+            }
+        } catch (IOException ioe) {
+            return false;
+        }
+    }
 
-	private boolean checkIff() throws IOException {
-		byte[] a = new byte[10];
-		// read remaining 2 bytes of file id, 4 bytes file size 
-		// and 4 bytes IFF subformat
-		if (read(a, 0, 10) != 10) {
-			return false;
-		}
-		final byte[] IFF_RM = {0x52, 0x4d};
-		if (!equals(a, 0, IFF_RM, 0, 2)) {
-			return false;
-		}
-		int type = getIntBigEndian(a, 6);
-		if (type != 0x494c424d && // type must be ILBM...
-		    type != 0x50424d20) { // ...or PBM
-		    return false;
-		}
-		// loop chunks to find BMHD chunk
-		do {
-			if (read(a, 0, 8) != 8) {
-				return false;
-			}
-			int chunkId = getIntBigEndian(a, 0);
-			int size = getIntBigEndian(a, 4);
-			if ((size & 1) == 1) {
-				size++;
-			}
-			if (chunkId == 0x424d4844) { // BMHD chunk
-				if (read(a, 0, 9) != 9) {
-					return false;
-				}
-				format = FORMAT_IFF;
-				width = getShortBigEndian(a, 0);
-				height = getShortBigEndian(a, 2);
-				bitsPerPixel = a[8] & 0xff;
-				return (width > 0 && height > 0 && bitsPerPixel > 0 && bitsPerPixel < 33);
-			} else {
-				skip(size);
-			}
-		} while (true);
-	}
+    private boolean checkBmp() throws IOException {
+        byte[] a = new byte[44];
 
-	private boolean checkJpeg() throws IOException {
-		byte[] data = new byte[12];
-		while (true) {
-			if (read(data, 0, 4) != 4) {
-				return false;
-			}
-			int marker = getShortBigEndian(data, 0);
-			int size = getShortBigEndian(data, 2);
-			if ((marker & 0xff00) != 0xff00) {
-				return false; // not a valid marker
-			}
-			if (marker == 0xffe0) { // APPx 
-				if (size < 14) {
-					return false; // APPx header must be >= 14 bytes
-				}
-				if (read(data, 0, 12) != 12) {
-					return false;
-				}
-				final byte[] APP0_ID = {0x4a, 0x46, 0x49, 0x46, 0x00};
-				if (equals(APP0_ID, 0, data, 0, 5)) {
-					//System.out.println("data 7=" + data[7]);
-					if (data[7] == 1) {
-						setPhysicalWidthDpi(getShortBigEndian(data, 8));
-						setPhysicalHeightDpi(getShortBigEndian(data, 10));
-					}
-					else
-					if (data[7] == 2) {
-						int x = getShortBigEndian(data, 8);
-						int y = getShortBigEndian(data, 10);
-						setPhysicalWidthDpi((int)(x * 2.54f));
-						setPhysicalHeightDpi((int)(y * 2.54f));
-					}
-				}
-				skip(size - 14);
-			}
-			else
-			if (collectComments && size > 2 && marker == 0xfffe) { // comment
-				size -= 2;
-				byte[] chars = new byte[size];
-				if (read(chars, 0, size) != size) {
-					return false;
-				}
-				String comment = new String(chars, "iso-8859-1");
-				comment = comment.trim();
-				addComment(comment);
-			}
-			else
-			if (marker >= 0xffc0 && marker <= 0xffcf && marker != 0xffc4 && marker != 0xffc8) {
-				if (read(data, 0, 6) != 6) {
-					return false;
-				}
-				format = FORMAT_JPEG;
-				bitsPerPixel = (data[0] & 0xff) * (data[5] & 0xff);
-				progressive = marker == 0xffc2 || marker == 0xffc6 ||
-					marker == 0xffca || marker == 0xffce;
-				width = getShortBigEndian(data, 3);
-				height = getShortBigEndian(data, 1);
-				return true;
-			} else {
-				skip(size - 2);
-			}
-		}
-	}
+        if (read(a) != a.length) {
+            return false;
+        }
 
-	private boolean checkPcx() throws IOException {
-		byte[] a = new byte[64];
-		if (read(a) != a.length) {
-			return false;
-		}
-		if (a[0] != 1) { // encoding, 1=RLE is only valid value
-			return false;
-		}
-		// width / height
-		int x1 = getShortLittleEndian(a, 2);
-		int y1 = getShortLittleEndian(a, 4);
-		int x2 = getShortLittleEndian(a, 6);
-		int y2 = getShortLittleEndian(a, 8);
-		if (x1 < 0 || x2 < x1 || y1 < 0 || y2 < y1) {
-			return false;
-		}
-		width = x2 - x1 + 1;
-		height = y2 - y1 + 1;
-		// color depth
-		int bits = a[1];
-		int planes = a[63];
-		if (planes == 1 &&
-		    (bits == 1 || bits == 2 || bits == 4 || bits == 8)) {
-			// paletted
-			bitsPerPixel = bits;
-		} else
-		if (planes == 3 && bits == 8) {
-			// RGB truecolor
-			bitsPerPixel = 24;
-		} else {
-			return false;
-		}
-		setPhysicalWidthDpi(getShortLittleEndian(a, 10));
-		setPhysicalHeightDpi(getShortLittleEndian(a, 10));
-		format = FORMAT_PCX;
-		return true;
-	}
+        width = getIntLittleEndian(a, 16);
+        height = getIntLittleEndian(a, 20);
 
-	private boolean checkPng() throws IOException {
-		final byte[] PNG_MAGIC = {0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};
-		byte[] a = new byte[27];
-		if (read(a) != 27) {
-			return false;
-		}
-		if (!equals(a, 0, PNG_MAGIC, 0, 6)) {
-			return false;
-		}
-		format = FORMAT_PNG;
-		width = getIntBigEndian(a, 14);
-		height = getIntBigEndian(a, 18);
-		bitsPerPixel = a[22] & 0xff;
-		int colorType = a[23] & 0xff;
-		if (colorType == 2 || colorType == 6) {
-			bitsPerPixel *= 3;
-		}
-		progressive = (a[26] & 0xff) != 0;
-		return true;
-	}
+        if ((width < 1) || (height < 1)) {
+            return false;
+        }
 
-	private boolean checkPnm(int id) throws IOException {
-		if (id < 1 || id > 6) {
-			return false;
-		}
-		final int[] PNM_FORMATS = {FORMAT_PBM, FORMAT_PGM, FORMAT_PPM};
-		format = PNM_FORMATS[(id - 1) % 3];
-		boolean hasPixelResolution = false;
-		String s;
-		while (true)
-		{
-			s = readLine();
-			if (s != null) {
-				s = s.trim();
-			}
-			if (s == null || s.length() < 1) {
-				continue;
-			}
-			if (s.charAt(0) == '#') { // comment
-				if (collectComments && s.length() > 1) {
-					addComment(s.substring(1));
-				}
-				continue;
-			}
-			if (!hasPixelResolution) { // split "343 966" into width=343, height=966
-				int spaceIndex = s.indexOf(' ');
-				if (spaceIndex == -1) {
-					return false;
-				}
-				String widthString = s.substring(0, spaceIndex);
-				spaceIndex = s.lastIndexOf(' ');
-				if (spaceIndex == -1) {
-					return false;
-				}
-				String heightString = s.substring(spaceIndex + 1);
-				try {
-					width = Integer.parseInt(widthString);
-					height = Integer.parseInt(heightString);
-				} catch (NumberFormatException nfe) {
-					return false;
-				}
-				if (width < 1 || height < 1) {
-					return false;
-				}
-				if (format == FORMAT_PBM) {
-					bitsPerPixel = 1;
-					return true;
-				}
-				hasPixelResolution = true;
-			}
-			else
-			{
-				int maxSample;
-				try {
-					maxSample = Integer.parseInt(s);
-				} catch (NumberFormatException nfe) {
-					return false;
-				}
-				if (maxSample < 0) {
-					return false;
-				}
-				for (int i = 0; i < 25; i++) {
-					if (maxSample < (1 << (i + 1))) {
-						bitsPerPixel = i + 1;
-						if (format == FORMAT_PPM) {
-							bitsPerPixel *= 3;
-						}
-						return true;
-					}
-				}
-				return false;
-			}
-		}
-	}
+        bitsPerPixel = getShortLittleEndian(a, 26);
 
-	private boolean checkPsd() throws IOException {
-		byte[] a = new byte[24];
-		if (read(a) != a.length) {
-			return false;
-		}
-		final byte[] PSD_MAGIC = {0x50, 0x53};
-		if (!equals(a, 0, PSD_MAGIC, 0, 2)) {
-			return false;
-		}
-		format = FORMAT_PSD;
-		width = getIntBigEndian(a, 16);
-		height = getIntBigEndian(a, 12);
-		int channels = getShortBigEndian(a, 10);
-		int depth = getShortBigEndian(a, 20);
-		bitsPerPixel = channels * depth;
-		return (width > 0 && height > 0 && bitsPerPixel > 0 && bitsPerPixel <= 64);
-	}
+        if ((bitsPerPixel != 1) && (bitsPerPixel != 4) && (bitsPerPixel != 8) && (bitsPerPixel != 16)
+                && (bitsPerPixel != 24) && (bitsPerPixel != 32)) {
+            return false;
+        }
 
-	private boolean checkRas() throws IOException {
-		byte[] a = new byte[14];
-		if (read(a) != a.length) {
-			return false;
-		}
-		final byte[] RAS_MAGIC = {0x6a, (byte)0x95};
-		if (!equals(a, 0, RAS_MAGIC, 0, 2)) {
-			return false;
-		}
-		format = FORMAT_RAS;
-		width = getIntBigEndian(a, 2);
-		height = getIntBigEndian(a, 6);
-		bitsPerPixel = getIntBigEndian(a, 10);
-		return (width > 0 && height > 0 && bitsPerPixel > 0 && bitsPerPixel <= 24);
-	}
+        int x = (int) (getIntLittleEndian(a, 36) * 0.0254);
 
-	// Written by Michael Aird.
-	private boolean checkSwf() throws IOException {
-		//get rid of the last byte of the signature, the byte of the version and 4 bytes of the size
-		byte[] a = new byte[6];
-		if (read(a) != a.length) {
-			return false;
-		}
-		format = FORMAT_SWF;
-		int bitSize = (int)readUBits( 5 );
-		int minX = (int)readSBits( bitSize );
-		int maxX = (int)readSBits( bitSize );
-		int minY = (int)readSBits( bitSize );
-		int maxY = (int)readSBits( bitSize );
-		width = maxX/20; //cause we're in twips
-		height = maxY/20;  //cause we're in twips
-		setPhysicalWidthDpi(72);
-		setPhysicalHeightDpi(72);
-		return (width > 0 && height > 0);
-	}
+        if (x > 0) {
+            setPhysicalWidthDpi(x);
+        }
 
-	/**
-	 * Run over String list, return false iff at least one of the arguments
-	 * equals <code>-c</code>.
-	 */
-	private static boolean determineVerbosity(String[] args) {
-		if (args != null && args.length > 0) {
-			for (int i = 0; i < args.length; i++) {
-				if ("-c".equals(args[i])) {
-					return false;
-				}
-			}
-		}
-		return true;
-	}
+        int y = (int) (getIntLittleEndian(a, 40) * 0.0254);
 
-	private boolean equals(byte[] a1, int offs1, byte[] a2, int offs2, int num) {
-		while (num-- > 0) {
-			if (a1[offs1++] != a2[offs2++]) {
-				return false;
-			}
-		}
-		return true;
-	}
+        if (y > 0) {
+            setPhysicalHeightDpi(y);
+        }
 
-	/** 
-	 * If {@link #check()} was successful, returns the image's number of bits per pixel.
-	 * Does not include transparency information like the alpha channel.
-	 * @return number of bits per image pixel
-	 */
-	public int getBitsPerPixel() {
-		return bitsPerPixel;
-	}
+        format = FORMAT_BMP;
 
-	/**
-	 * Returns the index'th comment retrieved from the image.
-	 * @throws IllegalArgumentException if index is smaller than 0 or larger than or equal
-	 * to the number of comments retrieved
-	 * @see #getNumberOfComments
-	 */
-	public String getComment(int index) {
-		if (comments == null || index < 0 || index >= comments.size()) {
-			throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_COMMENT_INDEX, "" + index));
-		}
-		return (String)comments.elementAt(index);
-	}
+        return true;
+    }
 
-	/**
-	 * If {@link #check()} was successful, returns the image format as one
-	 * of the FORMAT_xyz constants from this class.
-	 * Use {@link #getFormatName()} to get a textual description of the file format.
-	 * @return file format as a FORMAT_xyz constant
-	 */
-	public int getFormat() {
-		return format;
-	}
+    private boolean checkGif() throws IOException {
+        final byte[] gifMagic87a = {0x46, 0x38, 0x37, 0x61};
+        final byte[] gifMagic89a = {0x46, 0x38, 0x39, 0x61};
+        byte[] a = new byte[11]; // 4 from the GIF signature + 7 from the global header
 
-	/**
-	 * If {@link #check()} was successful, returns the image format's name.
-	 * Use {@link #getFormat()} to get a unique number.
-	 * @return file format name
-	 */
-	public String getFormatName() {
-		if (format >= 0 && format < FORMAT_NAMES.length) {
-			return FORMAT_NAMES[format];
-		} else {
-			return "?";
-		}
-	}
+        if (read(a) != 11) {
+            return false;
+        }
 
-	/** 
-	 * If {@link #check()} was successful, returns one the image's vertical
-	 * resolution in pixels.
-	 * @return image height in pixels
-	 */
-	public int getHeight() {
-		return height;
-	}
+        if ((!equals(a, 0, gifMagic89a, 0, 4)) && (!equals(a, 0, gifMagic87a, 0, 4))) {
+            return false;
+        }
 
-	private int getIntBigEndian(byte[] a, int offs) {
-		return
-			(a[offs] & 0xff) << 24 | 
-			(a[offs + 1] & 0xff) << 16 | 
-			(a[offs + 2] & 0xff) << 8 | 
-			a[offs + 3] & 0xff;
-	}
+        format = FORMAT_GIF;
+        width = getShortLittleEndian(a, 4);
+        height = getShortLittleEndian(a, 6);
 
-	private int getIntLittleEndian(byte[] a, int offs) {
-		return
-			(a[offs + 3] & 0xff) << 24 | 
-			(a[offs + 2] & 0xff) << 16 | 
-			(a[offs + 1] & 0xff) << 8 | 
-			a[offs] & 0xff;
-	}
+        int flags = a[8] & 0xff;
 
-	/** 
-	 * If {@link #check()} was successful, returns a String with the
-	 * MIME type of the format.
-	 * @return MIME type, e.g. <code>image/jpeg</code>
-	 */
-	public String getMimeType() {
-		if (format >= 0 && format < MIME_TYPE_STRINGS.length) {
-			if (format == FORMAT_JPEG && progressive)
-			{
-				return "image/pjpeg";
-			}
-			return MIME_TYPE_STRINGS[format];
-		} else {
-			return null;
-		}
-	}
+        bitsPerPixel = ((flags >> 4) & 0x07) + 1;
+        progressive = (flags & 0x02) != 0;
 
-	/**
-	 * If {@link #check()} was successful and {@link #setCollectComments(boolean)} was called with
-	 * <code>true</code> as argument, returns the number of comments retrieved 
-	 * from the input image stream / file.
-	 * Any number &gt;= 0 and smaller than this number of comments is then a
-	 * valid argument for the {@link #getComment(int)} method.
-	 * @return number of comments retrieved from input image
-	 */
-	public int getNumberOfComments()
-	{
-		if (comments == null) {
-			return 0;
-		} else {
-			return comments.size();
-		}
-	}
+        if (!determineNumberOfImages) {
+            return true;
+        }
 
-	/**
-	 * Returns the number of images in the examined file.
-	 * Assumes that <code>setDetermineImageNumber(true);</code> was called before
-	 * a successful call to {@link #check()}.
-	 * This value can currently be only different from <code>1</code> for GIF images.
-	 * @return number of images in file
-	 */
-	public int getNumberOfImages()
-	{
-		return numberOfImages;
-	}
+        // skip global color palette
+        if ((flags & 0x80) != 0) {
+            int tableSize = (1 << ((flags & 7) + 1)) * 3;
 
-	/**
-	 * Returns the physical height of this image in dots per inch (dpi).
-	 * Assumes that {@link #check()} was successful.
-	 * Returns <code>-1</code> on failure.
-	 * @return physical height (in dpi)
-	 * @see #getPhysicalWidthDpi()
-	 * @see #getPhysicalHeightInch()
-	 */
-	public int getPhysicalHeightDpi() {
-		return physicalHeightDpi;
-	}
+            skip(tableSize);
+        }
 
-	/**
-	 * If {@link #check()} was successful, returns the physical width of this image in dpi (dots per inch)
-	 * or -1 if no value could be found.
-	 * @return physical height (in dpi)
-	 * @see #getPhysicalHeightDpi()
-	 * @see #getPhysicalWidthDpi()
-	 * @see #getPhysicalWidthInch()
-	 */
-	public float getPhysicalHeightInch() {
-		int h = getHeight();
-		int ph = getPhysicalHeightDpi();
-		if (h > 0 && ph > 0) {
-			return ((float)h) / ((float)ph);
-		} else {
-			return -1.0f;
-		}
-	}
+        numberOfImages = 0;
 
-	/**
-	 * If {@link #check()} was successful, returns the physical width of this image in dpi (dots per inch)
-	 * or -1 if no value could be found.
-	 * @return physical width (in dpi)
-	 * @see #getPhysicalHeightDpi()
-	 * @see #getPhysicalWidthInch()
-	 * @see #getPhysicalHeightInch()
-	 */
-	public int getPhysicalWidthDpi() {
-		return physicalWidthDpi;
-	}
+        int blockType;
 
-	/**
-	 * Returns the physical width of an image in inches, or
-	 * <code>-1.0f</code> if width information is not available.
-	 * Assumes that {@link #check} has been called successfully.
-	 * @return physical width in inches or <code>-1.0f</code> on failure
-	 * @see #getPhysicalWidthDpi
-	 * @see #getPhysicalHeightInch
-	 */
-	public float getPhysicalWidthInch() {
-		int w = getWidth();
-		int pw = getPhysicalWidthDpi();
-		if (w > 0 && pw > 0) {
-			return ((float)w) / ((float)pw);
-		} else {
-			return -1.0f;
-		}
-	}
+        do {
+            blockType = read();
 
-	private int getShortBigEndian(byte[] a, int offs) {
-		return
-			(a[offs] & 0xff) << 8 | 
-			(a[offs + 1] & 0xff);
-	}
+            switch (blockType) {
+                case 0x2c : // image separator
+                {
+                    if (read(a, 0, 9) != 9) {
+                        return false;
+                    }
 
-	private int getShortLittleEndian(byte[] a, int offs) {
-		return (a[offs] & 0xff) | (a[offs + 1] & 0xff) << 8;
-	}
+                    flags = a[8] & 0xff;
 
-	/** 
-	 * If {@link #check()} was successful, returns one the image's horizontal
-	 * resolution in pixels.
-	 * @return image width in pixels
-	 */
-	public int getWidth() {
-		return width;
-	}
+                    int localBitsPerPixel = (flags & 0x07) + 1;
 
-	/**
-	 * Returns whether the image is stored in a progressive (also called: interlaced) way.
-	 * @return true for progressive/interlaced, false otherwise
-	 */
-	public boolean isProgressive()
-	{
-		return progressive;
-	}
+                    if (localBitsPerPixel > bitsPerPixel) {
+                        bitsPerPixel = localBitsPerPixel;
+                    }
 
-	/**
-	 * To use this class as a command line application, give it either 
-	 * some file names as parameters (information on them will be
-	 * printed to standard output, one line per file) or call
-	 * it with no parameters. It will then check data given to it
-	 * via standard input.
-	 * @param args the program arguments which must be file names
-	 */
-	public static void main(String[] args) {
-		ImageInfo imageInfo = new ImageInfo();
-		imageInfo.setDetermineImageNumber(true);
-		boolean verbose = determineVerbosity(args);
-		if (args.length == 0) {
-			run(null, System.in, imageInfo, verbose);
-		} else {
-			int index = 0;
-			while (index < args.length) {
-				InputStream in = null;
-				try {
-					String name = args[index++];
-					System.out.print(name + ";");
-					if (name.startsWith("http://")) {
-						in = new URL(name).openConnection().getInputStream();
-					} else {
-						in = new FileInputStream(name);
-					}
-					run(name, in, imageInfo, verbose);
-					in.close();
-				} catch (Exception e) {
-					System.out.println(e);
-					try {
-						in.close();
-					} catch (Exception ee) {
-					}
-				}
-			}
-		}
-	}
+                    if ((flags & 0x80) != 0) {
+                        skip((1 << localBitsPerPixel) * 3);
+                    }
 
-	private static void print(String sourceName, ImageInfo ii, boolean verbose) {
-		if (verbose) {
-			printVerbose(sourceName, ii);
-		} else {
-			printCompact(sourceName, ii);
-		}
-	}
+                    skip(1); // initial code length
 
-	private static void printCompact(String sourceName, ImageInfo imageInfo) {
-		System.out.println(
-			imageInfo.getFormatName() + ";" +
-			imageInfo.getMimeType() + ";" +
-			imageInfo.getWidth() + ";" +
-			imageInfo.getHeight() + ";" +
-			imageInfo.getBitsPerPixel() + ";" +
-			imageInfo.getNumberOfImages() + ";" +
-			imageInfo.getPhysicalWidthDpi() + ";" +
-			imageInfo.getPhysicalHeightDpi() + ";" +
-			imageInfo.getPhysicalWidthInch() + ";" +
-			imageInfo.getPhysicalHeightInch() + ";" +
-			imageInfo.isProgressive()
-		);
-	}
+                    int n;
 
-	private static void printLine(int indentLevels, String text, float value, float minValidValue) {
-		if (value < minValidValue) {
-			return;
-		}
-		printLine(indentLevels, text, Float.toString(value));
-	}
+                    do {
+                        n = read();
 
-	private static void printLine(int indentLevels, String text, int value, int minValidValue) {
-		if (value >= minValidValue) {
-			printLine(indentLevels, text, Integer.toString(value));
-		}
-	}
+                        if (n > 0) {
+                            skip(n);
+                        } else if (n == -1) {
+                            return false;
+                        }
+                    } while (n > 0);
 
-	private static void printLine(int indentLevels, String text, String value) {
-		if (value == null || value.length() == 0) {
-			return;
-		}
-		while (indentLevels-- > 0) {
-			System.out.print("\t");
-		}
-		if (text != null && text.length() > 0) {
-			System.out.print(text);
-			System.out.print(" ");
-		}
-		System.out.println(value);
-	}
+                    numberOfImages++;
 
-	private static void printVerbose(String sourceName, ImageInfo ii) {
-		printLine(0, null, sourceName);
-		printLine(1, "File format: ", ii.getFormatName());
-		printLine(1, "MIME type: ", ii.getMimeType());
-		printLine(1, "Width (pixels): ", ii.getWidth(), 1);
-		printLine(1, "Height (pixels): ", ii.getHeight(), 1);
-		printLine(1, "Bits per pixel: ", ii.getBitsPerPixel(), 1);
-		printLine(1, "Progressive: ", Boolean.toString(ii.isProgressive()));
-		printLine(1, "Number of images: ", ii.getNumberOfImages(), 1);
-		printLine(1, "Physical width (dpi): ", ii.getPhysicalWidthDpi(), 1);
-		printLine(1, "Physical height (dpi): ", ii.getPhysicalHeightDpi(), 1);
-		printLine(1, "Physical width (inches): ", ii.getPhysicalWidthInch(), 1.0f);
-		printLine(1, "Physical height (inches): ", ii.getPhysicalHeightInch(), 1.0f);
-		int numComments = ii.getNumberOfComments();
-		printLine(1, "Number of textual comments: ", numComments, 1);
-		if (numComments > 0) {
-			for (int i = 0; i < numComments; i++) {
-				printLine(2, null, ii.getComment(i));
-			}
-		}
-	}
+                    break;
+                }
 
-	private int read() throws IOException {
-		if (in != null) {
-			return in.read();
-		} else {
-			return din.readByte();
-		}
-	}
+                case 0x21 : // extension
+                {
+                    int extensionType = read();
 
-	private int read(byte[] a) throws IOException {
-		if (in != null) {
-			return in.read(a);
-		} else {
-			din.readFully(a);
-			return a.length;
-		}
-	}
+                    if (collectComments && (extensionType == 0xfe)) {
+                        StringBuffer sb = new StringBuffer();
+                        int n;
 
-	private int read(byte[] a, int offset, int num) throws IOException {
-		if (in != null) {
-			return in.read(a, offset, num);
-		} else {
-			din.readFully(a, offset, num);
-			return num;
-		}
-	}
+                        do {
+                            n = read();
 
-	private String readLine() throws IOException {
-		return readLine(new StringBuffer());
-	}
+                            if (n == -1) {
+                                return false;
+                            }
 
-	private String readLine(StringBuffer sb) throws IOException {
-		boolean finished;
-		do {
-			int value = read();
-			finished = (value == -1 || value == 10);
-			if (!finished) {
-				sb.append((char)value);
-			}
-		} while (!finished);
-		return sb.toString();
-	}
+                            if (n > 0) {
+                                for (int i = 0; i < n; i++) {
+                                    int ch = read();
 
-	private long readUBits( int numBits ) throws IOException
-	{
-		if (numBits == 0) {
-			return 0;
-		}
-		int bitsLeft = numBits;
-		long result = 0;
-		if (bitPos == 0) { //no value in the buffer - read a byte
-			if (in != null) {
-				bitBuf = in.read();
-			} else {
-				bitBuf = din.readByte();
-			}
-			bitPos = 8;
-		}
-        
-	    while( true )
-        {
+                                    if (ch == -1) {
+                                        return false;
+                                    }
+
+                                    sb.append((char) ch);
+                                }
+                            }
+                        } while (n > 0);
+                    } else {
+                        int n;
+
+                        do {
+                            n = read();
+
+                            if (n > 0) {
+                                skip(n);
+                            } else if (n == -1) {
+                                return false;
+                            }
+                        } while (n > 0);
+                    }
+
+                    break;
+                }
+
+                case 0x3b : // end of file
+                    break;
+
+                default : {
+                    return false;
+                }
+            }
+        } while (blockType != 0x3b);
+
+        return true;
+    }
+
+    private boolean checkIff() throws IOException {
+        byte[] a = new byte[10];
+
+        // read remaining 2 bytes of file id, 4 bytes file size
+        // and 4 bytes IFF subformat
+        if (read(a, 0, 10) != 10) {
+            return false;
+        }
+
+        final byte[] iffRm = {0x52, 0x4d};
+
+        if (!equals(a, 0, iffRm, 0, 2)) {
+            return false;
+        }
+
+        int type = getIntBigEndian(a, 6);
+
+        if ((type != 0x494c424d) && // type must be ILBM...
+                (type != 0x50424d20)) { // ...or PBM
+            return false;
+        }
+
+        // loop chunks to find BMHD chunk
+        do {
+            if (read(a, 0, 8) != 8) {
+                return false;
+            }
+
+            int chunkId = getIntBigEndian(a, 0);
+            int size = getIntBigEndian(a, 4);
+
+            if ((size & 1) == 1) {
+                size++;
+            }
+
+            if (chunkId == 0x424d4844) { // BMHD chunk
+                if (read(a, 0, 9) != 9) {
+                    return false;
+                }
+
+                format = FORMAT_IFF;
+                width = getShortBigEndian(a, 0);
+                height = getShortBigEndian(a, 2);
+                bitsPerPixel = a[8] & 0xff;
+
+                return (width > 0) && (height > 0) && (bitsPerPixel > 0) && (bitsPerPixel < 33);
+            } else {
+                skip(size);
+            }
+        } while (true);
+    }
+
+    private boolean checkJpeg() throws IOException {
+        byte[] data = new byte[12];
+
+        while (true) {
+            if (read(data, 0, 4) != 4) {
+                return false;
+            }
+
+            int marker = getShortBigEndian(data, 0);
+            int size = getShortBigEndian(data, 2);
+
+            if ((marker & 0xff00) != 0xff00) {
+                return false; // not a valid marker
+            }
+
+            if (marker == 0xffe0) { // APPx
+                if (size < 14) {
+                    return false; // APPx header must be >= 14 bytes
+                }
+
+                if (read(data, 0, 12) != 12) {
+                    return false;
+                }
+
+                final byte[] app0Id = {0x4a, 0x46, 0x49, 0x46, 0x00};
+
+                if (equals(app0Id, 0, data, 0, 5)) {
+
+                    // System.out.println("data 7=" + data[7]);
+                    if (data[7] == 1) {
+                        setPhysicalWidthDpi(getShortBigEndian(data, 8));
+                        setPhysicalHeightDpi(getShortBigEndian(data, 10));
+                    } else if (data[7] == 2) {
+                        int x = getShortBigEndian(data, 8);
+                        int y = getShortBigEndian(data, 10);
+
+                        setPhysicalWidthDpi((int) (x * 2.54f));
+                        setPhysicalHeightDpi((int) (y * 2.54f));
+                    }
+                }
+
+                skip(size - 14);
+            } else if (collectComments && (size > 2) && (marker == 0xfffe)) { // comment
+                size -= 2;
+
+                byte[] chars = new byte[size];
+
+                if (read(chars, 0, size) != size) {
+                    return false;
+                }
+
+                String comment = new String(chars, "iso-8859-1");
+
+                comment = comment.trim();
+                addComment(comment);
+            } else if ((marker >= 0xffc0) && (marker <= 0xffcf) && (marker != 0xffc4) && (marker != 0xffc8)) {
+                if (read(data, 0, 6) != 6) {
+                    return false;
+                }
+
+                format = FORMAT_JPEG;
+                bitsPerPixel = (data[0] & 0xff) * (data[5] & 0xff);
+                progressive = (marker == 0xffc2) || (marker == 0xffc6) || (marker == 0xffca) || (marker == 0xffce);
+                width = getShortBigEndian(data, 3);
+                height = getShortBigEndian(data, 1);
+
+                return true;
+            } else {
+                skip(size - 2);
+            }
+        }
+    }
+
+    private boolean checkPcx() throws IOException {
+        byte[] a = new byte[64];
+
+        if (read(a) != a.length) {
+            return false;
+        }
+
+        if (a[0] != 1) { // encoding, 1=RLE is only valid value
+            return false;
+        }
+
+        // width / height
+        int x1 = getShortLittleEndian(a, 2);
+        int y1 = getShortLittleEndian(a, 4);
+        int x2 = getShortLittleEndian(a, 6);
+        int y2 = getShortLittleEndian(a, 8);
+
+        if ((x1 < 0) || (x2 < x1) || (y1 < 0) || (y2 < y1)) {
+            return false;
+        }
+
+        width = x2 - x1 + 1;
+        height = y2 - y1 + 1;
+
+        // color depth
+        int bits = a[1];
+        int planes = a[63];
+
+        if ((planes == 1) && ((bits == 1) || (bits == 2) || (bits == 4) || (bits == 8))) {
+
+            // paletted
+            bitsPerPixel = bits;
+        } else if ((planes == 3) && (bits == 8)) {
+
+            // RGB truecolor
+            bitsPerPixel = 24;
+        } else {
+            return false;
+        }
+
+        setPhysicalWidthDpi(getShortLittleEndian(a, 10));
+        setPhysicalHeightDpi(getShortLittleEndian(a, 10));
+        format = FORMAT_PCX;
+
+        return true;
+    }
+
+    private boolean checkPng() throws IOException {
+        final byte[] pngMagic = {
+            0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
+        };
+        byte[] a = new byte[27];
+
+        if (read(a) != 27) {
+            return false;
+        }
+
+        if (!equals(a, 0, pngMagic, 0, 6)) {
+            return false;
+        }
+
+        format = FORMAT_PNG;
+        width = getIntBigEndian(a, 14);
+        height = getIntBigEndian(a, 18);
+        bitsPerPixel = a[22] & 0xff;
+
+        int colorType = a[23] & 0xff;
+
+        if ((colorType == 2) || (colorType == 6)) {
+            bitsPerPixel *= 3;
+        }
+
+        progressive = (a[26] & 0xff) != 0;
+
+        return true;
+    }
+
+    private boolean checkPnm(int id) throws IOException {
+        if ((id < 1) || (id > 6)) {
+            return false;
+        }
+
+        final int[] pnmFormats = {FORMAT_PBM, FORMAT_PGM, FORMAT_PPM};
+
+        format = pnmFormats[(id - 1) % 3];
+
+        boolean hasPixelResolution = false;
+        String s;
+
+        while (true) {
+            s = readLine();
+
+            if (s != null) {
+                s = s.trim();
+            }
+
+            if ((s == null) || (s.length() < 1)) {
+                continue;
+            }
+
+            if (s.charAt(0) == '#') { // comment
+                if (collectComments && (s.length() > 1)) {
+                    addComment(s.substring(1));
+                }
+
+                continue;
+            }
+
+            if (!hasPixelResolution) { // split "343 966" into width=343, height=966
+                int spaceIndex = s.indexOf(' ');
+
+                if (spaceIndex == -1) {
+                    return false;
+                }
+
+                String widthString = s.substring(0, spaceIndex);
+
+                spaceIndex = s.lastIndexOf(' ');
+
+                if (spaceIndex == -1) {
+                    return false;
+                }
+
+                String heightString = s.substring(spaceIndex + 1);
+
+                try {
+                    width = Integer.parseInt(widthString);
+                    height = Integer.parseInt(heightString);
+                } catch (NumberFormatException nfe) {
+                    return false;
+                }
+
+                if ((width < 1) || (height < 1)) {
+                    return false;
+                }
+
+                if (format == FORMAT_PBM) {
+                    bitsPerPixel = 1;
+
+                    return true;
+                }
+
+                hasPixelResolution = true;
+            } else {
+                int maxSample;
+
+                try {
+                    maxSample = Integer.parseInt(s);
+                } catch (NumberFormatException nfe) {
+                    return false;
+                }
+
+                if (maxSample < 0) {
+                    return false;
+                }
+
+                for (int i = 0; i < 25; i++) {
+                    if (maxSample < (1 << (i + 1))) {
+                        bitsPerPixel = i + 1;
+
+                        if (format == FORMAT_PPM) {
+                            bitsPerPixel *= 3;
+                        }
+
+                        return true;
+                    }
+                }
+
+                return false;
+            }
+        }
+    }
+
+    private boolean checkPsd() throws IOException {
+        byte[] a = new byte[24];
+
+        if (read(a) != a.length) {
+            return false;
+        }
+
+        final byte[] psdMagic = {0x50, 0x53};
+
+        if (!equals(a, 0, psdMagic, 0, 2)) {
+            return false;
+        }
+
+        format = FORMAT_PSD;
+        width = getIntBigEndian(a, 16);
+        height = getIntBigEndian(a, 12);
+
+        int channels = getShortBigEndian(a, 10);
+        int depth = getShortBigEndian(a, 20);
+
+        bitsPerPixel = channels * depth;
+
+        return (width > 0) && (height > 0) && (bitsPerPixel > 0) && (bitsPerPixel <= 64);
+    }
+
+    private boolean checkRas() throws IOException {
+        byte[] a = new byte[14];
+
+        if (read(a) != a.length) {
+            return false;
+        }
+
+        final byte[] rasMagic = {0x6a, (byte) 0x95};
+
+        if (!equals(a, 0, rasMagic, 0, 2)) {
+            return false;
+        }
+
+        format = FORMAT_RAS;
+        width = getIntBigEndian(a, 2);
+        height = getIntBigEndian(a, 6);
+        bitsPerPixel = getIntBigEndian(a, 10);
+
+        return (width > 0) && (height > 0) && (bitsPerPixel > 0) && (bitsPerPixel <= 24);
+    }
+
+    // Written by Michael Aird.
+    private boolean checkSwf() throws IOException {
+
+        // get rid of the last byte of the signature, the byte of the version and 4 bytes of the size
+        byte[] a = new byte[6];
+
+        if (read(a) != a.length) {
+            return false;
+        }
+
+        format = FORMAT_SWF;
+
+        int bitSize = (int) readUBits(5);
+        int minX = (int) readSBits(bitSize);
+        int maxX = (int) readSBits(bitSize);
+        int minY = (int) readSBits(bitSize);
+        int maxY = (int) readSBits(bitSize);
+
+        width = maxX / 20; // cause we're in twips
+        height = maxY / 20; // cause we're in twips
+        setPhysicalWidthDpi(72);
+        setPhysicalHeightDpi(72);
+
+        return (width > 0) && (height > 0);
+    }
+
+    /**
+     * Run over String list, return false iff at least one of the arguments
+     * equals <code>-c</code>.
+     */
+    private static boolean determineVerbosity(String[] args) {
+        if ((args != null) && (args.length > 0)) {
+            for (int i = 0; i < args.length; i++) {
+                if ("-c".equals(args[i])) {
+                    return false;
+                }
+            }
+        }
+
+        return true;
+    }
+
+    private boolean equals(byte[] a1, int offs1, byte[] a2, int offs2, int num) {
+        while (num-- > 0) {
+            if (a1[offs1++] != a2[offs2++]) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * If {@link #check()} was successful, returns the image's number of bits per pixel.
+     * Does not include transparency information like the alpha channel.
+     * @return number of bits per image pixel
+     */
+    public int getBitsPerPixel() {
+        return bitsPerPixel;
+    }
+
+    /**
+     * Returns the index'th comment retrieved from the image.
+     * @throws IllegalArgumentException if index is smaller than 0 or larger than or equal
+     * to the number of comments retrieved
+     * @see #getNumberOfComments
+     */
+    public String getComment(int index) {
+        if ((comments == null) || (index < 0) || (index >= comments.size())) {
+            throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_COMMENT_INDEX, "" + index));
+        }
+
+        return (String) comments.elementAt(index);
+    }
+
+    /**
+     * If {@link #check()} was successful, returns the image format as one
+     * of the FORMAT_xyz constants from this class.
+     * Use {@link #getFormatName()} to get a textual description of the file format.
+     * @return file format as a FORMAT_xyz constant
+     */
+    public int getFormat() {
+        return format;
+    }
+
+    /**
+     * If {@link #check()} was successful, returns the image format's name.
+     * Use {@link #getFormat()} to get a unique number.
+     * @return file format name
+     */
+    public String getFormatName() {
+        if ((format >= 0) && (format < FORMAT_NAMES.length)) {
+            return FORMAT_NAMES[format];
+        } else {
+            return "?";
+        }
+    }
+
+    /**
+     * If {@link #check()} was successful, returns one the image's vertical
+     * resolution in pixels.
+     * @return image height in pixels
+     */
+    public int getHeight() {
+        return height;
+    }
+
+    private int getIntBigEndian(byte[] a, int offs) {
+        return (a[offs] & 0xff) << 24 | (a[offs + 1] & 0xff) << 16 | (a[offs + 2] & 0xff) << 8 | a[offs + 3] & 0xff;
+    }
+
+    private int getIntLittleEndian(byte[] a, int offs) {
+        return (a[offs + 3] & 0xff) << 24 | (a[offs + 2] & 0xff) << 16 | (a[offs + 1] & 0xff) << 8 | a[offs] & 0xff;
+    }
+
+    /**
+     * If {@link #check()} was successful, returns a String with the
+     * MIME type of the format.
+     * @return MIME type, e.g. <code>image/jpeg</code>
+     */
+    public String getMimeType() {
+        if ((format >= 0) && (format < MIME_TYPE_STRINGS.length)) {
+            if ((format == FORMAT_JPEG) && progressive) {
+                return "image/pjpeg";
+            }
+
+            return MIME_TYPE_STRINGS[format];
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * If {@link #check()} was successful and {@link #setCollectComments(boolean)} was called with
+     * <code>true</code> as argument, returns the number of comments retrieved
+     * from the input image stream / file.
+     * Any number &gt;= 0 and smaller than this number of comments is then a
+     * valid argument for the {@link #getComment(int)} method.
+     * @return number of comments retrieved from input image
+     */
+    public int getNumberOfComments() {
+        if (comments == null) {
+            return 0;
+        } else {
+            return comments.size();
+        }
+    }
+
+    /**
+     * Returns the number of images in the examined file.
+     * Assumes that <code>setDetermineImageNumber(true);</code> was called before
+     * a successful call to {@link #check()}.
+     * This value can currently be only different from <code>1</code> for GIF images.
+     * @return number of images in file
+     */
+    public int getNumberOfImages() {
+        return numberOfImages;
+    }
+
+    /**
+     * Returns the physical height of this image in dots per inch (dpi).
+     * Assumes that {@link #check()} was successful.
+     * Returns <code>-1</code> on failure.
+     * @return physical height (in dpi)
+     * @see #getPhysicalWidthDpi()
+     * @see #getPhysicalHeightInch()
+     */
+    public int getPhysicalHeightDpi() {
+        return physicalHeightDpi;
+    }
+
+    /**
+     * If {@link #check()} was successful, returns the physical width of this image in dpi (dots per inch)
+     * or -1 if no value could be found.
+     * @return physical height (in dpi)
+     * @see #getPhysicalHeightDpi()
+     * @see #getPhysicalWidthDpi()
+     * @see #getPhysicalWidthInch()
+     */
+    public float getPhysicalHeightInch() {
+        int h = getHeight();
+        int ph = getPhysicalHeightDpi();
+
+        if ((h > 0) && (ph > 0)) {
+            return ((float) h) / ((float) ph);
+        } else {
+            return -1.0f;
+        }
+    }
+
+    /**
+     * If {@link #check()} was successful, returns the physical width of this image in dpi (dots per inch)
+     * or -1 if no value could be found.
+     * @return physical width (in dpi)
+     * @see #getPhysicalHeightDpi()
+     * @see #getPhysicalWidthInch()
+     * @see #getPhysicalHeightInch()
+     */
+    public int getPhysicalWidthDpi() {
+        return physicalWidthDpi;
+    }
+
+    /**
+     * Returns the physical width of an image in inches, or
+     * <code>-1.0f</code> if width information is not available.
+     * Assumes that {@link #check} has been called successfully.
+     * @return physical width in inches or <code>-1.0f</code> on failure
+     * @see #getPhysicalWidthDpi
+     * @see #getPhysicalHeightInch
+     */
+    public float getPhysicalWidthInch() {
+        int w = getWidth();
+        int pw = getPhysicalWidthDpi();
+
+        if ((w > 0) && (pw > 0)) {
+            return ((float) w) / ((float) pw);
+        } else {
+            return -1.0f;
+        }
+    }
+
+    private int getShortBigEndian(byte[] a, int offs) {
+        return (a[offs] & 0xff) << 8 | (a[offs + 1] & 0xff);
+    }
+
+    private int getShortLittleEndian(byte[] a, int offs) {
+        return (a[offs] & 0xff) | (a[offs + 1] & 0xff) << 8;
+    }
+
+    /**
+     * If {@link #check()} was successful, returns one the image's horizontal
+     * resolution in pixels.
+     * @return image width in pixels
+     */
+    public int getWidth() {
+        return width;
+    }
+
+    /**
+     * Returns whether the image is stored in a progressive (also called: interlaced) way.
+     * @return true for progressive/interlaced, false otherwise
+     */
+    public boolean isProgressive() {
+        return progressive;
+    }
+
+    /**
+     * To use this class as a command line application, give it either
+     * some file names as parameters (information on them will be
+     * printed to standard output, one line per file) or call
+     * it with no parameters. It will then check data given to it
+     * via standard input.
+     * @param args the program arguments which must be file names
+     */
+    public static void main(String[] args) {
+        ImageInfo imageInfo = new ImageInfo();
+
+        imageInfo.setDetermineImageNumber(true);
+
+        boolean verbose = determineVerbosity(args);
+
+        if (args.length == 0) {
+            run(null, System.in, imageInfo, verbose);
+        } else {
+            int index = 0;
+
+            while (index < args.length) {
+                InputStream in = null;
+
+                try {
+                    String name = args[index++];
+
+                    System.out.print(name + ";");
+
+                    if (name.startsWith("http://")) {
+                        in = new URL(name).openConnection().getInputStream();
+                    } else {
+                        in = new FileInputStream(name);
+                    }
+
+                    run(name, in, imageInfo, verbose);
+                    in.close();
+                } catch (Exception e) {
+                    System.out.println(e);
+
+                    try {
+                        in.close();
+                    } catch (Exception ee) {
+
+                        // TODO Refactoring
+                    }
+                }
+            }
+        }
+    }
+
+    private static void print(String sourceName, ImageInfo ii, boolean verbose) {
+        if (verbose) {
+            printVerbose(sourceName, ii);
+        } else {
+            printCompact(sourceName, ii);
+        }
+    }
+
+    private static void printCompact(String sourceName, ImageInfo imageInfo) {
+        System.out.println(imageInfo.getFormatName() + ";" + imageInfo.getMimeType() + ";" + imageInfo.getWidth() + ";"
+                           + imageInfo.getHeight() + ";" + imageInfo.getBitsPerPixel() + ";"
+                           + imageInfo.getNumberOfImages() + ";" + imageInfo.getPhysicalWidthDpi() + ";"
+                           + imageInfo.getPhysicalHeightDpi() + ";" + imageInfo.getPhysicalWidthInch() + ";"
+                           + imageInfo.getPhysicalHeightInch() + ";" + imageInfo.isProgressive());
+    }
+
+    private static void printLine(int indentLevels, String text, float value, float minValidValue) {
+        if (value < minValidValue) {
+            return;
+        }
+
+        printLine(indentLevels, text, Float.toString(value));
+    }
+
+    private static void printLine(int indentLevels, String text, int value, int minValidValue) {
+        if (value >= minValidValue) {
+            printLine(indentLevels, text, Integer.toString(value));
+        }
+    }
+
+    private static void printLine(int indentLevels, String text, String value) {
+        if ((value == null) || (value.length() == 0)) {
+            return;
+        }
+
+        while (indentLevels-- > 0) {
+            System.out.print("\t");
+        }
+
+        if ((text != null) && (text.length() > 0)) {
+            System.out.print(text);
+            System.out.print(" ");
+        }
+
+        System.out.println(value);
+    }
+
+    private static void printVerbose(String sourceName, ImageInfo ii) {
+        printLine(0, null, sourceName);
+        printLine(1, "File format: ", ii.getFormatName());
+        printLine(1, "MIME type: ", ii.getMimeType());
+        printLine(1, "Width (pixels): ", ii.getWidth(), 1);
+        printLine(1, "Height (pixels): ", ii.getHeight(), 1);
+        printLine(1, "Bits per pixel: ", ii.getBitsPerPixel(), 1);
+        printLine(1, "Progressive: ", Boolean.toString(ii.isProgressive()));
+        printLine(1, "Number of images: ", ii.getNumberOfImages(), 1);
+        printLine(1, "Physical width (dpi): ", ii.getPhysicalWidthDpi(), 1);
+        printLine(1, "Physical height (dpi): ", ii.getPhysicalHeightDpi(), 1);
+        printLine(1, "Physical width (inches): ", ii.getPhysicalWidthInch(), 1.0f);
+        printLine(1, "Physical height (inches): ", ii.getPhysicalHeightInch(), 1.0f);
+
+        int numComments = ii.getNumberOfComments();
+
+        printLine(1, "Number of textual comments: ", numComments, 1);
+
+        if (numComments > 0) {
+            for (int i = 0; i < numComments; i++) {
+                printLine(2, null, ii.getComment(i));
+            }
+        }
+    }
+
+    private int read() throws IOException {
+        if (in != null) {
+            return in.read();
+        } else {
+            return din.readByte();
+        }
+    }
+
+    private int read(byte[] a) throws IOException {
+        if (in != null) {
+            return in.read(a);
+        } else {
+            din.readFully(a);
+
+            return a.length;
+        }
+    }
+
+    private int read(byte[] a, int offset, int num) throws IOException {
+        if (in != null) {
+            return in.read(a, offset, num);
+        } else {
+            din.readFully(a, offset, num);
+
+            return num;
+        }
+    }
+
+    private String readLine() throws IOException {
+        return readLine(new StringBuffer());
+    }
+
+    private String readLine(StringBuffer sb) throws IOException {
+        boolean finished;
+
+        do {
+            int value = read();
+
+            finished = (value == -1) || (value == 10);
+
+            if (!finished) {
+                sb.append((char) value);
+            }
+        } while (!finished);
+
+        return sb.toString();
+    }
+
+    private long readUBits(int numBits) throws IOException {
+        if (numBits == 0) {
+            return 0;
+        }
+
+        int bitsLeft = numBits;
+        long result = 0;
+
+        if (bitPos == 0) { // no value in the buffer - read a byte
+            if (in != null) {
+                bitBuf = in.read();
+            } else {
+                bitBuf = din.readByte();
+            }
+
+            bitPos = 8;
+        }
+
+        while (true) {
             int shift = bitsLeft - bitPos;
-            if( shift > 0 )
-            {
+
+            if (shift > 0) {
+
                 // Consume the entire buffer
                 result |= bitBuf << shift;
                 bitsLeft -= bitPos;
 
                 // Get the next byte from the input stream
                 if (in != null) {
-                  bitBuf = in.read();
+                    bitBuf = in.read();
                 } else {
-                  bitBuf = din.readByte();
+                    bitBuf = din.readByte();
                 }
+
                 bitPos = 8;
-            }
-            else
-            {
-             	// Consume a portion of the buffer
+            } else {
+
+                // Consume a portion of the buffer
                 result |= bitBuf >> -shift;
                 bitPos -= bitsLeft;
-                bitBuf &= 0xff >> (8 - bitPos);	// mask off the consumed bits
+                bitBuf &= 0xff >> (8 - bitPos); // mask off the consumed bits
 
                 return result;
             }
-        }        
+        }
     }
-    
-        /**
+
+    /**
      * Read a signed value from the given number of bits
      */
-    private int readSBits( int numBits ) throws IOException
-    {
+    private int readSBits(int numBits) throws IOException {
+
         // Get the number as an unsigned value.
-        long uBits = readUBits( numBits );
+        long uBits = readUBits(numBits);
 
         // Is the number negative?
-        if( ( uBits & (1L << (numBits - 1))) != 0 )
-        {
+        if ((uBits & (1L << (numBits - 1))) != 0) {
+
             // Yes. Extend the sign.
             uBits |= -1L << numBits;
         }
 
-        return (int)uBits;        
-    }  
-   
-	private void synchBits()
-	{
-		bitBuf = 0;
-		bitPos = 0;
-	}
+        return (int) uBits;
+    }
 
-	private String readLine(int firstChar) throws IOException {
-		StringBuffer result = new StringBuffer();
-		result.append((char)firstChar);
-		return readLine(result);
-	}
+    private void synchBits() {
+        bitBuf = 0;
+        bitPos = 0;
+    }
 
-	private static void run(String sourceName, InputStream in, ImageInfo imageInfo, boolean verbose) {
-		imageInfo.setInput(in);
-		imageInfo.setDetermineImageNumber(false);
-		imageInfo.setCollectComments(verbose);
-		if (imageInfo.check()) {
-			print(sourceName, imageInfo, verbose);
-		}
-	}
+    private String readLine(int firstChar) throws IOException {
+        StringBuffer result = new StringBuffer();
 
-	/**
-	 * Specify whether textual comments are supposed to be extracted from input.
-	 * Default is <code>false</code>.
-	 * If enabled, comments will be added to an internal list.
-	 * @param newValue if <code>true</code>, this class will read comments
-	 * @see #getNumberOfComments
-	 * @see #getComment
-	 */
-	public void setCollectComments(boolean newValue)
-	{
-		collectComments = newValue;
-	}
+        result.append((char) firstChar);
 
-	/**
-	 * Specify whether the number of images in a file is to be
-	 * determined - default is <code>false</code>.
-	 * This is a special option because some file formats require running over
-	 * the entire file to find out the number of images, a rather time-consuming
-	 * task.
-	 * Not all file formats support more than one image.
-	 * If this method is called with <code>true</code> as argument,
-	 * the actual number of images can be queried via 
-	 * {@link #getNumberOfImages()} after a successful call to
-	 * {@link #check()}.
-	 * @param newValue will the number of images be determined?
-	 * @see #getNumberOfImages
-	 */
-	public void setDetermineImageNumber(boolean newValue)
-	{
-		determineNumberOfImages = newValue;
-	}
+        return readLine(result);
+    }
 
-	/**
-	 * Set the input stream to the argument stream (or file). 
-	 * Note that {@link java.io.RandomAccessFile} implements
-	 * {@link java.io.DataInput}.
-	 * @param dataInput the input stream to read from
-	 */
-	public void setInput(DataInput dataInput) {
-		din = dataInput;
-		in = null;
-	}
+    private static void run(String sourceName, InputStream in, ImageInfo imageInfo, boolean verbose) {
+        imageInfo.setInput(in);
+        imageInfo.setDetermineImageNumber(false);
+        imageInfo.setCollectComments(verbose);
 
-	/**
-	 * Set the input stream to the argument stream (or file).
-	 * @param inputStream the input stream to read from
-	 */
-	public void setInput(InputStream inputStream) {
-		in = inputStream;
-		din = null;
-	}
+        if (imageInfo.check()) {
+            print(sourceName, imageInfo, verbose);
+        }
+    }
 
-	private void setPhysicalHeightDpi(int newValue) {
-		physicalWidthDpi = newValue;
-	}
+    /**
+     * Specify whether textual comments are supposed to be extracted from input.
+     * Default is <code>false</code>.
+     * If enabled, comments will be added to an internal list.
+     * @param newValue if <code>true</code>, this class will read comments
+     * @see #getNumberOfComments
+     * @see #getComment
+     */
+    public void setCollectComments(boolean newValue) {
+        collectComments = newValue;
+    }
 
-	private void setPhysicalWidthDpi(int newValue) {
-		physicalHeightDpi = newValue;
-	}
+    /**
+     * Specify whether the number of images in a file is to be
+     * determined - default is <code>false</code>.
+     * This is a special option because some file formats require running over
+     * the entire file to find out the number of images, a rather time-consuming
+     * task.
+     * Not all file formats support more than one image.
+     * If this method is called with <code>true</code> as argument,
+     * the actual number of images can be queried via
+     * {@link #getNumberOfImages()} after a successful call to
+     * {@link #check()}.
+     * @param newValue will the number of images be determined?
+     * @see #getNumberOfImages
+     */
+    public void setDetermineImageNumber(boolean newValue) {
+        determineNumberOfImages = newValue;
+    }
 
-	private void skip(int num) throws IOException {
-		while (num > 0) {
-			long result;
-			if (in != null) {
-				result = in.skip(num);
-			} else {
-				result = din.skipBytes(num);
-			}
-			if (result > 0) {
-				num -= result;
-			}
-		}
-	}
+    /**
+     * Set the input stream to the argument stream (or file).
+     * Note that {@link java.io.RandomAccessFile} implements
+     * {@link java.io.DataInput}.
+     * @param dataInput the input stream to read from
+     */
+    public void setInput(DataInput dataInput) {
+        din = dataInput;
+        in = null;
+    }
+
+    /**
+     * Set the input stream to the argument stream (or file).
+     * @param inputStream the input stream to read from
+     */
+    public void setInput(InputStream inputStream) {
+        in = inputStream;
+        din = null;
+    }
+
+    private void setPhysicalHeightDpi(int newValue) {
+        physicalWidthDpi = newValue;
+    }
+
+    private void setPhysicalWidthDpi(int newValue) {
+        physicalHeightDpi = newValue;
+    }
+
+    private void skip(int num) throws IOException {
+        while (num > 0) {
+            long result;
+
+            if (in != null) {
+                result = in.skip(num);
+            } else {
+                result = din.skipBytes(num);
+            }
+
+            if (result > 0) {
+                num -= result;
+            }
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/image/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/image/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/resource/image/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Image resources support classes
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/CapturingELResolver.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/CapturingELResolver.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/CapturingELResolver.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,53 +19,52 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
+import org.ajax4jsf.el.ELResolverWrapper;
+
 import javax.el.ELContext;
 import javax.el.ELResolver;
 
-import org.ajax4jsf.el.ELResolverWrapper;
-
 /**
  * @author Nick Belaevski
  * @since 3.3.0
  */
-
 class CapturingELResolver extends ELResolverWrapper {
+    private Object base;
+    private Object property;
 
-	private Object base;
-	
-	private Object property;
-	
-	public CapturingELResolver(ELResolver resolver) {
-		super(resolver);
-	}
+    public CapturingELResolver(ELResolver resolver) {
+        super(resolver);
+    }
 
-	@Override
-	public Object getValue(ELContext context, Object base, Object property) {
-		if (base != null && property != null) {
-			this.base = base;
-			this.property = property;
-		}
+    @Override
+    public Object getValue(ELContext context, Object base, Object property) {
+        if ((base != null) && (property != null)) {
+            this.base = base;
+            this.property = property;
+        }
 
-		return super.getValue(context, base, property);
-	}
-	
-	@Override
-	public Class<?> getType(ELContext context, Object base, Object property) {
-		if (base != null && property != null) {
-			this.base = base;
-			this.property = property;
-		}
+        return super.getValue(context, base, property);
+    }
 
-		return super.getType(context, base, property);
-	}
-	
-	public Object getBase() {
-		return base;
-	}
-	
-	public Object getProperty() {
-		return property;
-	}
+    @Override
+    public Class<?> getType(ELContext context, Object base, Object property) {
+        if ((base != null) && (property != null)) {
+            this.base = base;
+            this.property = property;
+        }
+
+        return super.getType(context, base, property);
+    }
+
+    public Object getBase() {
+        return base;
+    }
+
+    public Object getProperty() {
+        return property;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/ELUtils.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/ELUtils.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/ELUtils.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,16 +18,24 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.util;
 
+import org.ajax4jsf.el.ELContextWrapper;
+import org.ajax4jsf.util.GenericsIntrospectionCache.GenericsCacheEntry;
+
 import java.beans.BeanInfo;
 import java.beans.IntrospectionException;
 import java.beans.Introspector;
 import java.beans.PropertyDescriptor;
+
 import java.lang.ref.SoftReference;
 import java.lang.reflect.Method;
 import java.lang.reflect.ParameterizedType;
 import java.lang.reflect.Type;
+
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.Map;
@@ -35,147 +43,151 @@
 
 import javax.el.ELContext;
 import javax.el.ValueExpression;
+
 import javax.faces.FacesException;
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.el.ELContextWrapper;
-import org.ajax4jsf.util.GenericsIntrospectionCache.GenericsCacheEntry;
-
 /**
  * @author asmirnov
  *
  */
-public class ELUtils {
-	
-	private ELUtils() {
-		// Utility class with static methods only - do not instantiate.
-	}
+public final class ELUtils {
+    private ELUtils() {
 
-	/**
-	 * Get EL-enabled value. Return same string, if not el-expression.
-	 * Otherthise, return parsed and evaluated expression.
-	 * 
-	 * @param context -
-	 *            current Faces Context.
-	 * @param value -
-	 *            string to parse.
-	 * @return - interpreted el or unmodified value.
-	 */
-	public static boolean isValueReference(String value) {
-		if (value == null)
-			return false;
+        // Utility class with static methods only - do not instantiate.
+    }
 
-		int start = value.indexOf("#{");
-		if (start >= 0) {
-			int end = value.lastIndexOf('}');
-			if (end >= 0 && start < end) {
-				return true;
-			}
-		}
-		return false;
-	}
+    /**
+     * Get EL-enabled value. Return same string, if not el-expression.
+     * Otherthise, return parsed and evaluated expression.
+     *
+     * @param context -
+     *            current Faces Context.
+     * @param value -
+     *            string to parse.
+     * @return - interpreted el or unmodified value.
+     */
+    public static boolean isValueReference(String value) {
+        if (value == null) {
+            return false;
+        }
 
-	private static Class<?> resolveType(Type type) {
-		Class<?> result = Object.class;
-		
-		if (type instanceof ParameterizedType) {
-			ParameterizedType parameterizedType = (ParameterizedType) type;
-			Type[] types = parameterizedType.getActualTypeArguments();
-			if (types != null && types.length != 0) {
-				Type actualType = types[0];
-				if (actualType instanceof Class) {
-					result = (Class<?>) actualType;
-				}
-			}
-		}
+        int start = value.indexOf("#{");
 
-		return result;
-	}
-	
-	private static BeanInfo getBeanInfo(Class<?> beanClass, GenericsCacheEntry entry) {
-		BeanInfo beanInfo = null;
-		
-		SoftReference<BeanInfo> beanInfoReference = entry.beanInfoReference;
-		if (beanInfoReference != null) {
-			beanInfo = beanInfoReference.get();
-		}
-		
-		if (beanInfo == null) {
-			try {
-				beanInfo = Introspector.getBeanInfo(beanClass);
-				entry.beanInfoReference = new SoftReference<BeanInfo>(beanInfo);
-			} catch (IntrospectionException e) {
-				throw new FacesException(e.getMessage(), e);
-			}
-		}
-		
-		return beanInfo;
-	}
+        if (start >= 0) {
+            int end = value.lastIndexOf('}');
 
-	private static Class<?> getGenericCollectionType(FacesContext context, Object base, String propertyName) {
-		Class<?> genericPropertyClass = null;
-		
-		if (base != null && propertyName != null) {
-			Class<? extends Object> beanClass = base.getClass();
+            if ((end >= 0) && (start < end)) {
+                return true;
+            }
+        }
 
-			//Map and ResourceBundle have special resolvers that we doesn't support
-			if (!Map.class.isAssignableFrom(beanClass) && !ResourceBundle.class.isAssignableFrom(beanClass)) {
-				
-				GenericsIntrospectionCache introspectionCache = GenericsIntrospectionCache.getInstance(context);
+        return false;
+    }
 
-				synchronized (introspectionCache) {
-					GenericsCacheEntry cacheEntry = introspectionCache.getGenericCacheEntry(beanClass);
-					
-					if (cacheEntry.genericPropertiesClasses == null) {
-						cacheEntry.genericPropertiesClasses = new HashMap<String, Class<?>>();
-					} else {
-						genericPropertyClass = cacheEntry.genericPropertiesClasses.get(propertyName);
-					}
-					
-					if (genericPropertyClass == null) {
-						if (!cacheEntry.genericPropertiesClasses.containsKey(propertyName)) {
-							BeanInfo beanInfo = getBeanInfo(beanClass, cacheEntry);
+    private static Class<?> resolveType(Type type) {
+        Class<?> result = Object.class;
 
-							PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
-							for (PropertyDescriptor pd : descriptors) {
-								if (propertyName.equals(pd.getName())) {
-									Method readMethod = pd.getReadMethod();
-								
-									genericPropertyClass = resolveType(readMethod.getGenericReturnType());
-									break;
-								}
-							}
-							
-							cacheEntry.genericPropertiesClasses.put(propertyName, genericPropertyClass);
-						} else {
-							//property Class has been already resolved as null
-						}
-					}
-				}
-			}
-		}
-		
-		return genericPropertyClass;
-	}
-	
-	public static Class<?> getContainerClass(FacesContext facesContext, ValueExpression expression) {
-		ELContext initialELContext = facesContext.getELContext();
+        if (type instanceof ParameterizedType) {
+            ParameterizedType parameterizedType = (ParameterizedType) type;
+            Type[] types = parameterizedType.getActualTypeArguments();
 
-		CapturingELResolver capturingELResolver = new CapturingELResolver(initialELContext.getELResolver());
-		Class<?> type = expression.getType(new ELContextWrapper(initialELContext, capturingELResolver));
+            if ((types != null) && (types.length != 0)) {
+                Type actualType = types[0];
 
-		Class<?> containerType = type.getComponentType();
-		if (containerType == null && type != null) {
-			if (Collection.class.isAssignableFrom(type)) {
-				Object base = capturingELResolver.getBase();
-				Object property = capturingELResolver.getProperty();
-				
-				if (base != null && property != null) {
-					containerType = getGenericCollectionType(facesContext, base, property.toString());
-				}
-			}
-		}
-		
-		return containerType;
-	}
+                if (actualType instanceof Class) {
+                    result = (Class<?>) actualType;
+                }
+            }
+        }
+
+        return result;
+    }
+
+    private static BeanInfo getBeanInfo(Class<?> beanClass, GenericsCacheEntry entry) {
+        BeanInfo beanInfo = null;
+        SoftReference<BeanInfo> beanInfoReference = entry.beanInfoReference;
+
+        if (beanInfoReference != null) {
+            beanInfo = beanInfoReference.get();
+        }
+
+        if (beanInfo == null) {
+            try {
+                beanInfo = Introspector.getBeanInfo(beanClass);
+                entry.beanInfoReference = new SoftReference<BeanInfo>(beanInfo);
+            } catch (IntrospectionException e) {
+                throw new FacesException(e.getMessage(), e);
+            }
+        }
+
+        return beanInfo;
+    }
+
+    private static Class<?> getGenericCollectionType(FacesContext context, Object base, String propertyName) {
+        Class<?> genericPropertyClass = null;
+
+        if ((base != null) && (propertyName != null)) {
+            Class<? extends Object> beanClass = base.getClass();
+
+            // Map and ResourceBundle have special resolvers that we doesn't support
+            if (!Map.class.isAssignableFrom(beanClass) && !ResourceBundle.class.isAssignableFrom(beanClass)) {
+                GenericsIntrospectionCache introspectionCache = GenericsIntrospectionCache.getInstance(context);
+
+                synchronized (introspectionCache) {
+                    GenericsCacheEntry cacheEntry = introspectionCache.getGenericCacheEntry(beanClass);
+
+                    if (cacheEntry.genericPropertiesClasses == null) {
+                        cacheEntry.genericPropertiesClasses = new HashMap<String, Class<?>>();
+                    } else {
+                        genericPropertyClass = cacheEntry.genericPropertiesClasses.get(propertyName);
+                    }
+
+                    if (genericPropertyClass == null) {
+                        if (!cacheEntry.genericPropertiesClasses.containsKey(propertyName)) {
+                            BeanInfo beanInfo = getBeanInfo(beanClass, cacheEntry);
+                            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
+
+                            for (PropertyDescriptor pd : descriptors) {
+                                if (propertyName.equals(pd.getName())) {
+                                    Method readMethod = pd.getReadMethod();
+
+                                    genericPropertyClass = resolveType(readMethod.getGenericReturnType());
+
+                                    break;
+                                }
+                            }
+
+                            cacheEntry.genericPropertiesClasses.put(propertyName, genericPropertyClass);
+                        } else {
+
+                            // property Class has been already resolved as null
+                        }
+                    }
+                }
+            }
+        }
+
+        return genericPropertyClass;
+    }
+
+    public static Class<?> getContainerClass(FacesContext facesContext, ValueExpression expression) {
+        ELContext initialELContext = facesContext.getELContext();
+        CapturingELResolver capturingELResolver = new CapturingELResolver(initialELContext.getELResolver());
+        Class<?> type = expression.getType(new ELContextWrapper(initialELContext, capturingELResolver));
+        Class<?> containerType = type.getComponentType();
+
+        if ((containerType == null) && (type != null)) {
+            if (Collection.class.isAssignableFrom(type)) {
+                Object base = capturingELResolver.getBase();
+                Object property = capturingELResolver.getProperty();
+
+                if ((base != null) && (property != null)) {
+                    containerType = getGenericCollectionType(facesContext, base, property.toString());
+                }
+            }
+        }
+
+        return containerType;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/GenericsIntrospectionCache.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/GenericsIntrospectionCache.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/GenericsIntrospectionCache.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,11 +19,15 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
 import java.beans.BeanInfo;
+
 import java.lang.ref.Reference;
 import java.lang.ref.SoftReference;
+
 import java.util.Collections;
 import java.util.Map;
 
@@ -36,67 +40,64 @@
  * @author Nick Belaevski
  * @since 3.3.0
  */
+final class GenericsIntrospectionCache {
+    private static final String CACHE_SIZE_PARAMETER = "org.richfaces.GenericsIntrospectionCacheSize";
+    private static final int DEFAULT_CACHE_SIZE = 256;
+    private static final String INSTANCE_ATTRIBUTE_NAME = GenericsIntrospectionCache.class.getName();
+    private Map<Class<?>, GenericsCacheEntry> genericsCache;
 
-class GenericsIntrospectionCache {
+    private GenericsIntrospectionCache(int cacheSize) {
+        genericsCache = new ReferenceMap<Class<?>,
+                                         GenericsCacheEntry>(Collections.synchronizedMap(new LRUMap<Class<?>,
+                                             Reference<GenericsCacheEntry>>(cacheSize)));
+    }
 
-	private static final String INSTANCE_ATTRIBUTE_NAME = GenericsIntrospectionCache.class.getName();
-	
-	private static final String CACHE_SIZE_PARAMETER = "org.richfaces.GenericsIntrospectionCacheSize";
-	
-	private static final int DEFAULT_CACHE_SIZE = 256;
+    private static int getSize(ExternalContext externalContext) {
+        int cacheSize = DEFAULT_CACHE_SIZE;
+        String cacheSizeParameter = externalContext.getInitParameter(CACHE_SIZE_PARAMETER);
 
-	static final class GenericsCacheEntry {
-		SoftReference<BeanInfo> beanInfoReference;
-		Map<String, Class<?>> genericPropertiesClasses;
-	};
-	
-	private Map<Class<?>, GenericsCacheEntry> genericsCache;
-	
-	private static int getSize(ExternalContext externalContext) {
-		int cacheSize = DEFAULT_CACHE_SIZE;
-		
-		String cacheSizeParameter = externalContext.getInitParameter(CACHE_SIZE_PARAMETER);
-		if (cacheSizeParameter != null && cacheSizeParameter.length() != 0) {
-			try {
-				cacheSize = Integer.valueOf(cacheSizeParameter);
-			} catch (NumberFormatException e) {
-				externalContext.log("Error converting " + CACHE_SIZE_PARAMETER + " init parameter to int: " + e.getMessage(), 
-					e);
-			}
-		}
-		
-		return cacheSize;
-	}
+        if (cacheSizeParameter != null && cacheSizeParameter.length() != 0) {
+            try {
+                cacheSize = Integer.valueOf(cacheSizeParameter);
+            } catch (NumberFormatException e) {
+                externalContext.log("Error converting " + CACHE_SIZE_PARAMETER + " init parameter to int: "
+                                    + e.getMessage(), e);
+            }
+        }
 
-	private GenericsIntrospectionCache(int cacheSize) {
-		genericsCache = new ReferenceMap<Class<?>, GenericsCacheEntry>(
-			Collections.synchronizedMap(new LRUMap<Class<?>, Reference<GenericsCacheEntry>>(cacheSize)));
-	}
-	
-	public GenericsCacheEntry getGenericCacheEntry(Class<?> beanClass) {
-		GenericsCacheEntry cacheEntry = genericsCache.get(beanClass);
-		if (cacheEntry == null) {
-			cacheEntry = new GenericsCacheEntry();
-			genericsCache.put(beanClass, cacheEntry);
-		}
-		
-		return cacheEntry;
-	}
-	
-	static GenericsIntrospectionCache getInstance(FacesContext facesContext) {
-		ExternalContext externalContext = facesContext.getExternalContext();
-		Map<String, Object> applicationMap = externalContext.getApplicationMap();
-		
-		GenericsIntrospectionCache instance;
-		synchronized (applicationMap) {
-			instance = (GenericsIntrospectionCache) applicationMap.get(INSTANCE_ATTRIBUTE_NAME);
-			if (instance == null) {
-				instance = new GenericsIntrospectionCache(getSize(externalContext));
-				applicationMap.put(INSTANCE_ATTRIBUTE_NAME, instance);
-			}
- 		}
-		
-		return instance;
-	}
+        return cacheSize;
+    }
 
+    public GenericsCacheEntry getGenericCacheEntry(Class<?> beanClass) {
+        GenericsCacheEntry cacheEntry = genericsCache.get(beanClass);
+
+        if (cacheEntry == null) {
+            cacheEntry = new GenericsCacheEntry();
+            genericsCache.put(beanClass, cacheEntry);
+        }
+
+        return cacheEntry;
+    }
+
+    static GenericsIntrospectionCache getInstance(FacesContext facesContext) {
+        ExternalContext externalContext = facesContext.getExternalContext();
+        Map<String, Object> applicationMap = externalContext.getApplicationMap();
+        GenericsIntrospectionCache instance;
+
+        synchronized (applicationMap) {
+            instance = (GenericsIntrospectionCache) applicationMap.get(INSTANCE_ATTRIBUTE_NAME);
+
+            if (instance == null) {
+                instance = new GenericsIntrospectionCache(getSize(externalContext));
+                applicationMap.put(INSTANCE_ATTRIBUTE_NAME, instance);
+            }
+        }
+
+        return instance;
+    }
+
+    static final class GenericsCacheEntry {
+        SoftReference<BeanInfo> beanInfoReference;
+        Map<String, Class<?>> genericPropertiesClasses;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/HtmlColor.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/HtmlColor.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/HtmlColor.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,72 +19,82 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
+import org.ajax4jsf.Messages;
+
 import java.awt.Color;
+
 import java.util.HashMap;
 import java.util.Map;
 
-import org.ajax4jsf.Messages;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:59:16 $
  *
  */
-public class HtmlColor {
-	private static Map<String, Color> colorNames;
-	
-	static {
-		// color names.
-		colorNames = new HashMap<String, Color>();
-	    colorNames.put("black", new Color(0x000000));
-		colorNames.put("green", new Color(0x008000));
-		colorNames.put("silver", new Color(0xC0C0C0));
-		colorNames.put("lime", new Color(0x00FF00));
-		colorNames.put("gray", new Color(0x808080));
-		colorNames.put("olive", new Color(0x808000));
-		colorNames.put("white", new Color(0xFFFFFF));
-		colorNames.put("yellow", new Color(0xFFFF00));
-		colorNames.put("maroon", new Color(0x800000));
-		colorNames.put("navy", new Color(0x000080));
-		colorNames.put("red", new Color(0xFF0000));
-		colorNames.put("blue", new Color(0x0000FF));
-		colorNames.put("purple", new Color(0x800080));
-		colorNames.put("teal", new Color(0x008080));
-		colorNames.put("fuchsia", new Color(0xFF00FF));
-		colorNames.put("aqua", new Color(0x00FFFF));
-	}
+public final class HtmlColor {
+    private static Map<String, Color> colorNames;
 
-	/**
-	 * Decode HTML-attribute style of color to {@link Color}
-	 * @param color - color name or #RRGGBB string
-	 * @return - color for this value.
-	 */
-	public static Color decode(String color){
-		if(null == color) {
-			throw new IllegalArgumentException(Messages.getMessage(Messages.NULL_COLOR_PARAMETER_ERROR));
-		}
-		Color c = (Color) colorNames.get(color.trim().toLowerCase());
-		if (null == c) {
-			try {
-				c = Color.decode(color.trim());
-			} catch (NumberFormatException e) {
-				throw new IllegalArgumentException(Messages.getMessage(Messages.DECODE_COLOR_PARAMETER_ERROR, color, e.getMessage()));
-			}
-		}
-		return c;
-	}
-	
-	public static Integer integerValue(String color){
-		return new Integer(decode(color).getRGB());
-	}
-	
-	public static String encodeRGB(Color color){
-		if(null == color) {
-			throw new IllegalArgumentException(Messages.getMessage(Messages.NULL_COLOR_PARAMETER_ERROR_2));
-		}
-		return "#" + Integer.toHexString(color.getRGB()).substring(2).toUpperCase();
-	}
-	
+    static {
+
+        // color names.
+        colorNames = new HashMap<String, Color>();
+        colorNames.put("black", new Color(0x000000));
+        colorNames.put("green", new Color(0x008000));
+        colorNames.put("silver", new Color(0xC0C0C0));
+        colorNames.put("lime", new Color(0x00FF00));
+        colorNames.put("gray", new Color(0x808080));
+        colorNames.put("olive", new Color(0x808000));
+        colorNames.put("white", new Color(0xFFFFFF));
+        colorNames.put("yellow", new Color(0xFFFF00));
+        colorNames.put("maroon", new Color(0x800000));
+        colorNames.put("navy", new Color(0x000080));
+        colorNames.put("red", new Color(0xFF0000));
+        colorNames.put("blue", new Color(0x0000FF));
+        colorNames.put("purple", new Color(0x800080));
+        colorNames.put("teal", new Color(0x008080));
+        colorNames.put("fuchsia", new Color(0xFF00FF));
+        colorNames.put("aqua", new Color(0x00FFFF));
+    }
+
+    private HtmlColor() {}
+
+    /**
+     * Decode HTML-attribute style of color to {@link Color}
+     * @param color - color name or #RRGGBB string
+     * @return - color for this value.
+     */
+    public static Color decode(String color) {
+        if (null == color) {
+            throw new IllegalArgumentException(Messages.getMessage(Messages.NULL_COLOR_PARAMETER_ERROR));
+        }
+
+        Color c = (Color) colorNames.get(color.trim().toLowerCase());
+
+        if (null == c) {
+            try {
+                c = Color.decode(color.trim());
+            } catch (NumberFormatException e) {
+                throw new IllegalArgumentException(Messages.getMessage(Messages.DECODE_COLOR_PARAMETER_ERROR, color,
+                        e.getMessage()));
+            }
+        }
+
+        return c;
+    }
+
+    public static Integer integerValue(String color) {
+        return new Integer(decode(color).getRGB());
+    }
+
+    public static String encodeRGB(Color color) {
+        if (null == color) {
+            throw new IllegalArgumentException(Messages.getMessage(Messages.NULL_COLOR_PARAMETER_ERROR_2));
+        }
+
+        return "#" + Integer.toHexString(color.getRGB()).substring(2).toUpperCase();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/HtmlDimensions.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/HtmlDimensions.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/HtmlDimensions.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,62 +19,74 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
+import org.ajax4jsf.Messages;
+
 import java.text.DecimalFormat;
 import java.text.NumberFormat;
 import java.text.ParseException;
+
 import java.util.regex.Pattern;
 
-import org.ajax4jsf.Messages;
+public final class HtmlDimensions {
+    private static final Pattern PATTERN_NUMERIC = Pattern.compile("^[+-]?\\d+(\\.\\d+)?$");
+    private static final Pattern PATTERN_PX = Pattern.compile("^[+-]?\\d+(\\.\\d+)?px$");
+    private static final Pattern PATTERN_PCT = Pattern.compile("^[+-]?\\d+(\\.\\d+)?%$");
+    private static final NumberFormat NUMERIC_FORMAT = new DecimalFormat();
+    private static final DecimalFormat PX_FORMAT = new DecimalFormat();
+    private static final NumberFormat PCT_FORMAT = NumberFormat.getPercentInstance();
 
-public class HtmlDimensions {
-	
-	private static final Pattern PATTERN_NUMERIC = Pattern.compile("^[+-]?\\d+(\\.\\d+)?$");
-	private static final Pattern PATTERN_PX = Pattern.compile("^[+-]?\\d+(\\.\\d+)?px$");
-	private static final Pattern PATTERN_PCT = Pattern.compile("^[+-]?\\d+(\\.\\d+)?%$");
-	
-	private static final NumberFormat numericFormat = new DecimalFormat();
-	private static final DecimalFormat pxFormat = new DecimalFormat();
-	private static final NumberFormat pctFormat = NumberFormat.getPercentInstance();
-	
-	static{
-		pxFormat.setPositiveSuffix("px");
-		pxFormat.setNegativeSuffix("px");
-	}
-	public static Double decode(String size){
-		// TODO - handle px,ex,pt enc suffixes.
-		double d = 0;
-		try {
-			if(size != null){
-				if(PATTERN_NUMERIC.matcher(size).matches()){
-					synchronized(numericFormat){
-						d = numericFormat.parse(size).doubleValue();
-					}
-				} else if(PATTERN_PX.matcher(size).matches()){
-					synchronized (pxFormat) {
-						d = pxFormat.parse(size).doubleValue();
-					}
-				} else if(PATTERN_PCT.matcher(size).matches()){
-					synchronized (pctFormat) {
-						d = pctFormat.parse(size).doubleValue();
-					}
-				}
-			}
-		} catch (ParseException e) {
-			throw new IllegalArgumentException(Messages.getMessage(Messages.DECODE_PARAMETER_ERROR, new Object[]{"size", size, e.getMessage()}));
-		}
-		return new Double(d);
-	}
-	
-	public static String formatPx(Double value){
-		return (value.intValue() + "px");
-	}
-	public static String formatPct(Double value){
-		String v = "";
-		synchronized (pctFormat) {
-			v = pctFormat.format(value.doubleValue());
-		}
-		return v;
-	}
+    static {
+        PX_FORMAT.setPositiveSuffix("px");
+        PX_FORMAT.setNegativeSuffix("px");
+    }
+
+    private HtmlDimensions() {}
+
+    public static Double decode(String size) {
+
+        // TODO - handle px,ex,pt enc suffixes.
+        double d = 0;
+
+        try {
+            if (size != null) {
+                if (PATTERN_NUMERIC.matcher(size).matches()) {
+                    synchronized (NUMERIC_FORMAT) {
+                        d = NUMERIC_FORMAT.parse(size).doubleValue();
+                    }
+                } else if (PATTERN_PX.matcher(size).matches()) {
+                    synchronized (PX_FORMAT) {
+                        d = PX_FORMAT.parse(size).doubleValue();
+                    }
+                } else if (PATTERN_PCT.matcher(size).matches()) {
+                    synchronized (PCT_FORMAT) {
+                        d = PCT_FORMAT.parse(size).doubleValue();
+                    }
+                }
+            }
+        } catch (ParseException e) {
+            throw new IllegalArgumentException(Messages.getMessage(Messages.DECODE_PARAMETER_ERROR,
+                    new Object[] {"size",
+                                  size, e.getMessage()}));
+        }
+
+        return new Double(d);
+    }
+
+    public static String formatPx(Double value) {
+        return value.intValue() + "px";
+    }
+
+    public static String formatPct(Double value) {
+        String v = "";
+
+        synchronized (PCT_FORMAT) {
+            v = PCT_FORMAT.format(value.doubleValue());
+        }
+
+        return v;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/InputUtils.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/InputUtils.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/InputUtils.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,100 +19,104 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
+import org.ajax4jsf.Messages;
+
 import java.io.Serializable;
 
 import javax.el.ValueExpression;
+
 import javax.faces.component.UIComponent;
 import javax.faces.component.ValueHolder;
 import javax.faces.context.FacesContext;
 import javax.faces.convert.Converter;
 import javax.faces.convert.ConverterException;
 
-import org.ajax4jsf.Messages;
-
 /**
  * @author Maksim Kaszynski
  * @author Manfred Geiler
  *
  */
-public class InputUtils {
+public final class InputUtils {
+    public static final String EMPTY_STRING = new String();
+    public static final Object NOTHING = new Serializable() { };
 
-    public static final String EMPTY_STRING = new String();
-    public static final Object NOTHING = new Serializable() {};
-	
-    public static boolean isTrue(Object obj)
-    {
-        if(!(obj instanceof Boolean))
+    private InputUtils() {}
+
+    public static boolean isTrue(Object obj) {
+        if (!(obj instanceof Boolean)) {
             return false;
+        }
 
         return ((Boolean) obj).booleanValue();
     }
 
-    public static boolean isDisabled(UIComponent component)
-    {
+    public static boolean isDisabled(UIComponent component) {
         return isTrue(component.getAttributes().get("disabled"));
     }
-    public static boolean isReadOnly(UIComponent component)
-    {
+
+    public static boolean isReadOnly(UIComponent component) {
         return isTrue(component.getAttributes().get("readonly"));
     }
-    
-    public static Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
-	
-	String newValue = (String) submittedValue;
-	
-	ValueExpression valueExpression = component.getValueExpression("value");
-	Converter converter = null;
 
-	if (component instanceof ValueHolder) {
-	    converter = ((ValueHolder)component).getConverter();
-	}
-	
-	if (converter == null && valueExpression != null) {
-	    Class converterType = valueExpression.getType(context.getELContext());
-	    if (converterType == null || converterType == Object.class || converterType == String.class) {
-		return newValue;
-	    } else {
-		converter = context.getApplication().createConverter(converterType);
-		if (converter == null) {
-		    throw new ConverterException(Messages.getMessage(Messages.NO_CONVERTER_FOUND_ERROR, converterType.getName()));
-		}
-	    }
-	} else if (converter == null) {
-	    return newValue;
-	}
-		
-	return converter.getAsObject(context, component, newValue);
+    public static Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue)
+            throws ConverterException {
+        String newValue = (String) submittedValue;
+        ValueExpression valueExpression = component.getValueExpression("value");
+        Converter converter = null;
+
+        if (component instanceof ValueHolder) {
+            converter = ((ValueHolder) component).getConverter();
+        }
+
+        if ((converter == null) && (valueExpression != null)) {
+            Class converterType = valueExpression.getType(context.getELContext());
+
+            if ((converterType == null) || (converterType == Object.class) || (converterType == String.class)) {
+                return newValue;
+            } else {
+                converter = context.getApplication().createConverter(converterType);
+
+                if (converter == null) {
+                    throw new ConverterException(Messages.getMessage(Messages.NO_CONVERTER_FOUND_ERROR,
+                            converterType.getName()));
+                }
+            }
+        } else if (converter == null) {
+            return newValue;
+        }
+
+        return converter.getAsObject(context, component, newValue);
     }
-    
+
     public static String getConvertedStringValue(FacesContext context, UIComponent component, Object value) {
-	
-	Converter converter = null;
-	
-	if (component instanceof ValueHolder) {
-	    converter = ((ValueHolder)component).getConverter();
-	}
-		
-	if (converter == null) {
-		if (value == null) {
-			return "";
-		} else if (value instanceof String) {
-			return (String) value;
-		}
-		
-		Class converterType = value.getClass();
-		if (converterType != null ) {
-			converter = context.getApplication().createConverter(converterType);
-		}
-		
-		if (converter == null) {
-			return value.toString();
-		}
-	}
-	return converter.getAsString(context, component, value);
-    
+        Converter converter = null;
+
+        if (component instanceof ValueHolder) {
+            converter = ((ValueHolder) component).getConverter();
+        }
+
+        if (converter == null) {
+            if (value == null) {
+                return "";
+            } else if (value instanceof String) {
+                return (String) value;
+            }
+
+            Class converterType = value.getClass();
+
+            if (converterType != null) {
+                converter = context.getApplication().createConverter(converterType);
+            }
+
+            if (converter == null) {
+                return value.toString();
+            }
+        }
+
+        return converter.getAsString(context, component, value);
     }
-    
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/LRUMap.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/LRUMap.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/LRUMap.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,9 +18,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.util;
 
 import java.io.Serializable;
+
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.Map.Entry;
@@ -30,47 +34,47 @@
  * @author asmirnov
  *
  */
-public class LRUMap<K,V> extends LinkedHashMap<K,V> implements Serializable {
+public class LRUMap<K, V> extends LinkedHashMap<K, V> implements Serializable {
 
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -7232885382582796665L;
-	private int capacity;
-	
-	
-	/**
-	 * Default capacity constructor
-	 */
-	public LRUMap() {
-		this(100);
-	}
-	
-	/**
-	 * @param capacity - maximal cache capacity.
-	 */
-	public LRUMap(int capacity) {
-		super(capacity, 1.0f,true);
-		this.capacity = capacity;
-	}
+    /**
+     *
+     */
+    private static final long serialVersionUID = -7232885382582796665L;
+    private int capacity;
 
-	
-	protected boolean removeEldestEntry(Entry<K,V> entry) {
-		// Remove last entry if size exceeded.
-		return size()>capacity;
-	}
+    /**
+     * Default capacity constructor
+     */
+    public LRUMap() {
+        this(100);
+    }
 
-	/**
-	 * Get most recent used element 
-	 * @return the most Recent value
-	 */
-	public V getMostRecent() {
-		Iterator<V> iterator = values().iterator();
-		V mostRecent=null;
-		while (iterator.hasNext()) {
-			 mostRecent = iterator.next();
-			
-		}
-		return mostRecent;
-	}
+    /**
+     * @param capacity - maximal cache capacity.
+     */
+    public LRUMap(int capacity) {
+        super(capacity, 1.0f, true);
+        this.capacity = capacity;
+    }
+
+    protected boolean removeEldestEntry(Entry<K, V> entry) {
+
+        // Remove last entry if size exceeded.
+        return size() > capacity;
+    }
+
+    /**
+     * Get most recent used element
+     * @return the most Recent value
+     */
+    public V getMostRecent() {
+        Iterator<V> iterator = values().iterator();
+        V mostRecent = null;
+
+        while (iterator.hasNext()) {
+            mostRecent = iterator.next();
+        }
+
+        return mostRecent;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/NumericDataInputStream.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/NumericDataInputStream.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/NumericDataInputStream.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,90 +19,92 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
 import java.awt.Color;
+
 import java.io.ByteArrayInputStream;
+
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
 
 /**
  * Original idea by Igor Shabalov
- * 
+ *
  * @author Nick Belaevski
  * @since 4.0
  */
 public class NumericDataInputStream {
+    static final int BYTES_IN_INT = Integer.SIZE >> 3;
+    static final int BYTES_IN_SHORT = Short.SIZE >> 3;
+    static final int BYTES_IN_COLOR = BYTES_IN_INT - 1;
 
-	static final int BYTES_IN_INT = Integer.SIZE >> 3;
+    // the size of maximum object in bytes that this stream can operate (int)
+    static final int MAX_BYTES = BYTES_IN_INT;
+    static final ByteOrder BUFFER_BYTES_ORDER = ByteOrder.LITTLE_ENDIAN;
+    private byte[] bytes = new byte[MAX_BYTES];
+    private ByteBuffer buffer = ByteBuffer.wrap(bytes).order(BUFFER_BYTES_ORDER);
+    private ByteArrayInputStream byteArrayStream;
 
-	static final int BYTES_IN_SHORT = Short.SIZE >> 3;
+    public NumericDataInputStream(byte[] buf) {
+        super();
+        byteArrayStream = new ByteArrayInputStream(buf);
+    }
 
-	static final int BYTES_IN_COLOR = BYTES_IN_INT - 1;
+    public NumericDataInputStream(byte[] buf, int offset, int length) {
+        super();
+        byteArrayStream = new ByteArrayInputStream(buf, offset, length);
+    }
 
-	//the size of maximum object in bytes that this stream can operate (int)
-	static final int MAX_BYTES = BYTES_IN_INT;
-	
-	static final ByteOrder BUFFER_BYTES_ORDER = ByteOrder.LITTLE_ENDIAN;
-	
-	private ByteArrayInputStream byteArrayStream;
-	
-	private byte[] bytes = new byte[MAX_BYTES];
-	
-	private ByteBuffer buffer = ByteBuffer.wrap(bytes).order(BUFFER_BYTES_ORDER);
-	
-	public NumericDataInputStream(byte[] buf, int offset, int length) {
-		super();
-		
-		byteArrayStream = new ByteArrayInputStream(buf, offset, length);
-	}
+    public byte readByte() {
+        int read = byteArrayStream.read();
 
-	public NumericDataInputStream(byte[] buf) {
-		super();
+        if (read >= 0) {
+            return (byte) read;
+        } else {
+            throw new IllegalStateException("Data is invalid or corrupted");
+        }
+    }
 
-		byteArrayStream = new ByteArrayInputStream(buf);
-	}
-	
-	public byte readByte() {
-		int read = byteArrayStream.read();
-		if (read >= 0) {
-			return (byte) read;
-		} else {
-			throw new IllegalStateException("Data is invalid or corrupted");
-		}
-	}
-	
-	public short readShort() {
-		int read = byteArrayStream.read(bytes, 0, BYTES_IN_SHORT);
-		if (read == BYTES_IN_SHORT) {
-			buffer.rewind();
-			return buffer.asShortBuffer().get();
-		} else {
-			throw new IllegalStateException("Data is invalid or corrupted");
-		}
-	}
-	
-	public int readInt() {
-		int read = byteArrayStream.read(bytes, 0, BYTES_IN_INT);
-		if (read == BYTES_IN_INT) {
-			buffer.rewind();
-			return buffer.asIntBuffer().get();
-		} else {
-			throw new IllegalStateException("Data is invalid or corrupted");
-		}
-	}
-	
-	public int readIntColor() {
-		int read = byteArrayStream.read(bytes, 0, BYTES_IN_COLOR);
-		if (read == BYTES_IN_COLOR) {
-			buffer.rewind();
-			return buffer.asIntBuffer().get() & 0x00FFFFFF;
-		} else {
-			throw new IllegalStateException("Data is invalid or corrupted");
-		}
-	}
-	
-	public Color readColor() {
-		return new Color(readIntColor());
-	}
+    public short readShort() {
+        int read = byteArrayStream.read(bytes, 0, BYTES_IN_SHORT);
+
+        if (read == BYTES_IN_SHORT) {
+            buffer.rewind();
+
+            return buffer.asShortBuffer().get();
+        } else {
+            throw new IllegalStateException("Data is invalid or corrupted");
+        }
+    }
+
+    public int readInt() {
+        int read = byteArrayStream.read(bytes, 0, BYTES_IN_INT);
+
+        if (read == BYTES_IN_INT) {
+            buffer.rewind();
+
+            return buffer.asIntBuffer().get();
+        } else {
+            throw new IllegalStateException("Data is invalid or corrupted");
+        }
+    }
+
+    public int readIntColor() {
+        int read = byteArrayStream.read(bytes, 0, BYTES_IN_COLOR);
+
+        if (read == BYTES_IN_COLOR) {
+            buffer.rewind();
+
+            return buffer.asIntBuffer().get() & 0x00FFFFFF;
+        } else {
+            throw new IllegalStateException("Data is invalid or corrupted");
+        }
+    }
+
+    public Color readColor() {
+        return new Color(readIntColor());
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/NumericDataOutputStream.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/NumericDataOutputStream.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/NumericDataOutputStream.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,62 +19,68 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
+import static org.ajax4jsf.util.NumericDataInputStream.*;
+
 import java.awt.Color;
+
 import java.io.ByteArrayOutputStream;
+
 import java.nio.ByteBuffer;
-import static org.ajax4jsf.util.NumericDataInputStream.*;
 
 /**
  * Original idea by Igor Shabalov
- * 
+ *
  * @author Nick Belaevski
  * @since 4.0
  */
 public class NumericDataOutputStream {
+    private ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+    private byte[] bytes = new byte[MAX_BYTES];
+    private ByteBuffer buffer = ByteBuffer.wrap(bytes).order(BUFFER_BYTES_ORDER);
 
-	private ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+    public NumericDataOutputStream writeByte(byte value) {
+        byteStream.write(value);
 
-	private byte[] bytes = new byte[MAX_BYTES];
+        return this;
+    }
 
-	private ByteBuffer buffer = ByteBuffer.wrap(bytes)
-			.order(BUFFER_BYTES_ORDER);
+    public NumericDataOutputStream writeShort(short value) {
+        buffer.rewind();
+        buffer.asShortBuffer().put(value);
+        byteStream.write(bytes, 0, BYTES_IN_SHORT);
 
-	public NumericDataOutputStream writeByte(byte value) {
-		byteStream.write(value);
-		return this;
-	}
+        return this;
+    }
 
-	public NumericDataOutputStream writeShort(short value) {
-		buffer.rewind();
-		buffer.asShortBuffer().put(value);
-		byteStream.write(bytes, 0, BYTES_IN_SHORT);
-		return this;
-	}
+    private void writeInteger(int value, int numBytes) {
+        buffer.rewind();
+        buffer.asIntBuffer().put(value);
+        byteStream.write(bytes, 0, numBytes);
+    }
 
-	private void writeInteger(int value, int numBytes) {
-		buffer.rewind();
-		buffer.asIntBuffer().put(value);
-		byteStream.write(bytes, 0, numBytes);
-	}
+    public NumericDataOutputStream writeInt(int value) {
+        writeInteger(value, BYTES_IN_INT);
 
-	public NumericDataOutputStream writeInt(int value) {
-		writeInteger(value, BYTES_IN_INT);
-		return this;
-	}
+        return this;
+    }
 
-	public NumericDataOutputStream writeIntColor(int value) {
-		writeInteger(value, BYTES_IN_COLOR);
-		return this;
-	}
+    public NumericDataOutputStream writeIntColor(int value) {
+        writeInteger(value, BYTES_IN_COLOR);
 
-	public NumericDataOutputStream writeColor(Color value) {
-		writeIntColor(value.getRGB());
-		return this;
-	}
+        return this;
+    }
 
-	public byte[] getBytes() {
-		return byteStream.toByteArray();
-	}
+    public NumericDataOutputStream writeColor(Color value) {
+        writeIntColor(value.getRGB());
+
+        return this;
+    }
+
+    public byte[] getBytes() {
+        return byteStream.toByteArray();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/SelectUtils.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/SelectUtils.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/SelectUtils.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,20 +19,30 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
+import org.ajax4jsf.Messages;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.lang.reflect.Array;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
-import java.util.Map.Entry;
 
 import javax.el.ELContext;
 import javax.el.ValueExpression;
+
 import javax.faces.FacesException;
 import javax.faces.component.UIComponent;
 import javax.faces.component.UIInput;
@@ -45,235 +55,261 @@
 import javax.faces.convert.ConverterException;
 import javax.faces.model.SelectItem;
 
-import org.ajax4jsf.Messages;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * @author Maksim Kaszynski
  *
  */
-public class SelectUtils {
-	
-	private static final Logger log = RichfacesLogger.APPLICATION.getLogger();
-	
-	/**
-	 * Gathers all select items from specified component's children
-	 * @param context
-	 * @param component
-	 * @return list of {@link SelectItems} taken from f:selectItem and f:selectItems
-	 */
-	public static List<SelectItem> getSelectItems(FacesContext context, UIComponent component) {
+public final class SelectUtils {
+    private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
+
+    private SelectUtils() { }
+
+    /**
+     * Gathers all select items from specified component's children
+     * @param context
+     * @param component
+     * @return list of {@link SelectItems} taken from f:selectItem and f:selectItems
+     */
+    public static List<SelectItem> getSelectItems(FacesContext context, UIComponent component) {
         ArrayList<SelectItem> list = new ArrayList<SelectItem>();
-		Iterator<UIComponent> kids = component.getChildren().iterator();
-		while (kids.hasNext()) {
-			UIComponent kid = kids.next();
-			if (kid instanceof UISelectItem) {
-				Object value = ((UISelectItem) kid).getValue();
-				if (value == null) {
-					UISelectItem item = (UISelectItem) kid;
-					list.add(new SelectItem(item.getItemValue(), item.getItemLabel(), item.getItemDescription(), item.isItemDisabled()));
-				} else if (value instanceof SelectItem) {
-					list.add((SelectItem)value);
-				} else {
-					String valueClass = (value != null ? "'" + value.getClass().getName() + "'" : "");
-					throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_ATTRIBUTE_VALUE, valueClass, "<selectItem>"));
-				}
-			} else if (kid instanceof UISelectItems && null != context) {
-				Object value = ((UISelectItems) kid).getValue();
-				if (value instanceof SelectItem) {
-					list.add((SelectItem)value);
-				} else if (value instanceof SelectItem[]) {
-					SelectItem items[] = (SelectItem[]) value;
-					list.addAll(Arrays.asList(items));
-				} else if (value instanceof Collection) {
-					list.addAll(((Collection<SelectItem>)value));
-				} else if (value instanceof Map) {
-					Map<Object,Object> map = (Map<Object, Object>) value;
-					Set<Entry<Object,Object>> entrySet = map.entrySet();
-					for (Entry<Object, Object> entry : entrySet) {
-						list.add(new SelectItem(entry.getValue(), entry.getKey().toString(), null));
-					}
-				} else {
-					String valueClass = (value != null ? "'" + value.getClass().getName() + "'" : "");
-					throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_ATTRIBUTE_VALUE, valueClass, "<selectItems>"));
-				}
-			}
-		}
+        Iterator<UIComponent> kids = component.getChildren().iterator();
+
+        while (kids.hasNext()) {
+            UIComponent kid = kids.next();
+
+            if (kid instanceof UISelectItem) {
+                Object value = ((UISelectItem) kid).getValue();
+
+                if (value == null) {
+                    UISelectItem item = (UISelectItem) kid;
+
+                    list.add(new SelectItem(item.getItemValue(), item.getItemLabel(), item.getItemDescription(),
+                                            item.isItemDisabled()));
+                } else if (value instanceof SelectItem) {
+                    list.add((SelectItem) value);
+                } else {
+                    String valueClass = value != null ? "'" + value.getClass().getName() + "'" : "";
+
+                    throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_ATTRIBUTE_VALUE,
+                            valueClass, "<selectItem>"));
+                }
+            } else if ((kid instanceof UISelectItems) && (null != context)) {
+                Object value = ((UISelectItems) kid).getValue();
+
+                if (value instanceof SelectItem) {
+                    list.add((SelectItem) value);
+                } else if (value instanceof SelectItem[]) {
+                    SelectItem[] items = (SelectItem[]) value;
+
+                    list.addAll(Arrays.asList(items));
+                } else if (value instanceof Collection) {
+                    list.addAll((Collection<SelectItem>) value);
+                } else if (value instanceof Map) {
+                    Map<Object, Object> map = (Map<Object, Object>) value;
+                    Set<Entry<Object, Object>> entrySet = map.entrySet();
+
+                    for (Entry<Object, Object> entry : entrySet) {
+                        list.add(new SelectItem(entry.getValue(), entry.getKey().toString(), null));
+                    }
+                } else {
+                    String valueClass = (value != null) ? "'" + value.getClass().getName() + "'" : "";
+
+                    throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_ATTRIBUTE_VALUE,
+                            valueClass, "<selectItems>"));
+                }
+            }
+        }
+
         return list;
+    }
 
-	}
-	
-	/**
-	 * Converts UISelectMany submitted value to converted value
-	 * 
-	 * @author Manfred Geiler
-	 * @param facesContext
-	 * @param component
-	 * @param submittedValue
-	 * @return
-	 * @throws ConverterException
-	 */
-	public static Object getConvertedUISelectManyValue(
-			FacesContext facesContext, UISelectMany component,
-			String[] submittedValue) throws ConverterException {
-		// Attention!
-		// This code is duplicated in jsfapi component package.
-		// If you change something here please do the same in the other class!
+    /**
+     * Converts UISelectMany submitted value to converted value
+     *
+     * @author Manfred Geiler
+     * @param facesContext
+     * @param component
+     * @param submittedValue
+     * @return
+     * @throws ConverterException
+     */
+    public static Object getConvertedUISelectManyValue(FacesContext facesContext, UISelectMany component,
+            String[] submittedValue) throws ConverterException {
 
-		if (submittedValue == null)
-			throw new NullPointerException("submittedValue");
-		
-		ELContext elContext = facesContext.getELContext();
-		ValueExpression vb = component.getValueExpression("value");
-		Class<?> valueType = null;
-		Class<?> arrayComponentType = null;
-		if (vb != null) {
-			valueType = vb.getType(elContext);
-			if (valueType != null && valueType.isArray()) {
-				arrayComponentType = valueType.getComponentType();
-			}
-		}
+        // Attention!
+        // This code is duplicated in jsfapi component package.
+        // If you change something here please do the same in the other class!
+        if (submittedValue == null) {
+            throw new NullPointerException("submittedValue");
+        }
 
-		Converter converter = component.getConverter();
-		if (converter == null) {
-			if (valueType == null) {
-				// No converter, and no idea of expected type
-				// --> return the submitted String array
-				return submittedValue;
-			}
+        ELContext elContext = facesContext.getELContext();
+        ValueExpression vb = component.getValueExpression("value");
+        Class<?> valueType = null;
+        Class<?> arrayComponentType = null;
 
-			if (List.class.isAssignableFrom(valueType)) {
-				// expected type is a List
-				// --> according to javadoc of UISelectMany we assume that the
-				// element type
-				// is java.lang.String, and copy the String array to a new List
-				List<String> lst = Arrays.asList(submittedValue);
-				return lst;
-			}
+        if (vb != null) {
+            valueType = vb.getType(elContext);
 
-			if (arrayComponentType == null) {
-				throw new IllegalArgumentException(Messages.getMessage(Messages.VALUE_BINDING_TYPE_ERROR));
-			}
+            if ((valueType != null) && valueType.isArray()) {
+                arrayComponentType = valueType.getComponentType();
+            }
+        }
 
-			if (String.class.equals(arrayComponentType))
-				return submittedValue; // No conversion needed for String type
-			if (Object.class.equals(arrayComponentType))
-				return submittedValue; // No conversion for Object class
+        Converter converter = component.getConverter();
 
-			try {
-				converter = facesContext.getApplication().createConverter(
-						arrayComponentType);
-			} catch (FacesException e) {
-				log.error(Messages.getMessage(Messages.NO_CONVERTER_FOUND_ERROR, arrayComponentType.getName()), e);
-				return submittedValue;
-			}
-		}
+        if (converter == null) {
+            if (valueType == null) {
 
-		// Now, we have a converter...
-		if (valueType == null) {
-			// ...but have no idea of expected type
-			// --> so let's convert it to an Object array
-			int len = submittedValue.length;
-			Object[] convertedValues = (Object[]) Array.newInstance(
-					arrayComponentType == null ? Object.class
-							: arrayComponentType, len);
-			for (int i = 0; i < len; i++) {
-				convertedValues[i] = converter.getAsObject(facesContext,
-						component, submittedValue[i]);
-			}
-			return convertedValues;
-		}
+                // No converter, and no idea of expected type
+                // --> return the submitted String array
+                return submittedValue;
+            }
 
-		if (List.class.isAssignableFrom(valueType)) {
-			// Curious case: According to specs we should assume, that the
-			// element type
-			// of this List is java.lang.String. But there is a Converter set
-			// for this
-			// component. Because the user must know what he is doing, we will
-			// convert the values.
-			int len = submittedValue.length;
-			List<Object> lst = new ArrayList<Object>(len);
-			for (int i = 0; i < len; i++) {
-				lst.add(converter.getAsObject(facesContext, component,
-						submittedValue[i]));
-			}
-			return lst;
-		}
+            if (List.class.isAssignableFrom(valueType)) {
 
-		if (arrayComponentType == null) {
-			throw new IllegalArgumentException(Messages.getMessage(Messages.VALUE_BINDING_TYPE_ERROR));
-		}
+                // expected type is a List
+                // --> according to javadoc of UISelectMany we assume that the
+                // element type
+                // is java.lang.String, and copy the String array to a new List
+                List<String> lst = Arrays.asList(submittedValue);
 
-		if (arrayComponentType.isPrimitive()) {
-			// primitive array
-			int len = submittedValue.length;
-			Object convertedValues = Array.newInstance(arrayComponentType, len);
-			for (int i = 0; i < len; i++) {
-				Array.set(convertedValues, i, converter.getAsObject(
-						facesContext, component, submittedValue[i]));
-			}
-			return convertedValues;
-		} else {
-			// Object array
-			int len = submittedValue.length;
-			ArrayList<Object> convertedValues = new ArrayList<Object>(len);
-			for (int i = 0; i < len; i++) {
-				convertedValues.add(i, converter.getAsObject(facesContext,
-						component, submittedValue[i]));
-			}
-			return convertedValues.toArray((Object[]) Array.newInstance(
-					arrayComponentType, len));
-		}
-	}
+                return lst;
+            }
 
-	public static Object getConvertedUIInputValue(
-			FacesContext facesContext, UIInput component,
-			String submittedValue) throws ConverterException{
+            if (arrayComponentType == null) {
+                throw new IllegalArgumentException(Messages.getMessage(Messages.VALUE_BINDING_TYPE_ERROR));
+            }
 
-		Object convertedValue = null;
-		
-		/*
-		if (submittedValue == null)
-			throw new NullPointerException("submittedValue");
-		*/
-		if(InputUtils.EMPTY_STRING.equals(submittedValue)){
-			return null;
-		}
-		Converter converter = getConverterForProperty(facesContext, component, "value");
-		if(converter != null){
-			convertedValue = converter.getAsObject(facesContext, component, submittedValue);
-		} else {
-			convertedValue = submittedValue;
-		}
-		
-		return convertedValue;
+            if (String.class.equals(arrayComponentType)) {
+                return submittedValue; // No conversion needed for String type
+            }
 
-	}
-	/**
-	 * 
-	 * @param facesContext
-	 * @param component
-	 * @param property
-	 * @return converter for specified component attribute
-	 */
-	public static Converter getConverterForProperty(FacesContext facesContext, UIOutput component, String property){
-		Converter converter = component.getConverter();
-		if(converter == null){
-			ValueExpression ve = component.getValueExpression(property);
-			if(ve != null){
-				Class<?> valueType = ve.getType(facesContext.getELContext());
-				if(valueType == null || String.class.equals(valueType) || Object.class.equals(valueType)){
-					//No converter needed
-				} else {
-					converter = facesContext.getApplication().createConverter(valueType);
-					if(converter == null){
-						throw new ConverterException(Messages.getMessage(Messages.NO_CONVERTER_FOUND_ERROR, valueType.getName()));
-					}
-				}
-			}
-		} 
-		return converter;
-	}
-	
+            if (Object.class.equals(arrayComponentType)) {
+                return submittedValue; // No conversion for Object class
+            }
+
+            try {
+                converter = facesContext.getApplication().createConverter(arrayComponentType);
+            } catch (FacesException e) {
+                LOG.error(Messages.getMessage(Messages.NO_CONVERTER_FOUND_ERROR, arrayComponentType.getName()), e);
+
+                return submittedValue;
+            }
+        }
+
+        // Now, we have a converter...
+        if (valueType == null) {
+
+            // ...but have no idea of expected type
+            // --> so let's convert it to an Object array
+            int len = submittedValue.length;
+            Object[] convertedValues = (Object[]) Array.newInstance((arrayComponentType == null)
+                                           ? Object.class : arrayComponentType, len);
+
+            for (int i = 0; i < len; i++) {
+                convertedValues[i] = converter.getAsObject(facesContext, component, submittedValue[i]);
+            }
+
+            return convertedValues;
+        }
+
+        if (List.class.isAssignableFrom(valueType)) {
+
+            // Curious case: According to specs we should assume, that the
+            // element type
+            // of this List is java.lang.String. But there is a Converter set
+            // for this
+            // component. Because the user must know what he is doing, we will
+            // convert the values.
+            int len = submittedValue.length;
+            List<Object> lst = new ArrayList<Object>(len);
+
+            for (int i = 0; i < len; i++) {
+                lst.add(converter.getAsObject(facesContext, component, submittedValue[i]));
+            }
+
+            return lst;
+        }
+
+        if (arrayComponentType == null) {
+            throw new IllegalArgumentException(Messages.getMessage(Messages.VALUE_BINDING_TYPE_ERROR));
+        }
+
+        if (arrayComponentType.isPrimitive()) {
+
+            // primitive array
+            int len = submittedValue.length;
+            Object convertedValues = Array.newInstance(arrayComponentType, len);
+
+            for (int i = 0; i < len; i++) {
+                Array.set(convertedValues, i, converter.getAsObject(facesContext, component, submittedValue[i]));
+            }
+
+            return convertedValues;
+        } else {
+
+            // Object array
+            int len = submittedValue.length;
+            ArrayList<Object> convertedValues = new ArrayList<Object>(len);
+
+            for (int i = 0; i < len; i++) {
+                convertedValues.add(i, converter.getAsObject(facesContext, component, submittedValue[i]));
+            }
+
+            return convertedValues.toArray((Object[]) Array.newInstance(arrayComponentType, len));
+        }
+    }
+
+    public static Object getConvertedUIInputValue(FacesContext facesContext, UIInput component, String submittedValue)
+        throws ConverterException {
+        
+        /*
+         * if (submittedValue == null)
+         *   throw new NullPointerException("submittedValue");
+         */
+        if (InputUtils.EMPTY_STRING.equals(submittedValue)) {
+            return null;
+        }
+
+        Converter converter = getConverterForProperty(facesContext, component, "value");
+        if (converter != null) {
+            return converter.getAsObject(facesContext, component, submittedValue);
+        }
+
+        return submittedValue;
+    }
+
+    /**
+     *
+     * @param facesContext
+     * @param component
+     * @param property
+     * @return converter for specified component attribute
+     */
+    public static Converter getConverterForProperty(FacesContext facesContext, UIOutput component, String property) {
+        Converter converter = component.getConverter();
+
+        if (converter == null) {
+            ValueExpression ve = component.getValueExpression(property);
+
+            if (ve != null) {
+                Class<?> valueType = ve.getType(facesContext.getELContext());
+
+                if ((valueType == null) || String.class.equals(valueType) || Object.class.equals(valueType)) {
+
+                    // No converter needed
+                } else {
+                    converter = facesContext.getApplication().createConverter(valueType);
+
+                    if (converter == null) {
+                        throw new ConverterException(Messages.getMessage(Messages.NO_CONVERTER_FOUND_ERROR,
+                                valueType.getName()));
+                    }
+                }
+            }
+        }
+
+        return converter;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/ServicesUtils.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/ServicesUtils.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/ServicesUtils.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,136 +19,150 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
+import org.ajax4jsf.resource.util.URLToStreamHelper;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.BufferedReader;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 
 import javax.faces.FacesException;
 
-import org.ajax4jsf.resource.util.URLToStreamHelper;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * @author shura
- * 
+ *
  */
-public class ServicesUtils {
+public final class ServicesUtils {
+    private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
+    private static Map<String, Map<ClassLoader, Class<?>>> services = Collections.synchronizedMap(new HashMap<String,
+                                                                          Map<ClassLoader, Class<?>>>());
+    private static Map<String, Map<ClassLoader, Object>> instances = Collections.synchronizedMap(new HashMap<String,
+                                                                         Map<ClassLoader, Object>>());
 
-	private static final Logger log = RichfacesLogger.APPLICATION.getLogger();
+    private ServicesUtils() {
 
-	private static Map<String, Map<ClassLoader, Class<?>>> _services = 
-			Collections.synchronizedMap(new HashMap<String, Map<ClassLoader, Class<?>>>());
+        // This is a static utility class.
+    }
 
-	private static Map<String, Map<ClassLoader, Object>> _instances = 
-		Collections.synchronizedMap(new HashMap<String, Map<ClassLoader, Object>>());
-	/**
-	 * 
-	 */
-	private ServicesUtils() {
-		// This is a static utility class.
-	}
+    /**
+     * @param name
+     * @return
+     * @throws ClassNotFoundException
+     */
+    public static Class<?> getService(String name) throws ClassNotFoundException {
+        Map<ClassLoader, Class<?>> contextClasses = services.get(name);
 
-	/**
-	 * @param name
-	 * @return
-	 * @throws ClassNotFoundException
-	 */
-	public static Class<?> getService(String name) throws ClassNotFoundException {
-		Map<ClassLoader, Class<?>> contextClasses =  _services.get(name);
-		if (null == contextClasses) {
-			contextClasses = Collections.synchronizedMap(new HashMap<ClassLoader, Class<?>>());
-			_services.put(name, contextClasses);
-		}
-		ClassLoader loader = Thread.currentThread().getContextClassLoader();
-		Class<?> serviceClass = contextClasses.get(loader);
-		if (null == serviceClass) {
-			serviceClass = loadServiceClass(loader, name);
-			contextClasses.put(loader, serviceClass);
-		}
-		return serviceClass;
-	}
+        if (null == contextClasses) {
+            contextClasses = Collections.synchronizedMap(new HashMap<ClassLoader, Class<?>>());
+            services.put(name, contextClasses);
+        }
 
-	/**
-	 * Get per-context instance for service.
-	 * @param name - name ( default classname ) for service.
-	 * @return current instance for this service.
-	 * @throws ClassNotFoundException
-	 */
-	public static Object getServiceInstance(String name)  {
-		Map<ClassLoader, Object> contextInstances = (Map<ClassLoader, Object>) _instances.get(name);
-		if (null == contextInstances) {
-			contextInstances = Collections.synchronizedMap(new HashMap<ClassLoader, Object>());
-			_instances.put(name, contextInstances);
-		}
-		ClassLoader loader = Thread.currentThread().getContextClassLoader();
-		Object serviceInstance = contextInstances.get(loader);
-		if (null == serviceInstance) {
-			try{
-			Class<?> serviceClass = loadServiceClass(loader, name);
-			serviceInstance = serviceClass.newInstance();
-			} catch (Exception e) {
-				throw new FacesException("Error create instance for service "+name,e);
-			}
-			contextInstances.put(loader, serviceInstance);
-		}
-		return serviceInstance;
-	}
-	
-	
-	/**
-	 * @param loader
-	 * @param name
-	 * @return
-	 * @throws ClassNotFoundException
-	 */
-	public static Class<?> loadServiceClass(ClassLoader loader, String name) throws ClassNotFoundException {
-		Class<?> serviceClass;
-		try {
-			String resource = "META-INF/services/" + name;
-			InputStream in = URLToStreamHelper.urlToStreamSafe(loader.getResource(resource));
-			BufferedReader reader = new BufferedReader(
-					new InputStreamReader(in));
-			String serviceClassName = reader.readLine();
-			reader.close();
-			serviceClass = loadClass(loader, serviceClassName);
-			if (log.isDebugEnabled()) {
-				log.debug("Class for service "+name+ " set to "+ serviceClassName);
-			}
-		} catch (Exception e) {
-			serviceClass = loadClass(loader, name);
-			if (log.isDebugEnabled()) {
-				log
-						.debug("Service class set to default implementation "+name);
-			}
-		}
-		return serviceClass;
-	}
+        ClassLoader loader = Thread.currentThread().getContextClassLoader();
+        Class<?> serviceClass = contextClasses.get(loader);
 
-	/**
-	 * @param loader
-	 * @param name
-	 * @return
-	 * @throws ClassNotFoundException
-	 */
-	public static Class<?> loadClass(ClassLoader loader, String name)
-			throws ClassNotFoundException {
-		Class<?> clazz;
-		try {
-			clazz = loader.loadClass(name);
-		} catch (ClassNotFoundException e) {
-			if (log.isWarnEnabled()) {
-				log.warn("Class " + name + "not found by Context Classloader");
-			}
-			// Try internal library classloader.
-			clazz = ServicesUtils.class.getClassLoader().loadClass(name);
-		}
-		return clazz;
-	}
+        if (null == serviceClass) {
+            serviceClass = loadServiceClass(loader, name);
+            contextClasses.put(loader, serviceClass);
+        }
 
+        return serviceClass;
+    }
+
+    /**
+     * Get per-context instance for service.
+     * @param name - name ( default classname ) for service.
+     * @return current instance for this service.
+     * @throws ClassNotFoundException
+     */
+    public static Object getServiceInstance(String name) {
+        Map<ClassLoader, Object> contextInstances = (Map<ClassLoader, Object>) instances.get(name);
+
+        if (null == contextInstances) {
+            contextInstances = Collections.synchronizedMap(new HashMap<ClassLoader, Object>());
+            instances.put(name, contextInstances);
+        }
+
+        ClassLoader loader = Thread.currentThread().getContextClassLoader();
+        Object serviceInstance = contextInstances.get(loader);
+
+        if (null == serviceInstance) {
+            try {
+                Class<?> serviceClass = loadServiceClass(loader, name);
+
+                serviceInstance = serviceClass.newInstance();
+            } catch (Exception e) {
+                throw new FacesException("Error create instance for service " + name, e);
+            }
+
+            contextInstances.put(loader, serviceInstance);
+        }
+
+        return serviceInstance;
+    }
+
+    /**
+     * @param loader
+     * @param name
+     * @return
+     * @throws ClassNotFoundException
+     */
+    public static Class<?> loadServiceClass(ClassLoader loader, String name) throws ClassNotFoundException {
+        Class<?> serviceClass;
+
+        try {
+            String resource = "META-INF/services/" + name;
+            InputStream in = URLToStreamHelper.urlToStreamSafe(loader.getResource(resource));
+            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+            String serviceClassName = reader.readLine();
+
+            reader.close();
+            serviceClass = loadClass(loader, serviceClassName);
+
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Class for service " + name + " set to " + serviceClassName);
+            }
+        } catch (Exception e) {
+            serviceClass = loadClass(loader, name);
+
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Service class set to default implementation " + name);
+            }
+        }
+
+        return serviceClass;
+    }
+
+    /**
+     * @param loader
+     * @param name
+     * @return
+     * @throws ClassNotFoundException
+     */
+    public static Class<?> loadClass(ClassLoader loader, String name) throws ClassNotFoundException {
+        Class<?> clazz;
+
+        try {
+            clazz = loader.loadClass(name);
+        } catch (ClassNotFoundException e) {
+            if (LOG.isWarnEnabled()) {
+                LOG.warn("Class " + name + "not found by Context Classloader");
+            }
+
+            // Try internal library classloader.
+            clazz = ServicesUtils.class.getClassLoader().loadClass(name);
+        }
+
+        return clazz;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/Zipper.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/Zipper.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/Zipper.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,20 +18,27 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.util;
 
 @Deprecated
-public class Zipper {
-	public static void zip(byte[] buf, int value, int offset) {
-		buf[offset] = (byte)(value & 0x0ff);
-		buf[offset+1] = (byte)((value & 0x0ff00)>>8);
-		buf[offset+2] = (byte)((value & 0x0ff0000)>>16);
-	}
-	public static int unzip(byte[] buf, int offset) {
-		int r0 = buf[offset]&0x0ff;
-		int r1 = (buf[offset+1]<<8)&0x0ff00;
-		int r2 = (buf[offset+2]<<16)&0x0ff0000;
-		int ret = r0 | r1 | r2;
-		return ret;
-	}
+public final class Zipper {
+    private Zipper() {}
+
+    public static void zip(byte[] buf, int value, int offset) {
+        buf[offset] = (byte) (value & 0x0ff);
+        buf[offset + 1] = (byte) ((value & 0x0ff00) >> 8);
+        buf[offset + 2] = (byte) ((value & 0x0ff0000) >> 16);
+    }
+
+    public static int unzip(byte[] buf, int offset) {
+        int r0 = buf[offset] & 0x0ff;
+        int r1 = (buf[offset + 1] << 8) & 0x0ff00;
+        int r2 = (buf[offset + 2] << 16) & 0x0ff0000;
+        int ret = r0 | r1 | r2;
+
+        return ret;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/Zipper2.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/Zipper2.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/Zipper2.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,112 +19,126 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util;
 
 import java.awt.Color;
+
 import java.nio.ByteBuffer;
 
 /**
- * 
+ *
  * <br /><br />
- * 
+ *
  * Created 21.08.2007
  * @author Nick Belaevski
  * @since 3.1
  */
 @Deprecated
 public class Zipper2 {
-	private byte[] buffer;
+    int offset = 0;
+    private byte[] buffer;
 
-	int offset = 0;
-	
-	public Zipper2(byte[] buffer) {
-		super();
-		this.buffer = buffer;
-	}
+    public Zipper2(byte[] buffer) {
+        super();
+        this.buffer = buffer;
+    }
 
-	public Zipper2(byte[] buffer, int offest) {
-		super();
-		this.buffer = buffer;
-		this.offset = offest;
-	}
+    public Zipper2(byte[] buffer, int offest) {
+        super();
+        this.buffer = buffer;
+        this.offset = offest;
+    }
 
-	public Zipper2 addByte(byte b) {
-		buffer[offset++] = b;
-		return this;
-	}
+    public Zipper2 addByte(byte b) {
+        buffer[offset++] = b;
 
-	public Zipper2 addShort(short s) {
-		ByteBuffer.wrap(buffer, offset, 2).asShortBuffer().put(s);
-		offset += 2;
-		return this;
-	}
+        return this;
+    }
 
-	public Zipper2 addColor(Color color) {
-		addColor(color.getRGB());
-		return this;
-	}
+    public Zipper2 addShort(short s) {
+        ByteBuffer.wrap(buffer, offset, 2).asShortBuffer().put(s);
+        offset += 2;
 
-	public Zipper2 addColor(int i) {
-		buffer[offset] = (byte) ((i >> 0) & 0xFF);
-		buffer[offset + 1] = (byte) ((i >> 8) & 0xFF);
-		buffer[offset + 2] = (byte) ((i >> 16) & 0xFF);
-		offset += 3;
-		return this;
-	}
-	
-	public Zipper2 addInt(int i) {
-		ByteBuffer.wrap(buffer, offset, 4).asIntBuffer().put(i);
-		offset += 4;
-		return this;
-	}
-	
-	public Zipper2 addBytes(byte[] bs) {
-	    if (bs != null) {
-		System.arraycopy(bs, 0, buffer, offset, bs.length);
-	    }
+        return this;
+    }
 
-	    return this;
-	}
-	
-	public byte nextByte() {
-		return buffer[offset++];
-	}
+    public Zipper2 addColor(Color color) {
+        addColor(color.getRGB());
 
-	public short nextShort() {
-		short s = ByteBuffer.wrap(buffer, offset, 2).asShortBuffer().get();
-		offset += 2;
-		return s;
-	}
-	
-	public Color nextColor() {
-		return new Color(nextIntColor());
-	}
-	
-	public int nextIntColor() {
-		int r0 = buffer[offset]&0x0ff;
-		int r1 = (buffer[offset+1]<<8)&0x0ff00;
-		int r2 = (buffer[offset+2]<<16)&0x0ff0000;
-		int ret = r0 | r1 | r2;
-		offset += 3;
-		return ret;
-	}
-	
-	public int nextInt() {
-		int i = ByteBuffer.wrap(buffer, offset, 4).asIntBuffer().get();
-		offset += 4;
-		return i;
-	}
-	
-	public byte[] nextBytes() {
-	    byte[] bs = new byte[buffer.length - offset];
-	    System.arraycopy(buffer, offset, bs, 0, buffer.length - offset);
-	    offset = buffer.length;
+        return this;
+    }
 
-	    return bs;
-	}
-	
-	public boolean hasMore() {
-		return offset < buffer.length;
-	}
+    public Zipper2 addColor(int i) {
+        buffer[offset] = (byte) ((i >> 0) & 0xFF);
+        buffer[offset + 1] = (byte) ((i >> 8) & 0xFF);
+        buffer[offset + 2] = (byte) ((i >> 16) & 0xFF);
+        offset += 3;
+
+        return this;
+    }
+
+    public Zipper2 addInt(int i) {
+        ByteBuffer.wrap(buffer, offset, 4).asIntBuffer().put(i);
+        offset += 4;
+
+        return this;
+    }
+
+    public Zipper2 addBytes(byte[] bs) {
+        if (bs != null) {
+            System.arraycopy(bs, 0, buffer, offset, bs.length);
+        }
+
+        return this;
+    }
+
+    public byte nextByte() {
+        return buffer[offset++];
+    }
+
+    public short nextShort() {
+        short s = ByteBuffer.wrap(buffer, offset, 2).asShortBuffer().get();
+
+        offset += 2;
+
+        return s;
+    }
+
+    public Color nextColor() {
+        return new Color(nextIntColor());
+    }
+
+    public int nextIntColor() {
+        int r0 = buffer[offset] & 0x0ff;
+        int r1 = (buffer[offset + 1] << 8) & 0x0ff00;
+        int r2 = (buffer[offset + 2] << 16) & 0x0ff0000;
+        int ret = r0 | r1 | r2;
+
+        offset += 3;
+
+        return ret;
+    }
+
+    public int nextInt() {
+        int i = ByteBuffer.wrap(buffer, offset, 4).asIntBuffer().get();
+
+        offset += 4;
+
+        return i;
+    }
+
+    public byte[] nextBytes() {
+        byte[] bs = new byte[buffer.length - offset];
+
+        System.arraycopy(buffer, offset, bs, 0, buffer.length - offset);
+        offset = buffer.length;
+
+        return bs;
+    }
+
+    public boolean hasMore() {
+        return offset < buffer.length;
+    }
 }

Deleted: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Base64.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Base64.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Base64.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,521 +0,0 @@
-/*
- * Copyright 2001-2004 The Apache Software Foundation.
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */ 
-
-package org.ajax4jsf.util.base64;
-
-import org.ajax4jsf.Messages;
-
-
-/**
- * Provides Base64 encoding and decoding as defined by RFC 2045.
- * 
- * <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> 
- * from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One: 
- * Format of Internet Message Bodies</cite> by Freed and Borenstein.</p> 
- *
- * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
- * @author Apache Software Foundation
- * @since 1.0-dev
- * @version $Id: Base64.java,v 1.1.2.1 2007/01/09 18:59:11 alexsmirnov Exp $
- */
-public class Base64 implements BinaryEncoder, BinaryDecoder {
-
-    /**
-     * Chunk size per RFC 2045 section 6.8.
-     * 
-     * <p>The {@value} character limit does not count the trailing CRLF, but counts 
-     * all other characters, including any equal signs.</p>
-     * 
-     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
-     */
-    static final int CHUNK_SIZE = 76;
-
-    /**
-     * Chunk separator per RFC 2045 section 2.1.
-     * 
-     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
-     */
-    static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
-
-    /**
-     * The base length.
-     */
-    static final int BASELENGTH = 255;
-
-    /**
-     * Lookup length.
-     */
-    static final int LOOKUPLENGTH = 64;
-
-    /**
-     * Used to calculate the number of bits in a byte.
-     */
-    static final int EIGHTBIT = 8;
-
-    /**
-     * Used when encoding something which has fewer than 24 bits.
-     */
-    static final int SIXTEENBIT = 16;
-
-    /**
-     * Used to determine how many bits data contains.
-     */
-    static final int TWENTYFOURBITGROUP = 24;
-
-    /**
-     * Used to get the number of Quadruples.
-     */
-    static final int FOURBYTE = 4;
-
-    /**
-     * Used to test the sign of a byte.
-     */
-    static final int SIGN = -128;
-    
-    /**
-     * Byte used to pad output.
-     */
-    static final byte PAD = (byte) '=';
-
-    // Create arrays to hold the base64 characters and a 
-    // lookup for base64 chars
-    private static byte[] base64Alphabet = new byte[BASELENGTH];
-    private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
-
-    // Populating the lookup and character arrays
-    static {
-        for (int i = 0; i < BASELENGTH; i++) {
-            base64Alphabet[i] = (byte) -1;
-        }
-        for (int i = 'Z'; i >= 'A'; i--) {
-            base64Alphabet[i] = (byte) (i - 'A');
-        }
-        for (int i = 'z'; i >= 'a'; i--) {
-            base64Alphabet[i] = (byte) (i - 'a' + 26);
-        }
-        for (int i = '9'; i >= '0'; i--) {
-            base64Alphabet[i] = (byte) (i - '0' + 52);
-        }
-
-        base64Alphabet['+'] = 62;
-        base64Alphabet['/'] = 63;
-
-        for (int i = 0; i <= 25; i++) {
-            lookUpBase64Alphabet[i] = (byte) ('A' + i);
-        }
-
-        for (int i = 26, j = 0; i <= 51; i++, j++) {
-            lookUpBase64Alphabet[i] = (byte) ('a' + j);
-        }
-
-        for (int i = 52, j = 0; i <= 61; i++, j++) {
-            lookUpBase64Alphabet[i] = (byte) ('0' + j);
-        }
-
-        lookUpBase64Alphabet[62] = (byte) '+';
-        lookUpBase64Alphabet[63] = (byte) '/';
-    }
-
-    private static boolean isBase64(byte octect) {
-        if (octect == PAD) {
-            return true;
-        } else if (base64Alphabet[octect] == -1) {
-            return false;
-        } else {
-            return true;
-        }
-    }
-
-    /**
-     * Tests a given byte array to see if it contains
-     * only valid characters within the Base64 alphabet.
-     *
-     * @param arrayOctect byte array to test
-     * @return true if all bytes are valid characters in the Base64
-     *         alphabet or if the byte array is empty; false, otherwise
-     */
-    public static boolean isArrayByteBase64(byte[] arrayOctect) {
-
-        arrayOctect = discardWhitespace(arrayOctect);
-
-        int length = arrayOctect.length;
-        if (length == 0) {
-            // shouldn't a 0 length array be valid base64 data?
-            // return false;
-            return true;
-        }
-        for (int i = 0; i < length; i++) {
-            if (!isBase64(arrayOctect[i])) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    /**
-     * Encodes binary data using the base64 algorithm but
-     * does not chunk the output.
-     *
-     * @param binaryData binary data to encode
-     * @return Base64 characters
-     */
-    public static byte[] encodeBase64(byte[] binaryData) {
-        return encodeBase64(binaryData, false);
-    }
-
-    /**
-     * Encodes binary data using the base64 algorithm and chunks
-     * the encoded output into 76 character blocks
-     *
-     * @param binaryData binary data to encode
-     * @return Base64 characters chunked in 76 character blocks
-     */
-    public static byte[] encodeBase64Chunked(byte[] binaryData) {
-        return encodeBase64(binaryData, true);
-    }
-
-
-    /**
-     * Decodes an Object using the base64 algorithm.  This method
-     * is provided in order to satisfy the requirements of the
-     * Decoder interface, and will throw a DecoderException if the
-     * supplied object is not of type byte[].
-     *
-     * @param pObject Object to decode
-     * @return An object (of type byte[]) containing the 
-     *         binary data which corresponds to the byte[] supplied.
-     * @throws DecoderException if the parameter supplied is not
-     *                          of type byte[]
-     */
-    public Object decode(Object pObject) throws DecoderException {
-        if (!(pObject instanceof byte[])) {
-            throw new DecoderException(Messages.getMessage(Messages.NO_BYTE_ARRAY_ERROR));
-        }
-        return decode((byte[]) pObject);
-    }
-
-    /**
-     * Decodes a byte[] containing containing
-     * characters in the Base64 alphabet.
-     *
-     * @param pArray A byte array containing Base64 character data
-     * @return a byte array containing binary data
-     */
-    public byte[] decode(byte[] pArray) {
-        return decodeBase64(pArray);
-    }
-
-    /**
-     * Encodes binary data using the base64 algorithm, optionally
-     * chunking the output into 76 character blocks.
-     *
-     * @param binaryData Array containing binary data to encode.
-     * @param isChunked if isChunked is true this encoder will chunk
-     *                  the base64 output into 76 character blocks
-     * @return Base64-encoded data.
-     */
-    public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
-        int lengthDataBits = binaryData.length * EIGHTBIT;
-        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
-        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
-        byte encodedData[] = null;
-        int encodedDataLength = 0;
-        int nbrChunks = 0;
-
-        if (fewerThan24bits != 0) {
-            //data not divisible by 24 bit
-            encodedDataLength = (numberTriplets + 1) * 4;
-        } else {
-            // 16 or 8 bit
-            encodedDataLength = numberTriplets * 4;
-        }
-
-        // If the output is to be "chunked" into 76 character sections, 
-        // for compliance with RFC 2045 MIME, then it is important to 
-        // allow for extra length to account for the separator(s)
-        if (isChunked) {
-
-            nbrChunks =
-                (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));
-            encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
-        }
-
-        encodedData = new byte[encodedDataLength];
-
-        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
-
-        int encodedIndex = 0;
-        int dataIndex = 0;
-        int i = 0;
-        int nextSeparatorIndex = CHUNK_SIZE;
-        int chunksSoFar = 0;
-
-        //log.debug("number of triplets = " + numberTriplets);
-        for (i = 0; i < numberTriplets; i++) {
-            dataIndex = i * 3;
-            b1 = binaryData[dataIndex];
-            b2 = binaryData[dataIndex + 1];
-            b3 = binaryData[dataIndex + 2];
-
-            //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
-
-            l = (byte) (b2 & 0x0f);
-            k = (byte) (b1 & 0x03);
-
-            byte val1 =
-                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
-            byte val2 =
-                ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
-            byte val3 =
-                ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
-
-            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
-            //log.debug( "val2 = " + val2 );
-            //log.debug( "k4   = " + (k<<4) );
-            //log.debug(  "vak  = " + (val2 | (k<<4)) );
-            encodedData[encodedIndex + 1] =
-                lookUpBase64Alphabet[val2 | (k << 4)];
-            encodedData[encodedIndex + 2] =
-                lookUpBase64Alphabet[(l << 2) | val3];
-            encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
-
-            encodedIndex += 4;
-
-            // If we are chunking, let's put a chunk separator down.
-            if (isChunked) {
-                // this assumes that CHUNK_SIZE % 4 == 0
-                if (encodedIndex == nextSeparatorIndex) {
-                    System.arraycopy(
-                        CHUNK_SEPARATOR,
-                        0,
-                        encodedData,
-                        encodedIndex,
-                        CHUNK_SEPARATOR.length);
-                    chunksSoFar++;
-                    nextSeparatorIndex =
-                        (CHUNK_SIZE * (chunksSoFar + 1)) + 
-                        (chunksSoFar * CHUNK_SEPARATOR.length);
-                    encodedIndex += CHUNK_SEPARATOR.length;
-                }
-            }
-        }
-
-        // form integral number of 6-bit groups
-        dataIndex = i * 3;
-
-        if (fewerThan24bits == EIGHTBIT) {
-            b1 = binaryData[dataIndex];
-            k = (byte) (b1 & 0x03);
-            //log.debug("b1=" + b1);
-            //log.debug("b1<<2 = " + (b1>>2) );
-            byte val1 =
-                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
-            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
-            encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
-            encodedData[encodedIndex + 2] = PAD;
-            encodedData[encodedIndex + 3] = PAD;
-        } else if (fewerThan24bits == SIXTEENBIT) {
-
-            b1 = binaryData[dataIndex];
-            b2 = binaryData[dataIndex + 1];
-            l = (byte) (b2 & 0x0f);
-            k = (byte) (b1 & 0x03);
-
-            byte val1 =
-                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
-            byte val2 =
-                ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
-
-            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
-            encodedData[encodedIndex + 1] =
-                lookUpBase64Alphabet[val2 | (k << 4)];
-            encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
-            encodedData[encodedIndex + 3] = PAD;
-        }
-
-        if (isChunked) {
-            // we also add a separator to the end of the final chunk.
-            if (chunksSoFar < nbrChunks) {
-                System.arraycopy(
-                    CHUNK_SEPARATOR,
-                    0,
-                    encodedData,
-                    encodedDataLength - CHUNK_SEPARATOR.length,
-                    CHUNK_SEPARATOR.length);
-            }
-        }
-
-        return encodedData;
-    }
-
-    /**
-     * Decodes Base64 data into octects
-     *
-     * @param base64Data Byte array containing Base64 data
-     * @return Array containing decoded data.
-     */
-    public static byte[] decodeBase64(byte[] base64Data) {
-        // RFC 2045 requires that we discard ALL non-Base64 characters
-        base64Data = discardNonBase64(base64Data);
-
-        // handle the edge case, so we don't have to worry about it later
-        if (base64Data.length == 0) {
-            return new byte[0];
-        }
-
-        int numberQuadruple = base64Data.length / FOURBYTE;
-        byte decodedData[] = null;
-        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
-
-        // Throw away anything not in base64Data
-
-        int encodedIndex = 0;
-        int dataIndex = 0;
-        {
-            // this sizes the output array properly - rlw
-            int lastData = base64Data.length;
-            // ignore the '=' padding
-            while (base64Data[lastData - 1] == PAD) {
-                if (--lastData == 0) {
-                    return new byte[0];
-                }
-            }
-            decodedData = new byte[lastData - numberQuadruple];
-        }
-        
-        for (int i = 0; i < numberQuadruple; i++) {
-            dataIndex = i * 4;
-            marker0 = base64Data[dataIndex + 2];
-            marker1 = base64Data[dataIndex + 3];
-            
-            b1 = base64Alphabet[base64Data[dataIndex]];
-            b2 = base64Alphabet[base64Data[dataIndex + 1]];
-            
-            if (marker0 != PAD && marker1 != PAD) {
-                //No PAD e.g 3cQl
-                b3 = base64Alphabet[marker0];
-                b4 = base64Alphabet[marker1];
-                
-                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
-                decodedData[encodedIndex + 1] =
-                    (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
-                decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
-            } else if (marker0 == PAD) {
-                //Two PAD e.g. 3c[Pad][Pad]
-                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
-            } else if (marker1 == PAD) {
-                //One PAD e.g. 3cQ[Pad]
-                b3 = base64Alphabet[marker0];
-                
-                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
-                decodedData[encodedIndex + 1] =
-                    (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
-            }
-            encodedIndex += 3;
-        }
-        return decodedData;
-    }
-    
-    /**
-     * Discards any whitespace from a base-64 encoded block.
-     *
-     * @param data The base-64 encoded data to discard the whitespace
-     * from.
-     * @return The data, less whitespace (see RFC 2045).
-     */
-    static byte[] discardWhitespace(byte[] data) {
-        byte groomedData[] = new byte[data.length];
-        int bytesCopied = 0;
-        
-        for (int i = 0; i < data.length; i++) {
-            switch (data[i]) {
-            case (byte) ' ' :
-            case (byte) '\n' :
-            case (byte) '\r' :
-            case (byte) '\t' :
-                    break;
-            default:
-                    groomedData[bytesCopied++] = data[i];
-            }
-        }
-
-        byte packedData[] = new byte[bytesCopied];
-
-        System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
-
-        return packedData;
-    }
-
-    /**
-     * Discards any characters outside of the base64 alphabet, per
-     * the requirements on page 25 of RFC 2045 - "Any characters
-     * outside of the base64 alphabet are to be ignored in base64
-     * encoded data."
-     *
-     * @param data The base-64 encoded data to groom
-     * @return The data, less non-base64 characters (see RFC 2045).
-     */
-    static byte[] discardNonBase64(byte[] data) {
-        byte groomedData[] = new byte[data.length];
-        int bytesCopied = 0;
-
-        for (int i = 0; i < data.length; i++) {
-            if (isBase64(data[i])) {
-                groomedData[bytesCopied++] = data[i];
-            }
-        }
-
-        byte packedData[] = new byte[bytesCopied];
-
-        System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
-
-        return packedData;
-    }
-
-
-    // Implementation of the Encoder Interface
-
-    /**
-     * Encodes an Object using the base64 algorithm.  This method
-     * is provided in order to satisfy the requirements of the
-     * Encoder interface, and will throw an EncoderException if the
-     * supplied object is not of type byte[].
-     *
-     * @param pObject Object to encode
-     * @return An object (of type byte[]) containing the 
-     *         base64 encoded data which corresponds to the byte[] supplied.
-     * @throws EncoderException if the parameter supplied is not
-     *                          of type byte[]
-     */
-    public Object encode(Object pObject) throws EncoderException {
-        if (!(pObject instanceof byte[])) {
-            throw new EncoderException(Messages.getMessage(Messages.NO_BYTE_ARRAY_ERROR));
-        }
-        return encode((byte[]) pObject);
-    }
-
-    /**
-     * Encodes a byte[] containing binary data, into a byte[] containing
-     * characters in the Base64 alphabet.
-     *
-     * @param pArray a byte array containing binary data
-     * @return A byte array containing only Base64 character data
-     */
-    public byte[] encode(byte[] pArray) {
-        return encodeBase64(pArray, false);
-    }
-
-}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/BinaryDecoder.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/BinaryDecoder.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/BinaryDecoder.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,19 +1,21 @@
 /*
  * Copyright 2001-2004 The Apache Software Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */ 
+ */
 
+
+
 package org.ajax4jsf.util.base64;
 
 /**
@@ -25,17 +27,16 @@
 public interface BinaryDecoder extends Decoder {
 
     /**
-     * Decodes a byte array and returns the results as a byte array. 
+     * Decodes a byte array and returns the results as a byte array.
      *
      * @param pArray A byte array which has been encoded with the
      *      appropriate encoder
-     * 
+     *
      * @return a byte array that contains decoded content
-     * 
+     *
      * @throws DecoderException A decoder exception is thrown
      *          if a Decoder encounters a failure condition during
      *          the decode process.
      */
     byte[] decode(byte[] pArray) throws DecoderException;
-}  
-
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/BinaryEncoder.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/BinaryEncoder.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/BinaryEncoder.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,41 +1,42 @@
 /*
  * Copyright 2001-2004 The Apache Software Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */ 
+ */
 
+
+
 package org.ajax4jsf.util.base64;
 
 /**
  * Defines common encoding methods for byte array encoders.
- * 
+ *
  * @author Apache Software Foundation
  * @version $Id: BinaryEncoder.java,v 1.1.2.1 2007/01/09 18:59:13 alexsmirnov Exp $
  */
 public interface BinaryEncoder extends Encoder {
-    
+
     /**
      * Encodes a byte array and return the encoded data
      * as a byte array.
-     * 
+     *
      * @param pArray Data to be encoded
      *
      * @return A byte array containing the encoded data
-     * 
+     *
      * @throws EncoderException thrown if the Encoder
      *      encounters a failure condition during the
      *      encoding process.
      */
     byte[] encode(byte[] pArray) throws EncoderException;
-}  
-
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Codec.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Codec.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Codec.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,19 +19,17 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.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;
 
 /**
@@ -40,99 +38,100 @@
  *
  */
 public class Codec {
+    private Cipher d = null;
+    private Cipher e = null;
 
-	private Cipher e = null;
-	private Cipher d = null;
-	
+    /**
+     *
+     */
+    public Codec() {}
 
-	/**
-	 * 
-	 */
-	public Codec() {
-	}
+    /**
+     *
+     */
+    public Codec(String p) throws Exception {
+        setPassword(p);
+    }
 
-	/**
-	 * 
-	 */
-	public Codec( String p ) throws Exception {
-		 setPassword(p);
-	}
+    /**
+     * @param p
+     * @throws java.security.InvalidKeyException
+     * @throws java.io.UnsupportedEncodingException
+     * @throws java.security.spec.InvalidKeySpecException
+     * @throws java.security.NoSuchAlgorithmException
+     * @throws javax.crypto.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
+        };
 
-	/**
-	 * @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());
+        try {
+            KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8"));
+            SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
 
-	    	// Prepare the parameters to the cipthers
-//			AlgorithmParameterSpec paramSpec = new IvParameterSpec(s);
+            e = Cipher.getInstance(key.getAlgorithm());
+            d = Cipher.getInstance(key.getAlgorithm());
 
-	    	e.init(Cipher.ENCRYPT_MODE, key);
-	    	d.init(Cipher.DECRYPT_MODE, key);
-		} catch (Exception e) {
-			throw new FacesException("Error set encryption key",e);
-		}
-	}
+            // 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) {
+            throw new FacesException("Error set encryption key", e);
+        }
+    }
 
-	public String decode(String str) throws Exception {
-			byte[] src = str.getBytes("UTF8");
-			byte[] utf8 = decode(src);
-			// Decode using utf-8
-			return new String(utf8, "UTF8");
-	}
-	public String encode(String str) throws Exception {
-//        try {
-		    
-			byte[] src = str.getBytes("UTF8");
-//			int len = (src.length/8+1)*8;
-//			byte[] block = new byte[len];
-//			Arrays.fill(block,0,len,(byte)0x20);
-//			System.arraycopy(src,0,block,0,src.length);
+    public String decode(String str) throws Exception {
+        byte[] src = str.getBytes("UTF8");
+        byte[] utf8 = decode(src);
 
-			// Decrypt
-			byte[] utf8 = encode(src);
+        // Decode using utf-8
+        return new String(utf8, "UTF8");
+    }
 
-			// Decode using utf-8
-			return new String(utf8, "UTF8");
-//		} catch (Exception e) {
-//			// TODO: handle exception
-//			return null;
-//		}
-	}
-	
-	public byte[] decode(byte[] src) throws Exception {
-		byte[] dec = URL64Codec.decodeBase64(src);
-		// Decrypt
-		if (null != d) {
-			return d.doFinal(dec);
-		} else {
-			return dec;
-		}
-	}
+    public String encode(String str) throws Exception {
 
-	public byte[] encode(byte[] src) throws Exception {
-		byte[] dec;
-		if(null != e){
-			dec = e.doFinal(src);
-		} else {
-			dec = src;
-		}
-		// Decrypt
-		return URL64Codec.encodeBase64(dec);
-	}
+//      try {
+        byte[] src = str.getBytes("UTF8");
 
+//      int len = (src.length/8+1)*8;
+//      byte[] block = new byte[len];
+//      Arrays.fill(block,0,len,(byte)0x20);
+//      System.arraycopy(src,0,block,0,src.length);
+        // Decrypt
+        byte[] utf8 = encode(src);
+
+        // Decode using utf-8
+        return new String(utf8, "UTF8");
+
+//      } catch (Exception e) {
+//          // TODO: handle exception
+//          return null;
+//      }
+    }
+
+    public byte[] decode(byte[] src) throws Exception {
+        byte[] dec = URL64Codec.decodeBase64(src);
+
+        // Decrypt
+        if (null != d) {
+            return d.doFinal(dec);
+        } else {
+            return dec;
+        }
+    }
+
+    public byte[] encode(byte[] src) throws Exception {
+        byte[] dec;
+
+        if (null != e) {
+            dec = e.doFinal(src);
+        } else {
+            dec = src;
+        }
+
+        // Decrypt
+        return URL64Codec.encodeBase64(dec);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Decoder.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Decoder.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Decoder.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,31 +1,33 @@
 /*
  * Copyright 2001-2004 The Apache Software Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */ 
+ */
 
+
+
 package org.ajax4jsf.util.base64;
 
 /**
  * <p>Provides the highest level of abstraction for Decoders.
  * This is the sister interface of {@link Encoder}.  All
  * Decoders implement this common generic interface.</p>
- * 
- * <p>Allows a user to pass a generic Object to any Decoder 
+ *
+ * <p>Allows a user to pass a generic Object to any Decoder
  * implementation in the codec package.</p>
- * 
+ *
  * <p>One of the two interfaces at the center of the codec package.</p>
- * 
+ *
  * @author Apache Software Foundation
  * @version $Id: Decoder.java,v 1.1.2.1 2007/01/09 18:59:14 alexsmirnov Exp $
  */
@@ -38,11 +40,11 @@
      * to the specific type expected by a particular Decoder
      * implementation.  If a {@link java.lang.ClassCastException} occurs
      * this decode method will throw a DecoderException.
-     * 
+     *
      * @param pObject an object to "decode"
-     * 
+     *
      * @return a 'decoded" object
-     * 
+     *
      * @throws DecoderException a decoder exception can
      * be thrown for any number of reasons.  Some good
      * candidates are that the parameter passed to this
@@ -50,5 +52,4 @@
      * appropriate type for a specific encoder.
      */
     Object decode(Object pObject) throws DecoderException;
-}  
-
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/DecoderException.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/DecoderException.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/DecoderException.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,24 +1,26 @@
 /*
  * Copyright 2001-2004 The Apache Software Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */ 
+ */
 
+
+
 package org.ajax4jsf.util.base64;
 
 /**
- * Thrown when a Decoder has encountered a failure condition during a decode. 
- * 
+ * Thrown when a Decoder has encountered a failure condition during a decode.
+ *
  * @author Apache Software Foundation
  * @version $Id: DecoderException.java,v 1.1.2.1 2007/01/09 18:59:13 alexsmirnov Exp $
  */
@@ -26,12 +28,10 @@
 
     /**
      * Creates a DecoderException
-     * 
+     *
      * @param pMessage A message with meaning to a human
      */
     public DecoderException(String pMessage) {
         super(pMessage);
     }
-
-}  
-
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Encoder.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Encoder.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/Encoder.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,45 +1,46 @@
 /*
  * Copyright 2001-2004 The Apache Software Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */ 
+ */
 
+
+
 package org.ajax4jsf.util.base64;
 
 /**
  * <p>Provides the highest level of abstraction for Encoders.
  * This is the sister interface of {@link Decoder}.  Every implementation of
- * Encoder provides this common generic interface whic allows a user to pass a 
+ * Encoder provides this common generic interface whic allows a user to pass a
  * generic Object to any Encoder implementation in the codec package.</p>
  *
  * @author Apache Software Foundation
  * @version $Id: Encoder.java,v 1.1.2.1 2007/01/09 18:59:12 alexsmirnov Exp $
  */
 public interface Encoder {
-    
+
     /**
-     * Encodes an "Object" and returns the encoded content 
+     * Encodes an "Object" and returns the encoded content
      * as an Object.  The Objects here may just be <code>byte[]</code>
      * or <code>String</code>s depending on the implementation used.
-     *   
+     *
      * @param pObject An object ot encode
-     * 
+     *
      * @return An "encoded" Object
-     * 
+     *
      * @throws EncoderException an encoder exception is
      *  thrown if the encoder experiences a failure
      *  condition during the encoding process.
      */
     Object encode(Object pObject) throws EncoderException;
-}  
-
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/EncoderException.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/EncoderException.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/EncoderException.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,27 +1,29 @@
 /*
  * Copyright 2001-2004 The Apache Software Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */ 
+ */
 
+
+
 package org.ajax4jsf.util.base64;
 
 /**
  * Thrown when there is a failure condition during the encoding process.  This
  * exception is thrown when an Encoder encounters a encoding specific exception
- * such as invalid data, inability to calculate a checksum, characters outside of the 
+ * such as invalid data, inability to calculate a checksum, characters outside of the
  * expected range.
- * 
+ *
  * @author Apache Software Foundation
  * @version $Id: EncoderException.java,v 1.1.2.1 2007/01/09 18:59:12 alexsmirnov Exp $
  */
@@ -29,11 +31,10 @@
 
     /**
      * Creates a new instance of this exception with an useful message.
-     * 
+     *
      * @param pMessage a useful message relating to the encoder specific error.
      */
     public EncoderException(String pMessage) {
         super(pMessage);
     }
-}  
-
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/URL64Codec.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/URL64Codec.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/URL64Codec.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,29 +1,30 @@
 /*
  * Copyright 2001-2004 The Apache Software Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */ 
+ */
 
+
+
 package org.ajax4jsf.util.base64;
 
 import org.ajax4jsf.Messages;
 
-
 /**
  * Provides Base64 encoding and decoding like defined by RFC 2045, but with little difference :
- * chars '=' '+' and '/' , incorrectly processed in URL by any browsers, replaced by '_' '-' '!', 
- * 
+ * chars '=' '+' and '/' , incorrectly processed in URL by any browsers, replaced by '_' '-' '!',
  *
+ *
  * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
  * @author Apache Software Foundation
  * @since 1.0-dev
@@ -32,38 +33,53 @@
 public class URL64Codec implements BinaryEncoder, BinaryDecoder {
 
     /**
+     * The base length.
+     */
+    static final int BASELENGTH = 255;
+
+    /**
      * Chunk size per RFC 2045 section 6.8.
-     * 
-     * <p>The {@value} character limit does not count the trailing CRLF, but counts 
+     *
+     * <p>The {@value} character limit does not count the trailing CRLF, but counts
      * all other characters, including any equal signs.</p>
-     * 
+     *
      * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
      */
     static final int CHUNK_SIZE = 76;
 
     /**
      * Chunk separator per RFC 2045 section 2.1.
-     * 
+     *
      * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
      */
     static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
 
     /**
-     * The base length.
+     * Used to calculate the number of bits in a byte.
      */
-    static final int BASELENGTH = 255;
+    static final int EIGHTBIT = 8;
 
     /**
+     * Used to get the number of Quadruples.
+     */
+    static final int FOURBYTE = 4;
+
+    /**
      * Lookup length.
      */
     static final int LOOKUPLENGTH = 64;
 
     /**
-     * Used to calculate the number of bits in a byte.
+     * Byte used to pad output. instesd of '=' in base64, used '_'
      */
-    static final int EIGHTBIT = 8;
+    static final byte PAD = (byte) '_';
 
     /**
+     * Used to test the sign of a byte.
+     */
+    static final int SIGN = -128;
+
+    /**
      * Used when encoding something which has fewer than 24 bits.
      */
     static final int SIXTEENBIT = 16;
@@ -73,22 +89,7 @@
      */
     static final int TWENTYFOURBITGROUP = 24;
 
-    /**
-     * Used to get the number of Quadruples.
-     */
-    static final int FOURBYTE = 4;
-
-    /**
-     * Used to test the sign of a byte.
-     */
-    static final int SIGN = -128;
-    
-    /**
-     * Byte used to pad output. instesd of '=' in base64, used '_'
-     */
-    static final byte PAD = (byte) '_';
-
-    // Create arrays to hold the base64 characters and a 
+    // Create arrays to hold the base64 characters and a
     // lookup for base64 chars
     private static byte[] base64Alphabet = new byte[BASELENGTH];
     private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
@@ -98,12 +99,15 @@
         for (int i = 0; i < BASELENGTH; i++) {
             base64Alphabet[i] = (byte) -1;
         }
+
         for (int i = 'Z'; i >= 'A'; i--) {
             base64Alphabet[i] = (byte) (i - 'A');
         }
+
         for (int i = 'z'; i >= 'a'; i--) {
             base64Alphabet[i] = (byte) (i - 'a' + 26);
         }
+
         for (int i = '9'; i >= '0'; i--) {
             base64Alphabet[i] = (byte) (i - '0' + 52);
         }
@@ -116,11 +120,15 @@
             lookUpBase64Alphabet[i] = (byte) ('A' + i);
         }
 
-        for (int i = 26, j = 0; i <= 51; i++, j++) {
+        int j = 0;
+
+        for (int i = 26; i <= 51; i++, j++) {
             lookUpBase64Alphabet[i] = (byte) ('a' + j);
         }
 
-        for (int i = 52, j = 0; i <= 61; i++, j++) {
+        j = 0;
+
+        for (int i = 52; i <= 61; i++, j++) {
             lookUpBase64Alphabet[i] = (byte) ('0' + j);
         }
 
@@ -132,10 +140,8 @@
     private static boolean isBase64(byte octect) {
         if (octect == PAD) {
             return true;
-        } else if (base64Alphabet[octect] == -1) {
-            return false;
         } else {
-            return true;
+            return base64Alphabet[octect] != -1;
         }
     }
 
@@ -148,20 +154,23 @@
      *         alphabet or if the byte array is empty; false, otherwise
      */
     public static boolean isArrayByteBase64(byte[] arrayOctect) {
-
         arrayOctect = discardWhitespace(arrayOctect);
 
         int length = arrayOctect.length;
+
         if (length == 0) {
+
             // shouldn't a 0 length array be valid base64 data?
             // return false;
             return true;
         }
+
         for (int i = 0; i < length; i++) {
             if (!isBase64(arrayOctect[i])) {
                 return false;
             }
         }
+
         return true;
     }
 
@@ -187,7 +196,6 @@
         return encodeBase64(binaryData, true);
     }
 
-
     /**
      * Decodes an Object using the base64 algorithm.  This method
      * is provided in order to satisfy the requirements of the
@@ -195,7 +203,7 @@
      * supplied object is not of type byte[].
      *
      * @param pObject Object to decode
-     * @return An object (of type byte[]) containing the 
+     * @return An object (of type byte[]) containing the
      *         binary data which corresponds to the byte[] supplied.
      * @throws DecoderException if the parameter supplied is not
      *                          of type byte[]
@@ -204,6 +212,7 @@
         if (!(pObject instanceof byte[])) {
             throw new DecoderException(Messages.getMessage(Messages.NO_BYTE_ARRAY_ERROR));
         }
+
         return decode((byte[]) pObject);
     }
 
@@ -231,83 +240,74 @@
         int lengthDataBits = binaryData.length * EIGHTBIT;
         int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
         int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
-        byte encodedData[] = null;
+        byte[] encodedData;
         int encodedDataLength = 0;
         int nbrChunks = 0;
 
         if (fewerThan24bits != 0) {
-            //data not divisible by 24 bit
+
+            // data not divisible by 24 bit
             encodedDataLength = (numberTriplets + 1) * 4;
         } else {
+
             // 16 or 8 bit
             encodedDataLength = numberTriplets * 4;
         }
 
-        // If the output is to be "chunked" into 76 character sections, 
-        // for compliance with RFC 2045 MIME, then it is important to 
+        // If the output is to be "chunked" into 76 character sections,
+        // for compliance with RFC 2045 MIME, then it is important to
         // allow for extra length to account for the separator(s)
         if (isChunked) {
-
-            nbrChunks =
-                (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));
+            nbrChunks = (CHUNK_SEPARATOR.length == 0) ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE);
             encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
         }
 
         encodedData = new byte[encodedDataLength];
 
-        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
-
+        byte k = 0;
+        byte l = 0;
+        byte b1 = 0;
+        byte b2 = 0;
+        byte b3 = 0;
         int encodedIndex = 0;
         int dataIndex = 0;
         int i = 0;
         int nextSeparatorIndex = CHUNK_SIZE;
         int chunksSoFar = 0;
 
-        //log.debug("number of triplets = " + numberTriplets);
+        // log.debug("number of triplets = " + numberTriplets);
         for (i = 0; i < numberTriplets; i++) {
             dataIndex = i * 3;
             b1 = binaryData[dataIndex];
             b2 = binaryData[dataIndex + 1];
             b3 = binaryData[dataIndex + 2];
 
-            //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
-
+            // log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
             l = (byte) (b2 & 0x0f);
             k = (byte) (b1 & 0x03);
 
-            byte val1 =
-                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
-            byte val2 =
-                ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
-            byte val3 =
-                ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
+            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 0xc0);
+            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) (b2 >> 4 ^ 0xf0);
+            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) (b3 >> 6 ^ 0xfc);
 
             encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
-            //log.debug( "val2 = " + val2 );
-            //log.debug( "k4   = " + (k<<4) );
-            //log.debug(  "vak  = " + (val2 | (k<<4)) );
-            encodedData[encodedIndex + 1] =
-                lookUpBase64Alphabet[val2 | (k << 4)];
-            encodedData[encodedIndex + 2] =
-                lookUpBase64Alphabet[(l << 2) | val3];
+
+            // log.debug( "val2 = " + val2 );
+            // log.debug( "k4   = " + (k<<4) );
+            // log.debug(  "vak  = " + (val2 | (k<<4)) );
+            encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
+            encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3];
             encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
-
             encodedIndex += 4;
 
             // If we are chunking, let's put a chunk separator down.
             if (isChunked) {
+
                 // this assumes that CHUNK_SIZE % 4 == 0
                 if (encodedIndex == nextSeparatorIndex) {
-                    System.arraycopy(
-                        CHUNK_SEPARATOR,
-                        0,
-                        encodedData,
-                        encodedIndex,
-                        CHUNK_SEPARATOR.length);
+                    System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length);
                     chunksSoFar++;
-                    nextSeparatorIndex =
-                        (CHUNK_SIZE * (chunksSoFar + 1)) + 
-                        (chunksSoFar * CHUNK_SEPARATOR.length);
+                    nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length);
                     encodedIndex += CHUNK_SEPARATOR.length;
                 }
             }
@@ -319,42 +319,36 @@
         if (fewerThan24bits == EIGHTBIT) {
             b1 = binaryData[dataIndex];
             k = (byte) (b1 & 0x03);
-            //log.debug("b1=" + b1);
-            //log.debug("b1<<2 = " + (b1>>2) );
-            byte val1 =
-                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+
+            // log.debug("b1=" + b1);
+            // log.debug("b1<<2 = " + (b1>>2) );
+            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 0xc0);
+
             encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
             encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
             encodedData[encodedIndex + 2] = PAD;
             encodedData[encodedIndex + 3] = PAD;
         } else if (fewerThan24bits == SIXTEENBIT) {
-
             b1 = binaryData[dataIndex];
             b2 = binaryData[dataIndex + 1];
             l = (byte) (b2 & 0x0f);
             k = (byte) (b1 & 0x03);
 
-            byte val1 =
-                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
-            byte val2 =
-                ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
+            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 0xc0);
+            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) (b2 >> 4 ^ 0xf0);
 
             encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
-            encodedData[encodedIndex + 1] =
-                lookUpBase64Alphabet[val2 | (k << 4)];
+            encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
             encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
             encodedData[encodedIndex + 3] = PAD;
         }
 
         if (isChunked) {
+
             // we also add a separator to the end of the final chunk.
             if (chunksSoFar < nbrChunks) {
-                System.arraycopy(
-                    CHUNK_SEPARATOR,
-                    0,
-                    encodedData,
-                    encodedDataLength - CHUNK_SEPARATOR.length,
-                    CHUNK_SEPARATOR.length);
+                System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length,
+                                 CHUNK_SEPARATOR.length);
             }
         }
 
@@ -368,6 +362,7 @@
      * @return Array containing decoded data.
      */
     public static byte[] decodeBase64(byte[] base64Data) {
+
         // RFC 2045 requires that we discard ALL non-Base64 characters
         base64Data = discardNonBase64(base64Data);
 
@@ -377,58 +372,63 @@
         }
 
         int numberQuadruple = base64Data.length / FOURBYTE;
-        byte decodedData[] = null;
-        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
+        byte[] decodedData = null;
+        byte b1 = 0;
+        byte b2 = 0;
+        byte b3 = 0;
+        byte b4 = 0;
+        byte marker0 = 0;
+        byte marker1 = 0;
 
         // Throw away anything not in base64Data
-
         int encodedIndex = 0;
         int dataIndex = 0;
-        {
-            // this sizes the output array properly - rlw
-            int lastData = base64Data.length;
-            // ignore the '=' padding
-            while (base64Data[lastData - 1] == PAD) {
-                if (--lastData == 0) {
-                    return new byte[0];
-                }
+
+        // this sizes the output array properly - rlw
+        int lastData = base64Data.length;
+
+        // ignore the '=' padding
+        while (base64Data[lastData - 1] == PAD) {
+            if (--lastData == 0) {
+                return new byte[0];
             }
-            decodedData = new byte[lastData - numberQuadruple];
         }
-        
+
+        decodedData = new byte[lastData - numberQuadruple];
+
         for (int i = 0; i < numberQuadruple; i++) {
             dataIndex = i * 4;
             marker0 = base64Data[dataIndex + 2];
             marker1 = base64Data[dataIndex + 3];
-            
             b1 = base64Alphabet[base64Data[dataIndex]];
             b2 = base64Alphabet[base64Data[dataIndex + 1]];
-            
-            if (marker0 != PAD && marker1 != PAD) {
-                //No PAD e.g 3cQl
+
+            if ((marker0 != PAD) && (marker1 != PAD)) {
+
+                // No PAD e.g 3cQl
                 b3 = base64Alphabet[marker0];
                 b4 = base64Alphabet[marker1];
-                
                 decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
-                decodedData[encodedIndex + 1] =
-                    (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+                decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
                 decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
             } else if (marker0 == PAD) {
-                //Two PAD e.g. 3c[Pad][Pad]
+
+                // Two PAD e.g. 3c[Pad][Pad]
                 decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
             } else if (marker1 == PAD) {
-                //One PAD e.g. 3cQ[Pad]
+
+                // One PAD e.g. 3cQ[Pad]
                 b3 = base64Alphabet[marker0];
-                
                 decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
-                decodedData[encodedIndex + 1] =
-                    (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+                decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
             }
+
             encodedIndex += 3;
         }
+
         return decodedData;
     }
-    
+
     /**
      * Discards any whitespace from a base-64 encoded block.
      *
@@ -437,22 +437,23 @@
      * @return The data, less whitespace (see RFC 2045).
      */
     static byte[] discardWhitespace(byte[] data) {
-        byte groomedData[] = new byte[data.length];
+        byte[] groomedData = new byte[data.length];
         int bytesCopied = 0;
-        
+
         for (int i = 0; i < data.length; i++) {
             switch (data[i]) {
-            case (byte) ' ' :
-            case (byte) '\n' :
-            case (byte) '\r' :
-            case (byte) '\t' :
+                case (byte) ' ' :
+                case (byte) '\n' :
+                case (byte) '\r' :
+                case (byte) '\t' :
                     break;
-            default:
+
+                default :
                     groomedData[bytesCopied++] = data[i];
             }
         }
 
-        byte packedData[] = new byte[bytesCopied];
+        byte[] packedData = new byte[bytesCopied];
 
         System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
 
@@ -469,7 +470,7 @@
      * @return The data, less non-base64 characters (see RFC 2045).
      */
     static byte[] discardNonBase64(byte[] data) {
-        byte groomedData[] = new byte[data.length];
+        byte[] groomedData = new byte[data.length];
         int bytesCopied = 0;
 
         for (int i = 0; i < data.length; i++) {
@@ -478,14 +479,13 @@
             }
         }
 
-        byte packedData[] = new byte[bytesCopied];
+        byte[] packedData = new byte[bytesCopied];
 
         System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
 
         return packedData;
     }
 
-
     // Implementation of the Encoder Interface
 
     /**
@@ -495,7 +495,7 @@
      * supplied object is not of type byte[].
      *
      * @param pObject Object to encode
-     * @return An object (of type byte[]) containing the 
+     * @return An object (of type byte[]) containing the
      *         base64 encoded data which corresponds to the byte[] supplied.
      * @throws EncoderException if the parameter supplied is not
      *                          of type byte[]
@@ -504,6 +504,7 @@
         if (!(pObject instanceof byte[])) {
             throw new EncoderException(Messages.getMessage(Messages.NO_BYTE_ARRAY_ERROR));
         }
+
         return encode((byte[]) pObject);
     }
 
@@ -517,5 +518,4 @@
     public byte[] encode(byte[] pArray) {
         return encodeBase64(pArray, false);
     }
-
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/URLCodec.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/URLCodec.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/URLCodec.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,462 +1,316 @@
-/*
- * Copyright 2001-2004 The Apache Software Foundation.
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+/*
+ * Copyright 2001-2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 
-package org.ajax4jsf.util.base64;
 
-
 
-import java.io.ByteArrayOutputStream;
+package org.ajax4jsf.util.base64;
 
-import java.util.BitSet;
+import java.io.ByteArrayOutputStream;
 
-
+import java.util.BitSet;
 
-/**
+/**
+ *
+ * <p>Implements the 'www-form-urlencoded' encoding scheme,
+ *
+ * also misleadingly known as URL encoding.</p>
+ *
+ *
+ *
+ * <p>For more detailed information please refer to
+ *
+ * <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1">
+ *
+ * Chapter 17.13.4 'Form content types'</a> of the
+ *
+ * <a href="http://www.w3.org/TR/html4/">HTML 4.01 Specification<a></p>
+ *
+ *
+ *
+ * <p>
+ *
+ * This codec is meant to be a replacement for standard Java classes
+ *
+ * {@link java.net.URLEncoder} and {@link java.net.URLDecoder}
+ *
+ * on older Java platforms, as these classes in Java versions below
+ *
+ * 1.4 rely on the platform's default charset encoding.
+ *
+ * </p>
+ *
+ *
+ *
+ * @author Apache Software Foundation
+ *
+ * @since 1.2
+ *
+ * @version $Id: URLCodec.java,v 1.1.2.1 2007/01/09 18:59:14 alexsmirnov Exp $
+ *
+ */
+public class URLCodec implements BinaryEncoder, BinaryDecoder {
+    protected static final byte ESCAPE_CHAR = '%';
 
- * <p>Implements the 'www-form-urlencoded' encoding scheme, 
+    /**
+     *
+     * BitSet of www-form-url safe characters.
+     *
+     */
+    protected static final BitSet WWW_FORM_URL = new BitSet(256);
 
- * also misleadingly known as URL encoding.</p>
+    // Static initializer for www_form_url
+    static {
 
- *  
+        // alpha characters
+        for (int i = 'a'; i <= 'z'; i++) {
+            WWW_FORM_URL.set(i);
+        }
 
- * <p>For more detailed information please refer to 
+        for (int i = 'A'; i <= 'Z'; i++) {
+            WWW_FORM_URL.set(i);
+        }
 
- * <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1">
+        // numeric characters
+        for (int i = '0'; i <= '9'; i++) {
+            WWW_FORM_URL.set(i);
+        }
 
- * Chapter 17.13.4 'Form content types'</a> of the 
+        // special chars
+        WWW_FORM_URL.set('-');
+        WWW_FORM_URL.set('_');
+        WWW_FORM_URL.set('.');
+        WWW_FORM_URL.set('*');
 
- * <a href="http://www.w3.org/TR/html4/">HTML 4.01 Specification<a></p>
+        // blank to be replaced with +
+        WWW_FORM_URL.set(' ');
+    }
 
- * 
+    /**
+     *
+     * Default constructor.
+     *
+     */
+    public URLCodec() {
+        super();
+    }
 
- * <p> 
+    public static final byte[] encodeUrl(byte[] bytes) {
+        return encodeUrl(WWW_FORM_URL, bytes);
+    }
 
- * This codec is meant to be a replacement for standard Java classes
+    /**
+     *
+     * Encodes an array of bytes into an array of URL safe 7-bit
+     *
+     * characters. Unsafe characters are escaped.
+     *
+     *
+     *
+     * @param urlsafe bitset of characters deemed URL safe
+     *
+     * @param bytes array of bytes to convert to URL safe characters
+     *
+     * @return array of bytes containing URL safe characters
+     *
+     */
+    public static final byte[] encodeUrl(BitSet urlsafe, byte[] bytes) {
+        if (bytes == null) {
+            return null;
+        }
 
- * {@link java.net.URLEncoder} and {@link java.net.URLDecoder} 
+        if (urlsafe == null) {
+            urlsafe = WWW_FORM_URL;
+        }
 
- * on older Java platforms, as these classes in Java versions below 
+        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
 
- * 1.4 rely on the platform's default charset encoding.
+        for (int i = 0; i < bytes.length; i++) {
+            int b = bytes[i];
 
- * </p>
+            if (b < 0) {
+                b = 256 + b;
+            }
 
- * 
+            if (urlsafe.get(b)) {
+                if (b == ' ') {
+                    b = '+';
+                }
 
- * @author Apache Software Foundation
+                buffer.write(b);
+            } else {
+                buffer.write('%');
 
- * @since 1.2
+                char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
+                char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
 
- * @version $Id: URLCodec.java,v 1.1.2.1 2007/01/09 18:59:14 alexsmirnov Exp $
+                buffer.write(hex1);
+                buffer.write(hex2);
+            }
+        }
 
- */
+        return buffer.toByteArray();
+    }
 
-public class URLCodec implements BinaryEncoder, BinaryDecoder {
+    /**
+     *
+     * Decodes an array of URL safe 7-bit characters into an array of
+     *
+     * original bytes. Escaped characters are converted back to their
+     *
+     * original representation.
+     *
+     *
+     *
+     * @param bytes array of URL safe characters
+     *
+     * @return array of original bytes
+     *
+     * @throws DecoderException Thrown if URL decoding is unsuccessful
+     *
+     */
+    public static final byte[] decodeUrl(byte[] bytes) throws DecoderException {
+        if (bytes == null) {
+            return null;
+        }
 
-    
+        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
 
-    protected static byte ESCAPE_CHAR = '%';
+        for (int i = 0; i < bytes.length; i++) {
+            int b = bytes[i];
 
-    /**
+            if (b == '+') {
+                buffer.write(' ');
+            } else if (b == '%') {
+                try {
+                    int u = Character.digit((char) bytes[++i], 16);
+                    int l = Character.digit((char) bytes[++i], 16);
 
-     * BitSet of www-form-url safe characters.
+                    if ((u == -1) || (l == -1)) {
+                        throw new DecoderException("Invalid URL encoding");
+                    }
 
-     */
+                    buffer.write((char) ((u << 4) + l));
+                } catch (ArrayIndexOutOfBoundsException e) {
+                    throw new DecoderException("Invalid URL encoding");
+                }
+            } else {
+                buffer.write(b);
+            }
+        }
 
-    protected static final BitSet WWW_FORM_URL = new BitSet(256);
+        return buffer.toByteArray();
+    }
 
-    
+    /**
+     *
+     * Encodes an array of bytes into an array of URL safe 7-bit
+     *
+     * characters. Unsafe characters are escaped.
+     *
+     *
+     *
+     * @param bytes array of bytes to convert to URL safe characters
+     *
+     * @return array of bytes containing URL safe characters
+     *
+     */
+    public byte[] encode(byte[] bytes) {
+        return encodeUrl(WWW_FORM_URL, bytes);
+    }
 
-    // Static initializer for www_form_url
+    /**
+     *
+     * Decodes an array of URL safe 7-bit characters into an array of
+     *
+     * original bytes. Escaped characters are converted back to their
+     *
+     * original representation.
+     *
+     *
+     *
+     * @param bytes array of URL safe characters
+     *
+     * @return array of original bytes
+     *
+     * @throws DecoderException Thrown if URL decoding is unsuccessful
+     *
+     */
+    public byte[] decode(byte[] bytes) throws DecoderException {
+        return decodeUrl(bytes);
+    }
 
-    static {
+    /**
+     *
+     * Encodes an object into its URL safe form. Unsafe characters are
+     *
+     * escaped.
+     *
+     *
+     *
+     * @param pObject string to convert to a URL safe form
+     *
+     * @return URL safe object
+     *
+     * @throws EncoderException Thrown if URL encoding is not
+     *
+     *                          applicable to objects of this type or
+     *
+     *                          if encoding is unsuccessful
+     *
+     */
+    public Object encode(Object pObject) throws EncoderException {
+        if (pObject == null) {
+            return null;
+        } else if (pObject instanceof byte[]) {
+            return encode((byte[]) pObject);
+        } else if (pObject instanceof String) {
+            return encode((String) pObject);
+        } else {
+            throw new EncoderException("Objects of type " + pObject.getClass().getName() + " cannot be URL encoded");
+        }
+    }
 
-        // alpha characters
-
-        for (int i = 'a'; i <= 'z'; i++) {
-
-            WWW_FORM_URL.set(i);
-
-        }
-
-        for (int i = 'A'; i <= 'Z'; i++) {
-
-            WWW_FORM_URL.set(i);
-
-        }
-
-        // numeric characters
-
-        for (int i = '0'; i <= '9'; i++) {
-
-            WWW_FORM_URL.set(i);
-
-        }
-
-        // special chars
-
-        WWW_FORM_URL.set('-');
-
-        WWW_FORM_URL.set('_');
-
-        WWW_FORM_URL.set('.');
-
-        WWW_FORM_URL.set('*');
-
-        // blank to be replaced with +
-
-        WWW_FORM_URL.set(' ');
-
-    }
-
-
-
-
-
-    /**
-
-     * Default constructor.
-
-     */
-
-    public URLCodec() {
-
-        super();
-
-    }
-
-
-
-    public static final byte[] encodeUrl( byte[] bytes) 
-
-    {
-
-    	return encodeUrl(WWW_FORM_URL, bytes);
-
-    }
-
-    /**
-
-     * Encodes an array of bytes into an array of URL safe 7-bit 
-
-     * characters. Unsafe characters are escaped.
-
-     *
-
-     * @param urlsafe bitset of characters deemed URL safe
-
-     * @param bytes array of bytes to convert to URL safe characters
-
-     * @return array of bytes containing URL safe characters
-
-     */
-
-    public static final byte[] encodeUrl(BitSet urlsafe, byte[] bytes) 
-
-    {
-
-        if (bytes == null) {
-
-            return null;
-
-        }
-
-        if (urlsafe == null) {
-
-            urlsafe = WWW_FORM_URL;
-
-        }
-
-        
-
-        ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
-
-        for (int i = 0; i < bytes.length; i++) {
-
-            int b = bytes[i];
-
-            if (b < 0) {
-
-                b = 256 + b;
-
-            }
-
-            if (urlsafe.get(b)) {
-
-                if (b == ' ') {
-
-                    b = '+';
-
-                }
-
-                buffer.write(b);
-
-            } else {
-
-                buffer.write('%');
-
-                char hex1 = Character.toUpperCase(
-
-                  Character.forDigit((b >> 4) & 0xF, 16));
-
-                char hex2 = Character.toUpperCase(
-
-                  Character.forDigit(b & 0xF, 16));
-
-                buffer.write(hex1);
-
-                buffer.write(hex2);
-
-            }
-
-        }
-
-        return buffer.toByteArray(); 
-
-    }
-
-
-
-
-
-    /**
-
-     * Decodes an array of URL safe 7-bit characters into an array of 
-
-     * original bytes. Escaped characters are converted back to their 
-
-     * original representation.
-
-     *
-
-     * @param bytes array of URL safe characters
-
-     * @return array of original bytes 
-
-     * @throws DecoderException Thrown if URL decoding is unsuccessful
-
-     */
-
-    public static final byte[] decodeUrl(byte[] bytes) 
-
-         throws DecoderException
-
-    {
-
-        if (bytes == null) {
-
-            return null;
-
-        }
-
-        ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
-
-        for (int i = 0; i < bytes.length; i++) {
-
-            int b = bytes[i];
-
-            if (b == '+') {
-
-                buffer.write(' ');
-
-            } else if (b == '%') {
-
-                try {
-
-                    int u = Character.digit((char)bytes[++i], 16);
-
-                    int l = Character.digit((char)bytes[++i], 16);
-
-                    if (u == -1 || l == -1) {
-
-                        throw new DecoderException("Invalid URL encoding");
-
-                    }
-
-                    buffer.write((char)((u << 4) + l));
-
-                } catch(ArrayIndexOutOfBoundsException e) {
-
-                    throw new DecoderException("Invalid URL encoding");
-
-                }
-
-            } else {
-
-                buffer.write(b);
-
-            }
-
-        }
-
-        return buffer.toByteArray(); 
-
-    }
-
-
-
-
-
-    /**
-
-     * Encodes an array of bytes into an array of URL safe 7-bit 
-
-     * characters. Unsafe characters are escaped.
-
-     *
-
-     * @param bytes array of bytes to convert to URL safe characters
-
-     * @return array of bytes containing URL safe characters
-
-     */
-
-    public byte[] encode(byte[] bytes) {
-
-        return encodeUrl(WWW_FORM_URL, bytes);
-
-    }
-
-
-
-
-
-    /**
-
-     * Decodes an array of URL safe 7-bit characters into an array of 
-
-     * original bytes. Escaped characters are converted back to their 
-
-     * original representation.
-
-     *
-
-     * @param bytes array of URL safe characters
-
-     * @return array of original bytes 
-
-     * @throws DecoderException Thrown if URL decoding is unsuccessful
-
-     */
-
-    public byte[] decode(byte[] bytes) throws DecoderException {
-
-        return decodeUrl(bytes);
-
-    }
-
-
-
-
-
-    /**
-
-     * Encodes an object into its URL safe form. Unsafe characters are 
-
-     * escaped.
-
-     *
-
-     * @param pObject string to convert to a URL safe form
-
-     * @return URL safe object
-
-     * @throws EncoderException Thrown if URL encoding is not 
-
-     *                          applicable to objects of this type or
-
-     *                          if encoding is unsuccessful
-
-     */
-
-    public Object encode(Object pObject) throws EncoderException {
-
-        if (pObject == null) {
-
-            return null;
-
-        } else if (pObject instanceof byte[]) {
-
-            return encode((byte[])pObject);
-
-        } else if (pObject instanceof String) {
-
-            return encode((String)pObject);
-
-        } else {
-
-            throw new EncoderException("Objects of type " +
-
-                pObject.getClass().getName() + " cannot be URL encoded"); 
-
-              
-
-        }
-
-    }
-
-
-
-    /**
-
-     * Decodes a URL safe object into its original form. Escaped 
-
-     * characters are converted back to their original representation.
-
-     *
-
-     * @param pObject URL safe object to convert into its original form
-
-     * @return original object 
-
-     * @throws DecoderException Thrown if URL decoding is not 
-
-     *                          applicable to objects of this type
-
-     *                          if decoding is unsuccessful
-
-     */
-
-    public Object decode(Object pObject) throws DecoderException {
-
-        if (pObject == null) {
-
-            return null;
-
-        } else if (pObject instanceof byte[]) {
-
-            return decode((byte[])pObject);
-
-        } else if (pObject instanceof String) {
-
-            return decode((String)pObject);
-
-        } else {
-
-            throw new DecoderException("Objects of type " +
-
-                pObject.getClass().getName() + " cannot be URL decoded"); 
-
-              
-
-        }
-
-    }
-
-
-
-}
-
+    /**
+     *
+     * Decodes a URL safe object into its original form. Escaped
+     *
+     * characters are converted back to their original representation.
+     *
+     *
+     *
+     * @param pObject URL safe object to convert into its original form
+     *
+     * @return original object
+     *
+     * @throws DecoderException Thrown if URL decoding is not
+     *
+     *                          applicable to objects of this type
+     *
+     *                          if decoding is unsuccessful
+     *
+     */
+    public Object decode(Object pObject) throws DecoderException {
+        if (pObject == null) {
+            return null;
+        } else if (pObject instanceof byte[]) {
+            return decode((byte[]) pObject);
+        } else if (pObject instanceof String) {
+            return decode((String) pObject);
+        } else {
+            throw new DecoderException("Objects of type " + pObject.getClass().getName() + " cannot be URL decoded");
+        }
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/base64/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Framework utility classes to handle BASE64 encoding
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Framework utility classes
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/CSSFormat.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/CSSFormat.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/CSSFormat.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,116 +19,133 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util.style;
 
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
+
 /**
  * Simple utility class for CSS style formatting
  * Current version isn't thread-safe and doesn't provide any validation
- * 
+ *
  * Usage is simle
  * <code>
- * 	CSSFormat format = new CSSFormat();
- * 	format.add("background-position", "top left");
- * 	format.addURL("background-image", "/images/corner.gif");
- * 	responseWriter.writeAttribute("style", format, null);
+ *  CSSFormat format = new CSSFormat();
+ *  format.add("background-position", "top left");
+ *  format.addURL("background-image", "/images/corner.gif");
+ *  responseWriter.writeAttribute("style", format, null);
  * </code>
- * 
+ *
  * @author Maksim Kaszynski
  *
  */
 public class CSSFormat {
+    private Map properties;
 
-	
-	/**
-	 * Surrounds given URL with <code>url()</code>
-	 * @param url
-	 * @return
-	 */
-	public static String url(String url){
-		StringBuffer buf = new StringBuffer(url.length() + 7);
-		//escape url according to http://www.w3.org/TR/REC-CSS1#url
-		buf.append("url(").append(url.replaceAll("([\\)\\(\\s,\'\"])", "\\\\$1")).append(")");
-		return buf.toString();
-	}
-	/**
-	 * Formats property-value pair in CSS fashion
-	 * @param property
-	 * @param value
-	 * @return
-	 */
-	public static String propertyValue(String property, String value){
-		return formatPropertyValue(property, value);
-	}
-	
-	private static String formatPropertyValue(Object property, Object value){
-		StringBuffer buf = new StringBuffer();
-		buf.append(property).append(": ").append(value).append(";");
-		return buf.toString();
-	}
-	
-	private Map properties;
-	/**
-	 * Constructs an empty CSSFormat object
-	 */
-	public CSSFormat() {
-		properties = new HashMap();
-	}
-	/**
-	 * Constructs CSSFormat object 
-	 * and fills it with given parameters
-	 * @param property
-	 * @param value
-	 */
-	public CSSFormat(String property, String value){
-		properties = new HashMap(3);
-		add(property, value);
-		
-	}
-	/**
-	 * Adds property. If such property already exists, 
-	 * its value is replaced with new one
-	 * @param property
-	 * @param value
-	 * @return itself
-	 */
-	public CSSFormat add(String property, String value){
-		properties.put(property, value);
-		return this;
-	}
-	/**
-	 * adds a property with URL value
-	 * given value is wrapped in <code>url()</code> clause
-	 * @param property
-	 * @param url
-	 * @return itself
-	 */
-	public CSSFormat addURL(String property, String url){
-		properties.put(property, url(url));
-		return this;
-	}
-	/**
-	 * Concatenates all properties with their values to produce single-line CSS output 
-	 */
-	public String toString() {
-		return concatenate(null);
-	}
-	/**
-	 * Concatenates all properties with their values to produce CSS output
-	 * @param separator - custom string to be inserted between properties
-	 * @return
-	 */
-	public String concatenate(String separator){
-		StringBuffer output = new StringBuffer();
-		for(Iterator iter = properties.entrySet().iterator(); iter.hasNext();){
-			Map.Entry entry = (Map.Entry) iter.next();
-			output.append(formatPropertyValue(entry.getKey(), entry.getValue()));
-			if(separator != null && iter.hasNext()){
-				output.append(separator);
-			}
-		}
-		return output.toString();
-	}
+    /**
+     * Constructs an empty CSSFormat object
+     */
+    public CSSFormat() {
+        properties = new HashMap();
+    }
+
+    /**
+     * Constructs CSSFormat object
+     * and fills it with given parameters
+     * @param property
+     * @param value
+     */
+    public CSSFormat(String property, String value) {
+        properties = new HashMap(3);
+        add(property, value);
+    }
+
+    /**
+     * Surrounds given URL with <code>url()</code>
+     * @param url
+     * @return
+     */
+    public static String url(String url) {
+        StringBuffer buf = new StringBuffer(url.length() + 7);
+
+        // escape url according to http://www.w3.org/TR/REC-CSS1#url
+        buf.append("url(").append(url.replaceAll("([\\)\\(\\s,\'\"])", "\\\\$1")).append(")");
+
+        return buf.toString();
+    }
+
+    /**
+     * Formats property-value pair in CSS fashion
+     * @param property
+     * @param value
+     * @return
+     */
+    public static String propertyValue(String property, String value) {
+        return formatPropertyValue(property, value);
+    }
+
+    private static String formatPropertyValue(Object property, Object value) {
+        StringBuffer buf = new StringBuffer();
+
+        buf.append(property).append(": ").append(value).append(";");
+
+        return buf.toString();
+    }
+
+    /**
+     * Adds property. If such property already exists,
+     * its value is replaced with new one
+     * @param property
+     * @param value
+     * @return itself
+     */
+    public CSSFormat add(String property, String value) {
+        properties.put(property, value);
+
+        return this;
+    }
+
+    /**
+     * adds a property with URL value
+     * given value is wrapped in <code>url()</code> clause
+     * @param property
+     * @param url
+     * @return itself
+     */
+    public CSSFormat addURL(String property, String url) {
+        properties.put(property, url(url));
+
+        return this;
+    }
+
+    /**
+     * Concatenates all properties with their values to produce single-line CSS output
+     */
+    public String toString() {
+        return concatenate(null);
+    }
+
+    /**
+     * Concatenates all properties with their values to produce CSS output
+     * @param separator - custom string to be inserted between properties
+     * @return
+     */
+    public String concatenate(String separator) {
+        StringBuffer output = new StringBuffer();
+
+        for (Iterator iter = properties.entrySet().iterator(); iter.hasNext(); ) {
+            Map.Entry entry = (Map.Entry) iter.next();
+
+            output.append(formatPropertyValue(entry.getKey(), entry.getValue()));
+
+            if ((separator != null) && iter.hasNext()) {
+                output.append(separator);
+            }
+        }
+
+        return output.toString();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/CSSSelector.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/CSSSelector.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/CSSSelector.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util.style;
 
 /**
@@ -26,25 +28,30 @@
  *
  */
 public class CSSSelector {
-	private StringBuffer selectorBuffer;
-	public CSSSelector() {
-		selectorBuffer = new StringBuffer();
-	}
-	public CSSSelector(String selector){
-		this();
-		selectorBuffer.append(selector);
-	}
-	
-	public CSSSelector addSelector(String selector){
-		if(selector != null){
-			if(selectorBuffer.length() > 0){
-				selectorBuffer.append(' ');
-			}
-			selectorBuffer.append(selector);
-		}
-		return this;
-	}
-	public String toString() {
-		return selectorBuffer.toString();
-	}
+    private StringBuffer selectorBuffer;
+
+    public CSSSelector() {
+        selectorBuffer = new StringBuffer();
+    }
+
+    public CSSSelector(String selector) {
+        this();
+        selectorBuffer.append(selector);
+    }
+
+    public CSSSelector addSelector(String selector) {
+        if (selector != null) {
+            if (selectorBuffer.length() > 0) {
+                selectorBuffer.append(' ');
+            }
+
+            selectorBuffer.append(selector);
+        }
+
+        return this;
+    }
+
+    public String toString() {
+        return selectorBuffer.toString();
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/FontFamily.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/FontFamily.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/FontFamily.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,10 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.util.style;
 
 import java.awt.Font;
 import java.awt.GraphicsEnvironment;
+
 import java.util.Arrays;
 import java.util.StringTokenizer;
 
@@ -30,40 +33,50 @@
  * @author Maksim Kaszynski
  *
  */
-public class FontFamily {
-	public static final String CSS_SANS_SERIF = "SANS-SERIF";
-	public static final String JAVA_SANS_SERIF = "SANSSERIF";
-	public static final String CSS_MONOSPACED = "MONOSPACE";
-	public static final String JAVA_MONOSPACED = "MONOSPACED";
-	
-	private static final String[] fontFamilies = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
-	static{
-		for (int i = 0; i < fontFamilies.length; i++) {
-			fontFamilies[i] = fontFamilies[i].toUpperCase();
-			//System.out.println(fontFamilies[i]);
-		}
-		Arrays.sort(fontFamilies);
-	}
-	
-	public static Font getFont(String fontFamily, int style, int size){
-		String fontUsed = null;
-		StringTokenizer tokenizer = new StringTokenizer(fontFamily, ",");
-		while(tokenizer.hasMoreElements()){
-			String fontName = tokenizer.nextToken().trim().toUpperCase();
-			if(fontName.equals(CSS_SANS_SERIF)){
-				fontName = JAVA_SANS_SERIF;
-			} else if(fontName.equals(CSS_MONOSPACED)){
-				fontName = JAVA_MONOSPACED;
-			}
-			
-			if(Arrays.binarySearch(fontFamilies, fontName) >= 0){
-				fontUsed = fontName;
-			}
-		}
-		if(fontUsed == null){
-			fontUsed = JAVA_SANS_SERIF;
-		}
-		Font f = new Font(fontUsed, style, size);
-		return f;
-	}
+public final class FontFamily {
+    public static final String CSS_MONOSPACED = "MONOSPACE";
+    public static final String CSS_SANS_SERIF = "SANS-SERIF";
+    public static final String JAVA_MONOSPACED = "MONOSPACED";
+    public static final String JAVA_SANS_SERIF = "SANSSERIF";
+    private static final String[] FONT_FAMILIES =
+        GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
+
+    static {
+        for (int i = 0; i < FONT_FAMILIES.length; i++) {
+            FONT_FAMILIES[i] = FONT_FAMILIES[i].toUpperCase();
+
+            // System.out.println(fontFamilies[i]);
+        }
+
+        Arrays.sort(FONT_FAMILIES);
+    }
+
+    private FontFamily() {}
+
+    public static Font getFont(String fontFamily, int style, int size) {
+        String fontUsed = null;
+        StringTokenizer tokenizer = new StringTokenizer(fontFamily, ",");
+
+        while (tokenizer.hasMoreElements()) {
+            String fontName = tokenizer.nextToken().trim().toUpperCase();
+
+            if (fontName.equals(CSS_SANS_SERIF)) {
+                fontName = JAVA_SANS_SERIF;
+            } else if (fontName.equals(CSS_MONOSPACED)) {
+                fontName = JAVA_MONOSPACED;
+            }
+
+            if (Arrays.binarySearch(FONT_FAMILIES, fontName) >= 0) {
+                fontUsed = fontName;
+            }
+        }
+
+        if (fontUsed == null) {
+            fontUsed = JAVA_SANS_SERIF;
+        }
+
+        Font f = new Font(fontUsed, style, size);
+
+        return f;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/util/style/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * CSS utility classes
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/BaseFilter.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/BaseFilter.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/BaseFilter.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,12 +19,27 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.context.AjaxContext;
+import org.ajax4jsf.renderkit.AjaxContainerRenderer;
+import org.ajax4jsf.request.MultipartRequest;
+import org.ajax4jsf.resource.InternetResourceService;
+
+import org.richfaces.component.FileUploadConstants;
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.UnsupportedEncodingException;
+
 import java.net.URLDecoder;
+
 import java.util.Collections;
 import java.util.Date;
 import java.util.Enumeration;
@@ -33,6 +48,7 @@
 import java.util.regex.Pattern;
 
 import javax.faces.application.ViewHandler;
+
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
 import javax.servlet.FilterConfig;
@@ -45,582 +61,591 @@
 import javax.servlet.http.HttpServletResponseWrapper;
 import javax.servlet.http.HttpSession;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.context.AjaxContext;
-import org.ajax4jsf.renderkit.AjaxContainerRenderer;
-import org.ajax4jsf.request.MultipartRequest;
-import org.ajax4jsf.resource.InternetResourceService;
-import org.richfaces.component.FileUploadConstants;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
 /**
  * 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 {
+    public static final String ABSOLUTE_TAGS_PARAMETER = "absolute-attributes";
+    public static final String AJAX_PUSH_KEY_HEADER = "Ajax-Push-Key";
+    public static final String AJAX_PUSH_READY = "READY";
+    public static final String AJAX_PUSH_STATUS_HEADER = "Ajax-Push-Status";
+    public static final String CACHEABLE_PREFIX = "/cache";
+    public static final String DATA_PARAMETER = "DATA";
+    public static final String DEFAULT_SERVLET_PATH = "/resource";
 
-	public static final String AJAX_PUSH_READY = "READY";
+    // 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 AJAX_PUSH_STATUS_HEADER = "Ajax-Push-Status";
+    /** Multipart request start */
+    public static final String MULTIPART = "multipart/";
 
-	public static final String AJAX_PUSH_KEY_HEADER = "Ajax-Push-Key";
+    // private WebXml webXml;
+    // private String xsl;
+    // private Templates xslTemplates;
 
-	private static final Logger log = RichfacesLogger.WEBAPP.getLogger();
+    public static final String RENDERER_PREFIX = "/renderer";
+    public static final String RESPONSE_WRAPPER_ATTRIBUTE = "com.exade.vcp.Filter.ResponseWrapper";
+    public static final String REWRITEID_PARAMETER = "rewriteid";
 
-	public static final boolean DEBUG = true;
+    /**
+     * Request parameter that allow to send HTTP error instead of html message
+     */
+    public static final String SEND_HTTP_ERROR = "_richfaces_send_http_error";
+    public static final String STYLESHEET_PARAMETER = "xsl";
+    public static final boolean DEBUG = true;
+    
+    private static final String FUNCTION_NAME_PARAMETER = "function";
+    private static final String MYFACES_DOFILTER_CALLED =
+        "org.apache.myfaces.component.html.util.ExtensionFilter.doFilterCalled";
 
-	private FilterConfig filterConfig;
+    private static final Logger LOG = RichfacesLogger.WEBAPP.getLogger();
+    private static final long serialVersionUID = -2295534611886142935L;
+    private static final String MYFACES_FILTER_CHECKED = BaseFilter.class.getName() + ":MyFacesFilterChecked";
+    private static final Pattern AMPERSAND = Pattern.compile("&+");
 
-	private static final String FUNCTION_NAME_PARAMETER = "function";
+    protected InternetResourceService resourceService = null;
+    protected BaseXMLFilter xmlFilter = null;
+    protected PollEventsManager eventsManager;
 
-	private String function = "alert('Data received');JSHttpRequest.dataReady";
+    private String function = "alert('Data received');JSHttpRequest.dataReady";
 
-	private String attributesNames;
+    /**
+     * The maximum size of a file upload request. 0 means no limit.
+     */
+    private int maxRequestSize = 0;
+    private boolean rewriteid = false;
+    private boolean myfacesMessagePrinted = false;
 
-	private boolean rewriteid = false;
+    /**
+     * Flag indicating whether a temporary file should be used to cache the
+     * uploaded file
+     */
+    private boolean createTempFiles = false;
+    private String attributesNames;
+    private FilterConfig filterConfig;
 
-	public static final String REWRITEID_PARAMETER = "rewriteid";
+    /**
+     * Initialize the filter.
+     */
+    public void init(FilterConfig config) throws ServletException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Init ajax4jsf filter with nane: " + config.getFilterName());
 
-	public static final String STYLESHEET_PARAMETER = "xsl";
+            Enumeration<String> parameterNames = config.getInitParameterNames();
+            StringBuffer parameters = new StringBuffer("Init parameters :\n");
 
-	public static final String ABSOLUTE_TAGS_PARAMETER = "absolute-attributes";
+            while (parameterNames.hasMoreElements()) {
+                String name = parameterNames.nextElement();
 
-	// private WebXml webXml;
-	// private String xsl;
-	// private Templates xslTemplates;
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -2295534611886142935L;
+                parameters.append(name).append(" : '").append(config.getInitParameter(name)).append('\n');
+            }
 
-	public static final String DATA_PARAMETER = "DATA";
+            LOG.debug(parameters.toString());
 
-	public static final String DEFAULT_SERVLET_PATH = "/resource";
+            // log.debug("Stack Trace", new Exception());
+        }
 
-	public static final String RENDERER_PREFIX = "/renderer";
+        // Save config
+        filterConfig = config;
+        setFunction((String) nz(filterConfig.getInitParameter(FUNCTION_NAME_PARAMETER), getFunction()));
+        setAttributesNames(filterConfig.getInitParameter(ABSOLUTE_TAGS_PARAMETER));
+        xmlFilter.init(config);
 
-	public static final String CACHEABLE_PREFIX = "/cache";
+        if ("true".equalsIgnoreCase(filterConfig.getInitParameter(REWRITEID_PARAMETER))) {
+            this.setRewriteid(true);
+        }
 
-	// 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";
+        resourceService = new InternetResourceService();
 
-	public static final String RESPONSE_WRAPPER_ATTRIBUTE = "com.exade.vcp.Filter.ResponseWrapper";
+        // Caching initialization.
+        resourceService.init(filterConfig);
+        eventsManager = new PollEventsManager();
+        eventsManager.init(filterConfig.getServletContext());
 
-	protected BaseXMLFilter xmlFilter = null;
+        String param = filterConfig.getInitParameter("createTempFiles");
 
-	protected InternetResourceService resourceService = null;
+        if (param != null) {
+            this.createTempFiles = Boolean.parseBoolean(param);
+        } else {
+            this.createTempFiles = true;
+        }
 
-	protected PollEventsManager eventsManager;
+        param = filterConfig.getInitParameter("maxRequestSize");
 
-	/**
-	 * Flag indicating whether a temporary file should be used to cache the
-	 * uploaded file
-	 */
-	private boolean createTempFiles = false;
+        if (param != null) {
+            this.maxRequestSize = Integer.parseInt(param);
+        }
+    }
 
-	/**
-	 * The maximum size of a file upload request. 0 means no limit.
-	 */
-	private int maxRequestSize = 0;
-	
-	/** Multipart request start */
-	public static final String MULTIPART = "multipart/";
+    private Map<String, String> parseQueryString(String queryString) {
+        if (queryString != null) {
+            Map<String, String> parameters = new HashMap<String, String>();
+            String[] nvPairs = AMPERSAND.split(queryString);
 
-	/**
-	 * Request parameter that allow to send HTTP error instead of html message
-	 */
-	public static final String SEND_HTTP_ERROR = "_richfaces_send_http_error";
-	
-	/**
-	 * Initialize the filter.
-	 */
-	public void init(FilterConfig config) throws ServletException {
-		if (log.isDebugEnabled()) {
-			log.debug("Init ajax4jsf filter with nane: "
-					+ config.getFilterName());
-			Enumeration<String> parameterNames = config.getInitParameterNames();
-			StringBuffer parameters = new StringBuffer("Init parameters :\n");
-			while (parameterNames.hasMoreElements()) {
-				String name = parameterNames.nextElement();
-				parameters.append(name).append(" : '").append(
-						config.getInitParameter(name)).append('\n');
-			}
-			log.debug(parameters.toString());
-			// 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);
-		}
-		resourceService = new InternetResourceService();
-		// Caching initialization.
-		resourceService.init(filterConfig);
-		eventsManager = new PollEventsManager();
-		eventsManager.init(filterConfig.getServletContext());
+            for (String nvPair : nvPairs) {
+                if (nvPair.length() == 0) {
+                    continue;
+                }
 
-		String param = filterConfig.getInitParameter("createTempFiles");
-		if (param != null) {
-			this.createTempFiles = Boolean.parseBoolean(param);
-		} else {
-			this.createTempFiles = true;
-		}
-		param = filterConfig.getInitParameter("maxRequestSize");
-		if (param != null) {
-			this.maxRequestSize = Integer.parseInt(param);
-		}
-	}
+                int eqIdx = nvPair.indexOf('=');
 
-	private static final Pattern AMPERSAND = Pattern.compile("&+");
+                if (eqIdx >= 0) {
+                    try {
+                        String name = URLDecoder.decode(nvPair.substring(0, eqIdx), "UTF-8");
 
-	private Map<String, String> parseQueryString(String queryString) {
-		if (queryString != null) {
-			Map<String, String> parameters = new HashMap<String, String>();
+                        if (!parameters.containsKey(name)) {
+                            String value = URLDecoder.decode(nvPair.substring(eqIdx + 1), "UTF-8");
 
-			String[] nvPairs = AMPERSAND.split(queryString);
-			for (String nvPair : nvPairs) {
-				if (nvPair.length() == 0) {
-					continue;
-				}
+                            parameters.put(name, value);
+                        }
+                    } catch (UnsupportedEncodingException e) {
 
-				int eqIdx = nvPair.indexOf('=');
-				if (eqIdx >= 0) {
-					try {
-						String name = URLDecoder.decode(nvPair.substring(0, eqIdx), "UTF-8");
-						if (!parameters.containsKey(name)) {
-							String value = URLDecoder.decode(nvPair.substring(eqIdx + 1), "UTF-8");
+                        // log warning and skip this parameter
+                        LOG.warn(e.getLocalizedMessage(), e);
+                    }
+                }
+            }
 
-							parameters.put(name, value);
-						}
-					} catch (UnsupportedEncodingException e) {
-						//log warning and skip this parameter
-						log.warn(e.getLocalizedMessage(), e);
-					}
-				}
-			}
+            return parameters;
+        } else {
+            return Collections.EMPTY_MAP;
+        }
+    }
 
-			return parameters;
-		} else {
+    private boolean isMultipartRequest(HttpServletRequest request) {
+        if (!"post".equals(request.getMethod().toLowerCase())) {
+            return false;
+        }
 
-			return Collections.EMPTY_MAP;
-		}
-	}
-	
-	private boolean isMultipartRequest(HttpServletRequest request) {
-		if (!"post".equals(request.getMethod().toLowerCase())) {
-			return false;
-		}
+        String contentType = request.getContentType();
 
-		String contentType = request.getContentType();
-		if (contentType == null) {
-			return false;
-		}
+        if (contentType == null) {
+            return false;
+        }
 
-		if (contentType.toLowerCase().startsWith(MULTIPART)) {
-			return true;
-		}
+        if (contentType.toLowerCase().startsWith(MULTIPART)) {
+            return true;
+        }
 
-		return false;
-	}
+        return false;
+    }
 
-	private boolean isFileSizeRestricted(ServletRequest request, int maxSize) {
-		if (maxSize != 0 && request.getContentLength() > maxSize) {
-			return true;
-		}
-		return false;
-	}
+    private boolean isFileSizeRestricted(ServletRequest request, int maxSize) {
+        if ((maxSize != 0) && (request.getContentLength() > maxSize)) {
+            return true;
+        }
 
-	private boolean checkFileCount(HttpServletRequest request, String idParameter) {
-		HttpSession session = request.getSession(false);
-		
-		if (session != null) {
-			Map<String, Integer> map = (Map<String, Integer>) session.getAttribute(FileUploadConstants.UPLOADED_COUNTER);
+        return false;
+    }
 
-			if (map != null) {
-				String id = idParameter;
-				if (id != null) {
-					Integer i = map.get(id);
-					if (i != null && i == 0) {
-						return false;
-					}
-				}
-			}
-		}
+    private boolean checkFileCount(HttpServletRequest request, String idParameter) {
+        HttpSession session = request.getSession(false);
 
-		return true;
-	}
+        if (session != null) {
+            Map<String, Integer> map = (Map<String,
+                                            Integer>) session.getAttribute(FileUploadConstants.UPLOADED_COUNTER);
 
-	private void printResponse(ServletResponse response, String message)
-			throws IOException {
-		HttpServletResponse httpResponse = (HttpServletResponse) response;
-		httpResponse.setStatus(HttpServletResponse.SC_OK);
-		httpResponse.setContentType("text/html");
-		PrintWriter writer = httpResponse.getWriter();
-		writer.write(message);
-		writer.close();
-	}
+            if (map != null) {
+                String id = idParameter;
 
-	protected void handleRequest(HttpServletRequest request, HttpServletResponse response,
-		FilterChain chain) throws IOException, ServletException {
+                if (id != null) {
+                    Integer i = map.get(id);
 
-		// check ajax request parameter
-		// TODO - check for JSF page.
-		if (true) {
-			if (log.isDebugEnabled()) {
-				log.debug(Messages
-						.getMessage(Messages.FILTER_XML_OUTPUT));
-			}
+                    if ((i != null) && (i == 0)) {
+                        return false;
+                    }
+                }
+            }
+        }
 
-			// Execute the rest of the filter chain, including the
-			// JSP
-			xmlFilter.doXmlFilter(chain, request,
-					response);
-		} else {
-			// normal request, execute chain ...
-			if (log.isDebugEnabled()) {
-				log.debug(Messages
-						.getMessage(Messages.FILTER_NO_XML_CHAIN));
-			}
-			chain.doFilter(request, response);
+        return true;
+    }
 
-		}
-	
-	}
-	
-	private static final String MYFACES_FILTER_CHECKED = BaseFilter.class.getName() + ":MyFacesFilterChecked";
-    
-	private static final String MYFACES_DOFILTER_CALLED = "org.apache.myfaces.component.html.util.ExtensionFilter.doFilterCalled"; 
-    
-	private boolean myfacesMessagePrinted = false;
-	
-	private void checkMyFacesExtensionsFilter(HttpServletRequest request) {
-		if (request.getAttribute(MYFACES_FILTER_CHECKED) == null) {
-			if (request.getAttribute(MYFACES_DOFILTER_CALLED) != null) {
-				if (!this.myfacesMessagePrinted) {
-					log.warn("MyFaces Extensions Filter should be configured to execute *AFTER* RichFaces filter. Refer to SRV.6.2.4 section of Servlets specification on how to achieve that.");
-					
-					this.myfacesMessagePrinted = true;
-				}
-			}
-			
-			request.setAttribute(MYFACES_FILTER_CHECKED, Boolean.TRUE);
-		}
-	}
-	
-	/**
-	 * Method catches upload files request. Request parameter
-	 * <b>org.ajax4jsf.Filter.UPLOAD_FILES_ID</b> indicates if request
-	 * generated by rich-upload component. If it was detected custom parsing
-	 * request should be done. Processing information about percent of
-	 * completion and file size will be put into session scope. 
-	 * 
-	 * @param request
-	 * @param response
-	 * @return 
-	 * @throws IOException 
-	 * @throws ServletException 
-	 */
-	protected void processUploadsAndHandleRequest(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
-		HttpServletRequest httpRequest = (HttpServletRequest) request;
-		
-		Map<String, String> queryParamMap = parseQueryString(httpRequest.getQueryString());
-		String uid = queryParamMap.get(FileUploadConstants.UPLOAD_FILES_ID);
+    private void printResponse(ServletResponse response, String message) throws IOException {
+        HttpServletResponse httpResponse = (HttpServletResponse) response;
 
-		if (uid != null) {
+        httpResponse.setStatus(HttpServletResponse.SC_OK);
+        httpResponse.setContentType("text/html");
 
-			if (isMultipartRequest(httpRequest)) {
-				MultipartRequest multipartRequest = new MultipartRequest(httpRequest, createTempFiles, maxRequestSize, uid);
+        PrintWriter writer = httpResponse.getWriter();
 
-				Object oldAttributeValue = httpRequest.getAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME);
-				httpRequest.setAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME, multipartRequest);
-				
-				try {
-					if (isFileSizeRestricted(request, maxRequestSize)) {
+        writer.write(message);
+        writer.close();
+    }
 
-						boolean sendError = Boolean.parseBoolean(queryParamMap.get(SEND_HTTP_ERROR));
-						if (sendError) {
-							response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
-							System.err.println("ERROR " + HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE + "request entity is larger than the server is willing or able to process.");
-							return;
-						} else {
-							printResponse(response, "<html id=\"_richfaces_file_upload_size_restricted\"></html>");
-						}
+    protected void handleRequest(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
+        throws IOException, ServletException {
 
-					} else if (!checkFileCount(httpRequest, queryParamMap.get("id"))) {
-						printResponse(response, "<html id=\"_richfaces_file_upload_forbidden\"></html>");
-					} else {
+        // check ajax request parameter
+        // TODO - check for JSF page.
+        if (true) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.FILTER_XML_OUTPUT));
+            }
 
-						handleRequest(multipartRequest,	multipartRequest.isFormUpload() ? response : 
-							new HttpServletResponseWrapper((HttpServletResponse) response){
-							@Override
-							public void setContentType(String type) {
-								super.setContentType(BaseXMLFilter.TEXT_HTML + ";charset=UTF-8");
-							}
-						}, chain);
+            // Execute the rest of the filter chain, including the
+            // JSP
+            xmlFilter.doXmlFilter(chain, request, response);
+        } else {
 
-						if (!multipartRequest.isDone()) {
-							printResponse(response, "<html id=\"_richfaces_file_upload_stopped\"></html>");
-						}
-					}
+            // normal request, execute chain ...
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN));
+            }
 
-				} finally {
-					httpRequest.setAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME, oldAttributeValue);
-					multipartRequest.clearRequestData();
-				}
-			} else {
-				handleRequest(request, response, chain);
-			}
-		} else {
-			handleRequest(request, response, chain);
-		}
-	}
-	
-	/**
-	 * @param httpServletRequest
-	 * @throws UnsupportedEncodingException
-	 */
-	protected void setupRequestEncoding(HttpServletRequest httpServletRequest)
-			throws UnsupportedEncodingException {
-		String contentType = httpServletRequest.getHeader("Content-Type");
+            chain.doFilter(request, response);
+        }
+    }
 
-		String characterEncoding = lookupCharacterEncoding(contentType);
+    private void checkMyFacesExtensionsFilter(HttpServletRequest request) {
+        if (request.getAttribute(MYFACES_FILTER_CHECKED) == null) {
+            if (request.getAttribute(MYFACES_DOFILTER_CALLED) != null) {
+                if (!this.myfacesMessagePrinted) {
+                    LOG.warn(
+                        "MyFaces Extensions Filter should be configured to execute *AFTER* RichFaces filter. Refer to "
+                                + "SRV.6.2.4 section of Servlets specification on how to achieve that.");
+                    this.myfacesMessagePrinted = true;
+                }
+            }
 
-		if (characterEncoding == null) {
-			HttpSession session = httpServletRequest.getSession(false);
+            request.setAttribute(MYFACES_FILTER_CHECKED, Boolean.TRUE);
+        }
+    }
 
-			if (session != null) {
-				characterEncoding = (String) session
-						.getAttribute(ViewHandler.CHARACTER_ENCODING_KEY);
-			}
+    /**
+     * Method catches upload files request. Request parameter
+     * <b>org.ajax4jsf.Filter.UPLOAD_FILES_ID</b> indicates if request
+     * generated by rich-upload component. If it was detected custom parsing
+     * request should be done. Processing information about percent of
+     * completion and file size will be put into session scope.
+     *
+     * @param request
+     * @param response
+     * @return
+     * @throws IOException
+     * @throws ServletException
+     */
+    protected void processUploadsAndHandleRequest(HttpServletRequest request, HttpServletResponse response,
+            FilterChain chain) throws IOException, ServletException {
 
-			if (characterEncoding != null) {
-				httpServletRequest.setCharacterEncoding(characterEncoding);
-			}
-		}
-	}
+        HttpServletRequest httpRequest = (HttpServletRequest) request;
+        Map<String, String> queryParamMap = parseQueryString(httpRequest.getQueryString());
+        String uid = queryParamMap.get(FileUploadConstants.UPLOAD_FILES_ID);
 
-	/**
-	 * Detect request encoding from Content-Type header
-	 * 
-	 * @param contentType
-	 * @return - charset, if present.
-	 */
-	private String lookupCharacterEncoding(String contentType) {
-		String characterEncoding = null;
+        if (uid != null) {
+            if (isMultipartRequest(httpRequest)) {
+                MultipartRequest multipartRequest = new MultipartRequest(httpRequest, createTempFiles, maxRequestSize,
+                                                        uid);
+                Object oldAttributeValue =
+                    httpRequest.getAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME);
 
-		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;
-	}
+                httpRequest.setAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME, multipartRequest);
 
-	/**
-	 * @param initParameter
-	 * @param function2
-	 * @return
-	 */
-	private Object nz(Object param, Object def) {
-		return param != null ? param : def;
-	}
+                try {
+                    if (isFileSizeRestricted(request, maxRequestSize)) {
+                        boolean sendError = Boolean.parseBoolean(queryParamMap.get(SEND_HTTP_ERROR));
 
-	/**
-	 * 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()));
-		}
+                        if (sendError) {
+                            response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
+                            System.err.println(
+                                "ERROR " + HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
+                                + "request entity is larger than the server is willing or able to process.");
 
-		if (request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) {
-			// mark - and not processing same request twice.
-			try {
-				request.setAttribute(FILTER_PERFORMED, Boolean.TRUE);
-				String ajaxPushHeader = httpServletRequest
-						.getHeader(AJAX_PUSH_KEY_HEADER);
-				// check for a push check request.
-				if (httpServletRequest.getMethod().equals("HEAD")
-						&& null != ajaxPushHeader) {
-					PushEventsCounter listener = eventsManager
-							.getListener(ajaxPushHeader);
-					// To avoid XmlHttpRequest parsing exceptions.
-					httpServletResponse.setContentType("text/plain");
-					if (listener.isPerformed()) {
-						listener.processed();
-						httpServletResponse.setStatus(HttpServletResponse.SC_OK);
-						httpServletResponse.setHeader(AJAX_PUSH_STATUS_HEADER, AJAX_PUSH_READY);
-						if (log.isDebugEnabled()) {
-							log
-									.debug("Occurs event for a id "
-											+ ajaxPushHeader);
-						}
-					} else {
-						// Response code - 'No content'
-						httpServletResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
-						if (log.isDebugEnabled()) {
-							log.debug("No event for a id " + ajaxPushHeader);
-						}
-					}
-					httpServletResponse.setContentLength(0);
-				} else
-				// 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);
-					checkMyFacesExtensionsFilter(httpServletRequest);
-					processUploadsAndHandleRequest(httpServletRequest, httpServletResponse, chain);
-				//}
-			} finally {
-				// Remove filter marker from response, to enable sequence calls ( for example, forward to error page )
-				request.removeAttribute(FILTER_PERFORMED);
-				Object ajaxContext = request.getAttribute(AjaxContext.AJAX_CONTEXT_KEY);
-				if(null != ajaxContext && ajaxContext instanceof AjaxContext){
-					((AjaxContext)ajaxContext).release();
-					request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY);
-				}
-			}
-		} else {
-			if (log.isDebugEnabled()) {
-				log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2));
-			}
-			chain.doFilter(request, response);
+                            return;
+                        } else {
+                            printResponse(response, "<html id=\"_richfaces_file_upload_size_restricted\"></html>");
+                        }
+                    } else if (!checkFileCount(httpRequest, queryParamMap.get("id"))) {
+                        printResponse(response, "<html id=\"_richfaces_file_upload_forbidden\"></html>");
+                    } else {
+                        handleRequest(multipartRequest, getHttpServletResponse(response, multipartRequest), chain);
 
-		}
-		if (log.isDebugEnabled()) {
-			startTimeMills = System.currentTimeMillis() - startTimeMills;
-			log.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, ""
-					+ startTimeMills, httpServletRequest.getRequestURI()));
-		}
-	}
+                        if (!multipartRequest.isDone()) {
+                            printResponse(response, "<html id=\"_richfaces_file_upload_stopped\"></html>");
+                        }
+                    }
+                } finally {
+                    httpRequest.setAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME, oldAttributeValue);
+                    multipartRequest.clearRequestData();
+                }
+            } else {
+                handleRequest(request, response, chain);
+            }
+        } else {
+            handleRequest(request, response, chain);
+        }
+    }
 
-	/**
-	 * @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;
-		}
-	}
+    private HttpServletResponse getHttpServletResponse(final HttpServletResponse response,
+            MultipartRequest multipartRequest) {
+        if (multipartRequest.isFormUpload()) {
+            return response;
+        }
 
-	/**
-	 * Destroy the filter.
-	 */
-	public void destroy() {
-	}
+        return new HttpServletResponseWrapper((HttpServletResponse) response) {
+            @Override
+            public void setContentType(String type) {
+                super.setContentType(BaseXMLFilter.TEXT_HTML + ";charset=UTF-8");
+            }
+        };
+    }
 
-	/**
-	 * @return Returns the servletContext.
-	 */
-	ServletContext getServletContext() {
-		return filterConfig.getServletContext();
-	}
+    /**
+     * @param httpServletRequest
+     * @throws UnsupportedEncodingException
+     */
+    protected void setupRequestEncoding(HttpServletRequest httpServletRequest) throws UnsupportedEncodingException {
+        String contentType = httpServletRequest.getHeader("Content-Type");
+        String characterEncoding = lookupCharacterEncoding(contentType);
 
-	/**
-	 * @return the resourceService
-	 * @throws ServletException
-	 */
-	protected synchronized InternetResourceService getResourceService()
-			throws ServletException {
-		// if (resourceService == null) {
-		// resourceService = new InternetResourceService();
-		// // Caching initialization.
-		// resourceService.init(filterConfig);
-		//
-		// }
-		return resourceService;
-	}
+        if (characterEncoding == null) {
+            HttpSession session = httpServletRequest.getSession(false);
 
-	/**
-	 * @param function
-	 *            The function to set.
-	 */
-	protected void setFunction(String function) {
-		this.function = function;
-	}
+            if (session != null) {
+                characterEncoding = (String) session.getAttribute(ViewHandler.CHARACTER_ENCODING_KEY);
+            }
 
-	/**
-	 * @return Returns the function.
-	 */
-	protected String getFunction() {
-		return function;
-	}
+            if (characterEncoding != null) {
+                httpServletRequest.setCharacterEncoding(characterEncoding);
+            }
+        }
+    }
 
-	/**
-	 * @param rewriteid
-	 *            The rewriteid to set.
-	 */
-	protected void setRewriteid(boolean rewriteid) {
-		this.rewriteid = rewriteid;
-	}
+    /**
+     * Detect request encoding from Content-Type header
+     *
+     * @param contentType
+     * @return - charset, if present.
+     */
+    private String lookupCharacterEncoding(String contentType) {
+        String characterEncoding = null;
 
-	/**
-	 * @return Returns the rewriteid.
-	 */
-	protected boolean isRewriteid() {
-		return rewriteid;
-	}
+        if (contentType != null) {
+            int charsetFind = contentType.indexOf("charset=");
 
-	/**
-	 * @param attributesNames
-	 *            The attributesNames to set.
-	 */
-	protected void setAttributesNames(String attributesNames) {
-		this.attributesNames = attributesNames;
-	}
+            if (charsetFind != -1) {
+                if (charsetFind == 0) {
 
-	/**
-	 * @return Returns the attributesNames.
-	 */
-	protected String getAttributesNames() {
-		return attributesNames;
-	}
+                    // 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;
+    }
+
+    /**
+     * @param def
+     * @param param
+     * @return
+     */
+    private Object nz(Object param, Object def) {
+        return (param != null) ? param : def;
+    }
+
+    /**
+     * 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()));
+        }
+
+        if (request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) {
+
+            // mark - and not processing same request twice.
+            try {
+                request.setAttribute(FILTER_PERFORMED, Boolean.TRUE);
+
+                String ajaxPushHeader = httpServletRequest.getHeader(AJAX_PUSH_KEY_HEADER);
+
+                // check for a push check request.
+                if (httpServletRequest.getMethod().equals("HEAD") && (null != ajaxPushHeader)) {
+                    PushEventsCounter listener = eventsManager.getListener(ajaxPushHeader);
+
+                    // To avoid XmlHttpRequest parsing exceptions.
+                    httpServletResponse.setContentType("text/plain");
+
+                    if (listener.isPerformed()) {
+                        listener.processed();
+                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
+                        httpServletResponse.setHeader(AJAX_PUSH_STATUS_HEADER, AJAX_PUSH_READY);
+
+                        if (LOG.isDebugEnabled()) {
+                            LOG.debug("Occurs event for a id " + ajaxPushHeader);
+                        }
+                    } else {
+
+                        // Response code - 'No content'
+                        httpServletResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
+
+                        if (LOG.isDebugEnabled()) {
+                            LOG.debug("No event for a id " + ajaxPushHeader);
+                        }
+                    }
+
+                    httpServletResponse.setContentLength(0);
+                } else {
+
+                    // 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);
+                }
+
+                checkMyFacesExtensionsFilter(httpServletRequest);
+                processUploadsAndHandleRequest(httpServletRequest, httpServletResponse, chain);
+
+                // }
+            } finally {
+
+                // Remove filter marker from response, to enable sequence calls ( for example, forward to error page )
+                request.removeAttribute(FILTER_PERFORMED);
+
+                Object ajaxContext = request.getAttribute(AjaxContext.AJAX_CONTEXT_KEY);
+
+                if ((null != ajaxContext) && (ajaxContext instanceof AjaxContext)) {
+                    ((AjaxContext) ajaxContext).release();
+                    request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY);
+                }
+            }
+        } else {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2));
+            }
+
+            chain.doFilter(request, response);
+        }
+
+        if (LOG.isDebugEnabled()) {
+            startTimeMills = System.currentTimeMillis() - startTimeMills;
+            LOG.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, "" + startTimeMills,
+                                          httpServletRequest.getRequestURI()));
+        }
+    }
+
+    /**
+     * @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;
+        }
+    }
+
+    /**
+     * Destroy the filter.
+     */
+    public void destroy() { }
+
+    /**
+     * @return Returns the servletContext.
+     */
+    ServletContext getServletContext() {
+        return filterConfig.getServletContext();
+    }
+
+    /**
+     * @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: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/BaseXMLFilter.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/BaseXMLFilter.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/BaseXMLFilter.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,16 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp;
 
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.io.Writer;
-import java.util.Iterator;
-import java.util.Map;
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.application.AjaxViewHandler;
+import org.ajax4jsf.context.ContextInitParameters;
+import org.ajax4jsf.renderkit.AjaxContainerRenderer;
 
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
 import javax.faces.application.ViewExpiredException;
+
 import javax.servlet.FilterChain;
 import javax.servlet.FilterConfig;
 import javax.servlet.ServletException;
@@ -38,534 +43,510 @@
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.application.AjaxViewHandler;
-import org.ajax4jsf.context.ContextInitParameters;
-import org.ajax4jsf.renderkit.AjaxContainerRenderer;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
 
+import java.util.Map;
+
 public abstract class BaseXMLFilter {
-	public static final String AJAX_EXPIRED = "Ajax-Expired";
+    public static final String AJAX_EXPIRED = "Ajax-Expired";
+    public static final String APPLICATION_XHTML_XML = "application/xhtml+xml";
+    public static final String APPLICATION_SCOPE_KEY = BaseXMLFilter.class.getName();
+    public static final String TEXT_HTML = "text/html";
 
-	private static final Logger log = RichfacesLogger.WEBAPP.getLogger();
+    private static final String FORCENOTRF_PARAMETER = "forcenotrf";
+    private static final String FORCEXML_PARAMETER = "forceparser";
+    private static final String INIT_PARAMETER_PREFIX = "org.ajax4jsf.xmlfilter.";
+    private static final String MIME_TYPE_PARAMETER = "mime-type";
+    private static final String NAMESPACE_PARAMETER = "namespace";
+    private static final String PUBLICID_PARAMETER = "publicid";
+    private static final String SYSTEMID_PARAMETER = "systemid";
+    private static final Logger LOG = RichfacesLogger.WEBAPP.getLogger();
 
-	public static final String APPLICATION_SCOPE_KEY = BaseXMLFilter.class.getName();
-	
-	private String mimetype = "text/xml";
+    private String mimetype = "text/xml";
+    private String namespace = "http://www.w3.org/1999/xhtml";
+    private String publicid = "-//W3C//DTD XHTML 1.0 Transitional//EN";
+    private String systemid = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
+    private boolean handleViewExpiredOnClient = false;
+    private boolean forcexml = false;
+    private boolean forceNotRf = true;
+    private BaseFilter filter;
 
-	private String publicid = "-//W3C//DTD XHTML 1.0 Transitional//EN";
+    public void setFilter(BaseFilter filter) {
+        this.filter = filter;
+    }
 
-	private String systemid = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
+    public void init(FilterConfig config) throws ServletException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("init XML filter service with class " + this.getClass().getName());
+        }
 
-	private String namespace = "http://www.w3.org/1999/xhtml";
+        String forceXmlParameter = config.getInitParameter(FORCEXML_PARAMETER);
 
-	private static final String MIME_TYPE_PARAMETER = "mime-type";
+        if (forceXmlParameter == null) {
+            forceXmlParameter = config.getServletContext().getInitParameter(INIT_PARAMETER_PREFIX + FORCEXML_PARAMETER);
+        }
 
-	private static final String PUBLICID_PARAMETER = "publicid";
+        setupForceXml(forceXmlParameter);
 
-	private static final String SYSTEMID_PARAMETER = "systemid";
+        String forceNotRfParameter = config.getInitParameter(FORCENOTRF_PARAMETER);
 
-	private static final String NAMESPACE_PARAMETER = "namespace";
+        if (forceNotRfParameter == null) {
+            forceNotRfParameter = config.getServletContext().getInitParameter(INIT_PARAMETER_PREFIX
+                    + FORCENOTRF_PARAMETER);
+        }
 
-	private boolean forcexml = false;
+        setupForcenotrf(forceNotRfParameter);
+        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()));
+        handleViewExpiredOnClient = Boolean.parseBoolean(
+            config.getServletContext().getInitParameter(ContextInitParameters.HANDLE_VIEW_EXPIRED_ON_CLIENT));
+    }
 
-	private boolean forceNotRf = true;
-	
-	private static final String FORCEXML_PARAMETER = "forceparser";
+    private Boolean stringToBoolean(String s) {
+        if ("false".equalsIgnoreCase(s)) {
+            return Boolean.FALSE;
+        } else if ("true".equalsIgnoreCase(s)) {
+            return Boolean.TRUE;
+        }
 
-	private static final String FORCENOTRF_PARAMETER = "forcenotrf";
+        return null;
+    }
 
-	private static final String INIT_PARAMETER_PREFIX = "org.ajax4jsf.xmlfilter.";
+    private void setupForcenotrf(String paramValue) {
+        Boolean val = stringToBoolean(paramValue);
 
-	public static final String TEXT_HTML = "text/html";
+        if (val != null) {
+            this.forceNotRf = val.booleanValue();
+        }
+    }
 
-	public static final String APPLICATION_XHTML_XML = "application/xhtml+xml";
-	
-	private boolean handleViewExpiredOnClient=false;
-	
-	public BaseFilter filter;
+    /**
+     * @param forceXmlParameter
+     */
+    private void setupForceXml(String forceXmlParameter) {
+        Boolean val = stringToBoolean(forceXmlParameter);
 
-	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());
-		}
-		String forceXmlParameter = config.getInitParameter(FORCEXML_PARAMETER);
-		if (forceXmlParameter == null) {
-			forceXmlParameter = config.getServletContext().getInitParameter(
-					INIT_PARAMETER_PREFIX + FORCEXML_PARAMETER);
-		}
-		setupForceXml(forceXmlParameter);
+        if (val != null) {
+            this.forcexml = val.booleanValue();
+        }
+    }
 
-		String forceNotRfParameter = config.getInitParameter(FORCENOTRF_PARAMETER);
-		if (forceNotRfParameter == null) {
-			forceNotRfParameter = config.getServletContext().getInitParameter(
-					INIT_PARAMETER_PREFIX + FORCENOTRF_PARAMETER);
-		}
-		setupForcenotrf(forceNotRfParameter);
+    /**
+     * 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");
+        }
 
-		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()));
-		handleViewExpiredOnClient = Boolean.parseBoolean(config.getServletContext().getInitParameter(ContextInitParameters.HANDLE_VIEW_EXPIRED_ON_CLIENT));
-		
-	}
+        FilterServletResponseWrapper servletResponseWrapper = getWrapper(response);
 
-	private Boolean stringToBoolean(String s) {
-		if ("false".equalsIgnoreCase(s)) {
-			return Boolean.FALSE;
-		} else if ("true".equalsIgnoreCase(s)) {
-			return Boolean.TRUE;
-		}
-		
-		return null;
-	}
-	
-	private void setupForcenotrf(String paramValue) {
-		Boolean val = stringToBoolean(paramValue);
-		if (val != null) {
-			this.forceNotRf = val.booleanValue();
-		}
-	}
-	
-	/**
-	 * @param forceXmlParameter
-	 */
-	private void setupForceXml(String forceXmlParameter) {
-		Boolean val = stringToBoolean(forceXmlParameter);
-		if (val != null) {
-			this.forcexml = val.booleanValue();
-		}
-	}
+        // 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.
+        try {
+            request.setAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE, servletResponseWrapper);
+            chain.doFilter(request, servletResponseWrapper);
+        } catch (ServletException e) {
+            if (handleViewExpiredOnClient && (isViewExpired(e) || isViewExpired(e.getRootCause()))
+                    && isAjaxRequest(request)) {
+                LOG.debug("ViewExpiredException in the filter chain - will be handled on the client", e);
 
-	/**
-	 * 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.
-		try {
-			request.setAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE,
-					servletResponseWrapper);
-			chain.doFilter(request, servletResponseWrapper);
+                Writer output = resetResponse(response, servletResponseWrapper, "true");
+                String message = Messages.getMessage(Messages.AJAX_VIEW_EXPIRED);
 
-		} catch (ServletException e) {
-			if(handleViewExpiredOnClient && (isViewExpired(e) || isViewExpired(e.getRootCause())) && isAjaxRequest(request)){
-				log.debug("ViewExpiredException in the filter chain - will be handled on the client", e);
-				Writer output = resetResponse(response, servletResponseWrapper, "true");
-				String message = Messages
-				.getMessage(Messages.AJAX_VIEW_EXPIRED);
-				response.setHeader(AJAX_EXPIRED, message);
-				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=\"true\" />" + "<meta name=\""
-						+ AJAX_EXPIRED
-						+ "\" content=\"" + message + "\" />"
-						+ "</head></html>");
-				output.flush();
-				response.flushBuffer();
-				return;
-			} else {
-				log.error("Exception in the filter chain", e);
-				throw e;
-			}
-		} finally {
-			request.removeAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE);
-		}
-		String viewId = (String) request
-				.getAttribute(AjaxViewHandler.VIEW_ID_KEY);
-	
-		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);
-				}
-				output = resetResponse(response, servletResponseWrapper,
-						"redirect");
-				response.setHeader(AjaxContainerRenderer.AJAX_LOCATION_HEADER,
-						redirectLocation);
-				// 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, viewId);
-				if (null == parser) {
-					throw new ServletException(Messages.getMessage(
-							Messages.PARSER_NOT_INSTANTIATED_ERROR, contentType));
-				}
-				output = createOutputWriter(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();
-				String contentTypeCharset = contentType;
-				if (log.isDebugEnabled()) {
-					log.debug("create HTML/XML parser for content type: "
-							+ contentType);
-				}
-				// if(contentType == null){
-				// contentType = request.getContentType();
-				// }
-				boolean forcenotrf = isForcenotrf();
-				
-				if (forcenotrf || !servletResponseWrapper.isError()) {
-					if (forcenotrf) {
-						if (contentTypeCharset != null) {
-							if (contentTypeCharset.indexOf("charset") < 0
-									&& null != characterEncoding) {
-							    contentTypeCharset += ";charset=" + characterEncoding;
-							}
-							parser = getParser(contentTypeCharset, false, viewId);
-							if (null == parser) {
-								if (log.isDebugEnabled()) {
-									log
-											.debug("Parser not have support for the such content type, send response as-is");
-								}
-							}
-						}
-					} else {
-						if (log.isDebugEnabled()) {
-							log.debug("No resource inclusions detected, send response as-is");
-						}
-					}
-				} else {
-					if (log.isDebugEnabled()) {
-						log.debug("Servlet error occured, send response as-is");
-					}
-				}
-				
-				
-				// null or unsupported content type
-				if (null == parser) {
-					try {
-						if (servletResponseWrapper.isUseWriter()) {
-							if (contentTypeCharset != null) {
-							    response.setContentType(contentTypeCharset);
-							}
-	
-							output = createOutputWriter(response,
-									characterEncoding);
-							servletResponseWrapper.sendContent(output);
-						} else if (servletResponseWrapper.isUseStream()) {
-							if (contentType != null) {
-							    response.setContentType(contentType);
-							}
-	
-							ServletOutputStream out = response.getOutputStream();
-							servletResponseWrapper.sendContent(out);
-						}
-					} finally {
-						// reuseWrapper(servletResponseWrapper);
-					}
-					
-					
-					return;
-				}
-	
-				if (contentTypeCharset != null) {
-				    response.setContentType(contentTypeCharset);
-				}
-				
-				output = createOutputWriter(response, characterEncoding);
-	
-				parser.setInputEncoding(characterEncoding);
-				parser.setOutputEncoding(characterEncoding);
-			}
-		}
-		
-		try {
-			// 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);
-		}
-	}
+                response.setHeader(AJAX_EXPIRED, message);
+                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=\"true\" />" + "<meta name=\""
+                             + AJAX_EXPIRED + "\" content=\"" + message + "\" />" + "</head></html>");
+                output.flush();
+                response.flushBuffer();
 
-	/**
-	 * @param response
-	 * @param servletResponseWrapper
-	 * @param ajaxResponseType
-	 * @return
-	 * @throws IOException
-	 * @throws UnsupportedEncodingException
-	 */
-	private Writer resetResponse(final HttpServletResponse response,
-			FilterServletResponseWrapper servletResponseWrapper,
-			String ajaxResponseType) throws IOException,
-			UnsupportedEncodingException {
-		Writer output;
-		response.reset();
-		// Keep cookies.
-		for (Iterator<Cookie> iter = servletResponseWrapper.getCookies()
-				.iterator(); iter.hasNext();) {
-			Cookie cookie = (Cookie) iter.next();
-			response.addCookie(cookie);
-		}
-		// Copy response headers
-		Map<String, Object> headers = servletResponseWrapper.getHeaders();
-		for (Iterator<Map.Entry<String, Object>> iter = headers.entrySet().iterator(); iter
-				.hasNext();) {
-			Map.Entry<String, Object> header = iter.next();
-			response.setHeader((String) header.getKey(),
-					(String) header.getValue());
-		}
-		response.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER,
-				ajaxResponseType);
-		// 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");
-		output = createOutputWriter(response, "UTF-8");
-		return output;
-	}
+                return;
+            } else {
+                LOG.error("Exception in the filter chain", e);
 
-	/**
-	 * Check for a {@link ViewExpiredException} in the exception chain.
-	 * @param e exception from filter chain
-	 * @return true if any exception in the chain instance of the {@link ViewExpiredException}
-	 */
-	private boolean isViewExpired(Throwable e) {
-		while (null != e) {
-			if (e instanceof ViewExpiredException) {
-				return true;
-			} else {
-				e = e.getCause();
-			}
-		}
-		return false;
-	}
+                throw e;
+            }
+        } finally {
+            request.removeAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE);
+        }
 
-	/**
-	 * @param response
-	 * @return
-	 * @throws ServletException
-	 */
-	protected FilterServletResponseWrapper getWrapper(
-			HttpServletResponse response) throws ServletException {
-		return new FilterServletResponseWrapper(response);
-	}
+        String viewId = (String) request.getAttribute(AjaxViewHandler.VIEW_ID_KEY);
+        HtmlParser parser = null;
 
-	/**
-	 * @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;
-		}
-	}
+        // setup response
+        // Redirect in AJAX request - convert to special response recognized by
+        // client.
+        String redirectLocation = servletResponseWrapper.getRedirectLocation();
+        String characterEncoding = servletResponseWrapper.getCharacterEncoding();
+        Writer output;
 
-	/**
-	 * @param response
-	 * @param characterEncoding
-	 * @return
-	 * @throws IOException
-	 * @throws UnsupportedEncodingException
-	 */
-	private Writer createOutputWriter(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;
-	}
+        if (null != redirectLocation) {
+            if (isAjaxRequest(request)) {
 
-	protected abstract void reuseParser(HtmlParser parser);
+                // 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);
+                }
 
-	protected abstract HtmlParser getParser(String mimetype, boolean isAjax,
-			String viewId);
+                output = resetResponse(response, servletResponseWrapper, "redirect");
+                response.setHeader(AjaxContainerRenderer.AJAX_LOCATION_HEADER, redirectLocation);
 
-	/**
-	 * @param publicid
-	 *            The publicid to set.
-	 */
-	protected void setPublicid(String publicid) {
-		this.publicid = publicid;
-	}
+                // 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 Returns the publicid.
-	 */
-	public String getPublicid() {
-		return publicid;
-	}
+            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");
+                }
 
-	/**
-	 * @param systemid
-	 *            The systemid to set.
-	 */
-	protected void setSystemid(String systemid) {
-		this.systemid = systemid;
-	}
+                // 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");
 
-	/**
-	 * @return Returns the systemid.
-	 */
-	public String getSystemid() {
-		return systemid;
-	}
+                // 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;
 
-	/**
-	 * @param namespace
-	 *            The namespace to set.
-	 */
-	protected void setNamespace(String namespace) {
-		this.namespace = namespace;
-	}
+                response.setContentType(contentType);
+                parser = getParser(getMimetype(), true, viewId);
 
-	/**
-	 * @return Returns the namespace.
-	 */
-	public String getNamespace() {
-		return namespace;
-	}
+                if (null == parser) {
+                    throw new ServletException(Messages.getMessage(Messages.PARSER_NOT_INSTANTIATED_ERROR,
+                            contentType));
+                }
 
-	/**
-	 * @param mimetype
-	 *            The mimetype to set.
-	 */
-	protected void setMimetype(String mimetype) {
-		this.mimetype = mimetype;
-	}
+                output = createOutputWriter(response, outputEncoding);
+                parser.setDoctype(getPublicid());
+                parser.setInputEncoding(characterEncoding);
+                parser.setOutputEncoding(outputEncoding);
+                parser.setViewState((String) request.getAttribute(AjaxViewHandler.SERIALIZED_STATE_KEY));
+            } else {
 
-	/**
-	 * @return Returns the mimetype.
-	 */
-	public String getMimetype() {
-		return mimetype;
-	}
-	
-	/**
-	 * @return Returns the forcexml.
-	 */
-	public boolean isForcexml() {
-		return this.forcexml;
-	}
+                // setup conversion reules for output contentType, send directly
+                // if content not
+                // supported by tidy.
+                String contentType = servletResponseWrapper.getContentType();
+                String contentTypeCharset = contentType;
 
-	public boolean isForcenotrf() {
-		return this.forceNotRf;
-	}
-	
-	/**
-	 * @param forcexml
-	 *            The forcexml to set.
-	 */
-	protected void setForcexml(boolean forcexml) {
-		this.forcexml = forcexml;
-	}
-	
-	protected void setForcenotrf(boolean forcenotrf) {
-		this.forceNotRf = forcenotrf;
-	}
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("create HTML/XML parser for content type: " + contentType);
+                }
 
-	private Object nz(Object param, Object def) {
-		return param != null ? param : def;
-	}
+                // if(contentType == null){
+                // contentType = request.getContentType();
+                // }
+                boolean forcenotrf = isForcenotrf();
 
+                if (forcenotrf || !servletResponseWrapper.isError()) {
+                    if (forcenotrf) {
+                        if (contentTypeCharset != null) {
+                            if ((contentTypeCharset.indexOf("charset") < 0) && (null != characterEncoding)) {
+                                contentTypeCharset += ";charset=" + characterEncoding;
+                            }
+
+                            parser = getParser(contentTypeCharset, false, viewId);
+
+                            if (null == parser) {
+                                if (LOG.isDebugEnabled()) {
+                                    LOG.debug("Parser not have support for the such content type, send response as-is");
+                                }
+                            }
+                        }
+                    } else {
+                        if (LOG.isDebugEnabled()) {
+                            LOG.debug("No resource inclusions detected, send response as-is");
+                        }
+                    }
+                } else {
+                    if (LOG.isDebugEnabled()) {
+                        LOG.debug("Servlet error occured, send response as-is");
+                    }
+                }
+
+                // null or unsupported content type
+                if (null == parser) {
+                    try {
+                        if (servletResponseWrapper.isUseWriter()) {
+                            if (contentTypeCharset != null) {
+                                response.setContentType(contentTypeCharset);
+                            }
+
+                            output = createOutputWriter(response, characterEncoding);
+                            servletResponseWrapper.sendContent(output);
+                        } else if (servletResponseWrapper.isUseStream()) {
+                            if (contentType != null) {
+                                response.setContentType(contentType);
+                            }
+
+                            ServletOutputStream out = response.getOutputStream();
+
+                            servletResponseWrapper.sendContent(out);
+                        }
+                    } finally {
+
+                        // reuseWrapper(servletResponseWrapper);
+                    }
+
+                    return;
+                }
+
+                if (contentTypeCharset != null) {
+                    response.setContentType(contentTypeCharset);
+                }
+
+                output = createOutputWriter(response, characterEncoding);
+                parser.setInputEncoding(characterEncoding);
+                parser.setOutputEncoding(characterEncoding);
+            }
+        }
+
+        try {
+
+            // 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);
+        }
+    }
+
+    /**
+     * @param response
+     * @param servletResponseWrapper
+     * @param ajaxResponseType
+     * @return
+     * @throws IOException
+     * @throws UnsupportedEncodingException
+     */
+    private Writer resetResponse(final HttpServletResponse response,
+        FilterServletResponseWrapper servletResponseWrapper, String ajaxResponseType)
+        throws IOException, UnsupportedEncodingException {
+        
+        response.reset();
+
+        // Keep cookies.
+        for (Cookie cookie : servletResponseWrapper.getCookies()) {
+            response.addCookie(cookie);
+        }
+
+        // Copy response headers
+        Map<String, Object> headers = servletResponseWrapper.getHeaders();
+
+        for (Map.Entry<String, Object> header : headers.entrySet()) {
+            response.setHeader(header.getKey(), (String) header.getValue());
+        }
+
+        response.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER, ajaxResponseType);
+
+        // 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");
+
+        return createOutputWriter(response, "UTF-8");
+    }
+
+    /**
+     * Check for a {@link ViewExpiredException} in the exception chain.
+     * @param e exception from filter chain
+     * @return true if any exception in the chain instance of the {@link ViewExpiredException}
+     */
+    private boolean isViewExpired(Throwable e) {
+        while (null != e) {
+            if (e instanceof ViewExpiredException) {
+                return true;
+            } else {
+                e = e.getCause();
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * @param response
+     * @return
+     * @throws ServletException
+     */
+    protected FilterServletResponseWrapper getWrapper(HttpServletResponse response) throws ServletException {
+        return new FilterServletResponseWrapper(response);
+    }
+
+    /**
+     * @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;
+        }
+    }
+
+    /**
+     * @param response
+     * @param characterEncoding
+     * @return
+     * @throws IOException
+     * @throws UnsupportedEncodingException
+     */
+    private Writer createOutputWriter(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;
+    }
+
+    protected abstract void reuseParser(HtmlParser parser);
+
+    protected abstract HtmlParser getParser(String mimetype, boolean isAjax, String viewId);
+
+    /**
+     * @param publicid
+     *            The publicid to set.
+     */
+    protected void setPublicid(String publicid) {
+        this.publicid = publicid;
+    }
+
+    /**
+     * @return Returns the publicid.
+     */
+    public String getPublicid() {
+        return publicid;
+    }
+
+    /**
+     * @param systemid
+     *            The systemid to set.
+     */
+    protected void setSystemid(String systemid) {
+        this.systemid = systemid;
+    }
+
+    /**
+     * @return Returns the systemid.
+     */
+    public String getSystemid() {
+        return systemid;
+    }
+
+    /**
+     * @param namespace
+     *            The namespace to set.
+     */
+    protected void setNamespace(String namespace) {
+        this.namespace = namespace;
+    }
+
+    /**
+     * @return Returns the namespace.
+     */
+    public String getNamespace() {
+        return namespace;
+    }
+
+    /**
+     * @param mimetype
+     *            The mimetype to set.
+     */
+    protected void setMimetype(String mimetype) {
+        this.mimetype = mimetype;
+    }
+
+    /**
+     * @return Returns the mimetype.
+     */
+    public String getMimetype() {
+        return mimetype;
+    }
+
+    /**
+     * @return Returns the forcexml.
+     */
+    public boolean isForcexml() {
+        return this.forcexml;
+    }
+
+    public boolean isForcenotrf() {
+        return this.forceNotRf;
+    }
+
+    /**
+     * @param forcexml
+     *            The forcexml to set.
+     */
+    protected void setForcexml(boolean forcexml) {
+        this.forcexml = forcexml;
+    }
+
+    protected void setForcenotrf(boolean forcenotrf) {
+        this.forceNotRf = forcenotrf;
+    }
+
+    private Object nz(Object param, Object def) {
+        return (param != null) ? param : def;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/CacheContent.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/CacheContent.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/CacheContent.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,334 +19,316 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp;
 
+import org.ajax4jsf.io.FastBufferOutputStream;
+import org.ajax4jsf.io.FastBufferWriter;
+
+import org.richfaces.log.RichfacesLogger;
+import org.richfaces.util.Util;
+
+import org.slf4j.Logger;
+
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.PrintWriter;
 import java.io.Serializable;
 import java.io.Writer;
+
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Map.Entry;
 
 import javax.faces.context.ExternalContext;
+
 import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletResponse;
 
-import org.ajax4jsf.io.FastBufferOutputStream;
-import org.ajax4jsf.io.FastBufferWriter;
-import org.richfaces.log.RichfacesLogger;
-import org.richfaces.util.Util;
-import org.slf4j.Logger;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:20 $
- * 
+ *
  */
 public class CacheContent implements Serializable {
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = 8120940486890871177L;
+    private static final long serialVersionUID = 8120940486890871177L;
+    private static final Logger LOG = RichfacesLogger.WEBAPP.getLogger();
 
-	private static final Logger _log = RichfacesLogger.WEBAPP.getLogger();
+    // content to send.
+    private byte[] content = null;
+    boolean filledOutputWriter = false;
+    boolean filledOutputStream = false;
+    private String writerContent = null;
+    private Map<String, Object> headers = new HashMap<String, Object>();
+    private Integer contentLength;
+    private String contentType;
 
-	// private transient ByteArrayOutputStream outputStream ;
-	private transient FastBufferOutputStream outputStream;
+    // private transient ByteArrayOutputStream outputStream ;
+    private transient FastBufferOutputStream outputStream;
+    private transient ServletOutputStream servletStream;
+    private transient PrintWriter servletWriter;
+    private transient FastBufferWriter stringOutputWriter;
 
-	private transient FastBufferWriter stringOutputWriter;
+    @Deprecated
+    public void send(HttpServletResponse response) throws IOException {
+        throw new UnsupportedOperationException();
+    }
 
-	private transient PrintWriter servletWriter;
+    /**
+     * Send saved content to http responce
+     *
+     * @param response
+     * @throws IOException
+     */
+    public void send(ExternalContext externalContext) throws IOException {
+        if (filledOutputStream) {
+            OutputStream out = externalContext.getResponseOutputStream();
 
-	private transient ServletOutputStream servletStream;
+            if (content != null) {
+                out.write(content);
+            } else {
+                this.outputStream.writeTo(out);
+            }
 
-	// content to send.
-	private byte[] content = null;
+            // out.flush();
+            // out.close();
+        } else if (filledOutputWriter) {
+            Writer out = externalContext.getResponseOutputWriter();
 
-	private String writerContent = null;
+            if (null != writerContent) {
+                out.write(writerContent);
+            } else {
+                stringOutputWriter.writeTo(out);
+            }
 
-	boolean filledOutputStream = false;
+            // out.flush();
+            // out.close();
+        }
+    }
 
-	boolean filledOutputWriter = false;
+    /**
+     * Send saved headers to http responce.
+     *
+     * @param response
+     */
+    public void sendHeaders(ExternalContext externalContext) {
 
-	private Map<String, Object> headers = new HashMap<String, Object>();
+        // set real content-length.
+        // / if (null != content) {
+        int realContentLength = 0;
 
-	private String contentType;
+        if (filledOutputStream) {
+            if ((null != content) && (content.length > 0)) {
+                realContentLength = content.length;
+            } else if ((null != outputStream) && (outputStream.getLength() > 0)) {
+                realContentLength = outputStream.getLength();
+            }
+        } // TODO - calculate content-lenght for writer ?
 
-	private Integer contentLength;
-	
-	@Deprecated
-	public void send(HttpServletResponse response) throws IOException {
-		throw new UnsupportedOperationException();
-	}
-	
-	/**
-	 * Send saved content to http responce
-	 * 
-	 * @param response
-	 * @throws IOException
-	 */
-	public void send(ExternalContext externalContext) throws IOException {
-		if (filledOutputStream) {
-			OutputStream out = externalContext.getResponseOutputStream();
-			if (content != null) {
-				out.write(content);
-			} else {
-				this.outputStream.writeTo(out);
-			}
-			// out.flush();
-			// out.close();
-		} else if (filledOutputWriter) {
-			Writer out = externalContext.getResponseOutputWriter();
-			if (null != writerContent) {
-				out.write(writerContent);
-			} else {
-				stringOutputWriter.writeTo(out);
-			}
-			// out.flush();
-			// out.close();
-		}
-	}
-	
-    /**
-	 * Send saved headers to http responce.
-	 * 
-	 * @param response
-	 */
-	public void sendHeaders(ExternalContext externalContext) {
-		// set real content-length.
-		// / if (null != content) {
-		int realContentLength = 0;
-		if (filledOutputStream) {
-			if (null != content && content.length > 0) {
-				realContentLength = content.length;
-			} else if (null != outputStream && outputStream.getLength() > 0) {
-				realContentLength = outputStream.getLength();
-			}
-		} // TODO - calculate content-lenght for writer ?
-	
-		if (realContentLength <= 0 && contentLength != null) {
-			realContentLength = contentLength.intValue();
-		}
-		
-		for (Iterator<Entry<String, Object>> iter = headers.entrySet()
-				.iterator(); iter.hasNext();) {
-			Entry<String, Object> element = iter.next();
-			String header = (String) element.getKey();
-			Object headerValue = element.getValue();
-			try {
-				if (headerValue instanceof Long) {
-					Long time = (Long) headerValue;
-					String formattedDate = Util.formatHttpDate(time);
-					externalContext.setResponseHeader(header, formattedDate);
-				} else if (headerValue instanceof Integer) {
-					Integer value = (Integer) headerValue;
-					// Check real content length.
-					if ("Content-Length".equals(header)) {
-						if (realContentLength <= 0) {
-							realContentLength = value.intValue();
-						} else {
-							//do nothing
-						}
-					} else {
-						externalContext.setResponseHeader(header, value.toString());
-					}
-				} else {
-					// Don't send "chunked" transfer-encoding type with real content-length
-					if (!(realContentLength > 0
-							&& "Transfer-Encoding".equals(header) && "chunked"
-							.equals(headerValue))) {
-						externalContext.setResponseHeader(header, (String) headerValue);
-					}
-				}
+        if ((realContentLength <= 0) && (contentLength != null)) {
+            realContentLength = contentLength.intValue();
+        }
 
-			} catch (Exception e) {
-				_log.error("Error set response header " + header + "for value "
-						+ headerValue, e);
-			}
-			if(realContentLength > 0){
-				externalContext.setResponseContentLength(realContentLength);
-			}
-			if (null != contentType) {
-				externalContext.setResponseContentType(this.contentType);
-			}
-		}
-	}
+        for (Iterator<Entry<String, Object>> iter = headers.entrySet().iterator(); iter.hasNext(); ) {
+            Entry<String, Object> element = iter.next();
+            String header = (String) element.getKey();
+            Object headerValue = element.getValue();
 
-	@Deprecated
-	public void sendHeaders(HttpServletResponse response) {
-		throw new UnsupportedOperationException();
-	}
-	
-	public void setDateHeader(String name, long value) {
-		// Expires not stored in cache - must be re-calculated for every
-		// response.
-		if (!"Expires".equals(name)) {
-			headers.put(name, new Long(value));
-		}
-	}
+            try {
+                if (headerValue instanceof Long) {
+                    Long time = (Long) headerValue;
+                    String formattedDate = Util.formatHttpDate(time);
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.resource.ResourceContext#setHeader(java.lang.String,
-	 *      java.lang.String)
-	 */
-	public void setHeader(String name, String value) {
-		headers.put(name, value);
-	}
+                    externalContext.setResponseHeader(header, formattedDate);
+                } else if (headerValue instanceof Integer) {
+                    Integer value = (Integer) headerValue;
 
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.ajax4jsf.framework.resource.ResourceContext#setIntHeader(java.lang.String,
-	 *      int)
-	 */
-	public void setIntHeader(String name, int value) {
-		headers.put(name, new Integer(value));
-	}
+                    // Check real content length.
+                    if ("Content-Length".equals(header)) {
+                        if (realContentLength <= 0) {
+                            realContentLength = value.intValue();
+                        } else {
 
-	/**
-	 * Create UNIX command 'tee' like stream - send all data to servlet
-	 * 
-	 * @param responseStream
-	 * @return
-	 */
-	public OutputStream getOutputStream() {
-		if (null == servletStream) {
-			outputStream = new FastBufferOutputStream(1024);
-			servletStream = new ServletOutputStream() {
+                            // do nothing
+                        }
+                    } else {
+                        externalContext.setResponseHeader(header, value.toString());
+                    }
+                } else {
 
-				/*
-				 * (non-Javadoc)
-				 * 
-				 * @see java.io.OutputStream#close()
-				 */
-				public void close() throws IOException {
-					filledOutputStream = true;
-					// / content = outputStream.toByteArray();
-					content = null;
-				}
+                    // Don't send "chunked" transfer-encoding type with real content-length
+                    if (!((realContentLength > 0) && "Transfer-Encoding".equals(header)
+                            && "chunked".equals(headerValue))) {
+                        externalContext.setResponseHeader(header, (String) headerValue);
+                    }
+                }
+            } catch (Exception e) {
+                LOG.error("Error set response header " + header + "for value " + headerValue, e);
+            }
 
-				/*
-				 * (non-Javadoc)
-				 * 
-				 * @see java.io.OutputStream#flush()
-				 */
-				public void flush() throws IOException {
-				}
+            if (realContentLength > 0) {
+                externalContext.setResponseContentLength(realContentLength);
+            }
 
-				/*
-				 * (non-Javadoc)
-				 * 
-				 * @see java.io.OutputStream#write(byte[], int, int)
-				 */
-				public void write(byte[] b, int off, int len)
-						throws IOException {
-					outputStream.write(b, off, len);
-				}
+            if (null != contentType) {
+                externalContext.setResponseContentType(this.contentType);
+            }
+        }
+    }
 
-				/*
-				 * (non-Javadoc)
-				 * 
-				 * @see java.io.OutputStream#write(byte[])
-				 */
-				public void write(byte[] b) throws IOException {
-					outputStream.write(b);
-				}
+    @Deprecated
+    public void sendHeaders(HttpServletResponse response) {
+        throw new UnsupportedOperationException();
+    }
 
-				public void write(int b) throws IOException {
-					outputStream.write(b);
-				}
+    public void setDateHeader(String name, long value) {
 
-			};
-		}
-		return servletStream;
-	}
+        // Expires not stored in cache - must be re-calculated for every
+        // response.
+        if (!"Expires".equals(name)) {
+            headers.put(name, new Long(value));
+        }
+    }
 
-	public PrintWriter getWriter() {
-		if (null == servletWriter) {
-			stringOutputWriter = new FastBufferWriter(1024);
-			Writer out = new Writer() {
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.resource.ResourceContext#setHeader(java.lang.String,
+     *      java.lang.String)
+     */
+    public void setHeader(String name, String value) {
+        headers.put(name, value);
+    }
 
-				public void write(char[] cbuf, int off, int len)
-						throws IOException {
-					stringOutputWriter.write(cbuf, off, len);
-				}
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.ajax4jsf.framework.resource.ResourceContext#setIntHeader(java.lang.String,
+     *      int)
+     */
+    public void setIntHeader(String name, int value) {
+        headers.put(name, new Integer(value));
+    }
 
-				public void flush() throws IOException {
-				}
+    /**
+     * Create UNIX command 'tee' like stream - send all data to servlet
+     *
+     * @param responseStream
+     * @return
+     */
+    public OutputStream getOutputStream() {
+        if (null == servletStream) {
+            outputStream = new FastBufferOutputStream(1024);
+            servletStream = new ServletOutputStream() {
+                @Override
+                public void close() {
+                    filledOutputStream = true;
+                    content = null;
+                }
+                @Override
+                public void flush() {}
+                @Override
+                public void write(byte[] b, int off, int len) throws IOException {
+                    outputStream.write(b, off, len);
+                }
+                @Override
+                public void write(byte[] b) throws IOException {
+                    outputStream.write(b);
+                }
+                @Override
+                public void write(int b) throws IOException {
+                    outputStream.write(b);
+                }
+            };
+        }
 
-				public void close() throws IOException {
-					// / writerContent = stringOutputWriter.toString();
-					filledOutputWriter = true;
-					writerContent = null;
-				}
+        return servletStream;
+    }
 
-			};
-			servletWriter = new PrintWriter(out);
-		}
-		return servletWriter;
-	}
+    public PrintWriter getWriter() {
+        if (null == servletWriter) {
+            stringOutputWriter = new FastBufferWriter(1024);
 
-	public void setContentType(String contentType) {
-		this.contentType = contentType;
+            Writer out = new Writer() {
+                @Override
+                public void write(char[] cbuf, int off, int len) throws IOException {
+                    stringOutputWriter.write(cbuf, off, len);
+                }
+                @Override
+                public void flush() throws IOException {}
+                @Override
+                public void close() throws IOException {
+                    filledOutputWriter = true;
+                    writerContent = null;
+                }
+            };
 
-	}
+            servletWriter = new PrintWriter(out);
+        }
 
-	/**
-	 * @return Returns the contentType.
-	 */
-	public String getContentType() {
-		return contentType;
-	}
+        return servletWriter;
+    }
 
-	private void writeObject(java.io.ObjectOutputStream s) throws IOException {
-		if (filledOutputStream) {
-			if (outputStream != null) {
-				content = outputStream.toByteArray();
-			}
-		} else if (filledOutputWriter) {
-			if (stringOutputWriter != null) {
-				char[] cs = stringOutputWriter.toCharArray();
-				writerContent = new String(cs);
-			}
-		}
-		s.defaultWriteObject();
-	}
+    public void setContentType(String contentType) {
+        this.contentType = contentType;
+    }
 
-	@Deprecated
-	public void flush(HttpServletResponse response) throws IOException {
-		throw new UnsupportedOperationException();
-	}
+    /**
+     * @return Returns the contentType.
+     */
+    public String getContentType() {
+        return contentType;
+    }
 
-	/**
-	 * Flush used output writer/stream, to fix https://jira.jboss.org/jira/browse/RF-4017
-	 * @param response
-	 * @throws IOException
-	 */
-	public void flush(ExternalContext externalContext) throws IOException {
-		if (filledOutputStream) {
-			OutputStream out = externalContext.getResponseOutputStream();
-			out.flush();
-		} else if (filledOutputWriter) {
-			Writer out = externalContext.getResponseOutputWriter();
-			out.flush();
-		}
-	}
-	
-	public int getContentLength() {
-		if (contentLength == null) {
-			throw new IllegalStateException("Content length hasn't been set yet!");
-		}
-		
-		return contentLength.intValue();
-	}
-	
-	public void setContentLength(int contentLength) {
-		this.contentLength = contentLength;
-	}
+    private void writeObject(java.io.ObjectOutputStream s) throws IOException {
+        if (filledOutputStream) {
+            if (outputStream != null) {
+                content = outputStream.toByteArray();
+            }
+        } else if (filledOutputWriter) {
+            if (stringOutputWriter != null) {
+                char[] cs = stringOutputWriter.toCharArray();
+
+                writerContent = new String(cs);
+            }
+        }
+
+        s.defaultWriteObject();
+    }
+
+    @Deprecated
+    public void flush(HttpServletResponse response) throws IOException {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Flush used output writer/stream, to fix https://jira.jboss.org/jira/browse/RF-4017
+     * @param response
+     * @throws IOException
+     */
+    public void flush(ExternalContext externalContext) throws IOException {
+        if (filledOutputStream) {
+            OutputStream out = externalContext.getResponseOutputStream();
+
+            out.flush();
+        } else if (filledOutputWriter) {
+            Writer out = externalContext.getResponseOutputWriter();
+
+            out.flush();
+        }
+    }
+
+    public int getContentLength() {
+        if (contentLength == null) {
+            throw new IllegalStateException("Content length hasn't been set yet!");
+        }
+
+        return contentLength.intValue();
+    }
+
+    public void setContentLength(int contentLength) {
+        this.contentLength = contentLength;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/FilterServletResponseWrapper.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/FilterServletResponseWrapper.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/FilterServletResponseWrapper.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -32,14 +32,30 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  */
+
+
+
 package org.ajax4jsf.webapp;
 
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.io.FastBufferInputStream;
+import org.ajax4jsf.io.FastBufferOutputStream;
+import org.ajax4jsf.io.FastBufferReader;
+import org.ajax4jsf.io.FastBufferWriter;
+
+import org.richfaces.log.RichfacesLogger;
+
+import org.slf4j.Logger;
+
+import org.xml.sax.InputSource;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintWriter;
 import java.io.Reader;
 import java.io.UnsupportedEncodingException;
 import java.io.Writer;
+
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
@@ -52,15 +68,6 @@
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpServletResponseWrapper;
 
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.io.FastBufferInputStream;
-import org.ajax4jsf.io.FastBufferOutputStream;
-import org.ajax4jsf.io.FastBufferReader;
-import org.ajax4jsf.io.FastBufferWriter;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-import org.xml.sax.InputSource;
-
 /**
  * Base wrapper save JSF page response, for parse to XML with different parsers
  * @author shura (latest modification by $Author: alexsmirnov $)
@@ -68,37 +75,23 @@
  *
  */
 public class FilterServletResponseWrapper extends HttpServletResponseWrapper {
-	
-	private static final Logger log = RichfacesLogger.WEBAPP.getLogger();
-
     public static final String DEFAULT_ENCODING = "UTF-8";
-
-
+    private static final Logger LOG = RichfacesLogger.WEBAPP.getLogger();
+    private int bufferSize = 2048;
     protected FastBufferOutputStream byteStream = null;
-    private ServletOutputStream servletOutputStream;
+    private String charterEncoding = null;
+    private String redirectLocation = null;
     private boolean useStream = false;
-
-    private FastBufferWriter stringWriter;
-    private PrintWriter printWriter;
     private boolean useWriter = false;
-
-    private String contentType;
-    
-    private String charterEncoding = null;
-
+    private boolean useNullStream = false;
     private Map<String, Object> headers = new HashMap<String, Object>();
-    
-    private int bufferSize = 2048;
-    
-    private int contentLength = Integer.MIN_VALUE;
-    
-    private String redirectLocation = null;
-    
-    private boolean useNullStream = false;
-    
     private boolean error = false;
-    
     private List<Cookie> cookies = new ArrayList<Cookie>();
+    private int contentLength = Integer.MIN_VALUE;
+    private String contentType;
+    private PrintWriter printWriter;
+    private ServletOutputStream servletOutputStream;
+    private FastBufferWriter stringWriter;
 
     public FilterServletResponseWrapper(HttpServletResponse response) {
         super(response);
@@ -109,539 +102,625 @@
      * @return stream from saved content
      */
     public InputStream getContentAsStream() {
-    	int length = 0;
-    	FastBufferInputStream result = null;    	
-        String encoding = this.getCharacterEncoding() ;
-///        byte[] content;
+        int length = 0;
+        FastBufferInputStream result = null;
+        String encoding = this.getCharacterEncoding();
+
+//      /        byte[] content;
         if (isUseStream()) {
-        	try {
-				servletOutputStream.flush();
-			} catch (IOException ex) {
-				log.warn(Messages.getMessage(Messages.FLUSH_BUFFERED_STREAM_ERROR), ex);
-			}
-///			content = byteStream.toByteArray();			
-			result = new FastBufferInputStream(byteStream);			
+            try {
+                servletOutputStream.flush();
+            } catch (IOException ex) {
+                LOG.warn(Messages.getMessage(Messages.FLUSH_BUFFERED_STREAM_ERROR), ex);
+            }
+
+//          /         content = byteStream.toByteArray();         
+            result = new FastBufferInputStream(byteStream);
         } else if (isUseWriter()) {
-			printWriter.flush();
-			printWriter.close();
-			length = stringWriter.getLength();
-///			String stringContent = stringWriter.toString();
-			try {
-				FastBufferOutputStream stream = stringWriter.convertToOutputStream(encoding);
-				result = new FastBufferInputStream(stream);
-///				content = stringContent.getBytes(encoding);
-			} catch (UnsupportedEncodingException e) {
-				// TODO Auto-generated catch block
-				log.warn(Messages.getMessage(Messages.UNSUPPORTED_ENCODING_WARNING));
-				FastBufferOutputStream stream = stringWriter.convertToOutputStream();
-				result = new FastBufferInputStream(stream);
-///				content = stringContent.getBytes();
-			}
-		} else  {
-            if (log.isDebugEnabled()) {
-            log.debug(Messages.getMessage(Messages.NO_WRITER_CALLED_INFO));
+            printWriter.flush();
+            printWriter.close();
+            length = stringWriter.getLength();
+
+//          /         String stringContent = stringWriter.toString();
+            try {
+                FastBufferOutputStream stream = stringWriter.convertToOutputStream(encoding);
+
+                result = new FastBufferInputStream(stream);
+
+//              /             content = stringContent.getBytes(encoding);
+            } catch (UnsupportedEncodingException e) {
+
+                // TODO Auto-generated catch block
+                LOG.warn(Messages.getMessage(Messages.UNSUPPORTED_ENCODING_WARNING));
+
+                FastBufferOutputStream stream = stringWriter.convertToOutputStream();
+
+                result = new FastBufferInputStream(stream);
+
+//              /             content = stringContent.getBytes();
             }
+        } else {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.NO_WRITER_CALLED_INFO));
+            }
+
             return null;
-        }   	
-///            if (content.length > 0) {
-                if (length > 0) {
-                if (log.isDebugEnabled()) {
-                    log.debug(Messages.getMessage(Messages.PARSE_XML_DOCUMENT_INFO));
-//                    try {
-//						log.debug(new String(content, encoding));
-//					} catch (UnsupportedEncodingException e) {
-//					}
-                }
+        }
+
+//      /            if (content.length > 0) {
+        if (length > 0) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.PARSE_XML_DOCUMENT_INFO));
+
+//              try {
+//                LOG.debug(new String(content, encoding));
+//                  }catch (UnsupportedEncodingException e) {
+//                  }
             }
-                return result;
-///            return new ByteArrayInputStream(content);
+        }
+
+        return result;
+
+//      /            return new ByteArrayInputStream(content);
     }
-    
+
     /**
      * Convert saved context to stream for parsing
      * @return stream from saved content
      */
     public Reader getContentAsReader() {
-    	FastBufferReader result = null;    	
-        String encoding = this.getCharacterEncoding() ;
-///        String content;
+        FastBufferReader result = null;
+        String encoding = this.getCharacterEncoding();
+
+//      /        String content;
         if (isUseWriter()) {
-			printWriter.flush();
-			printWriter.close();
-			result = new FastBufferReader(stringWriter);
-///			content = stringWriter.toString();
-		} else if (isUseStream()) {
-        	try {
-				servletOutputStream.flush();
-			} catch (IOException ex) {
-				log.warn(Messages.getMessage(Messages.FLUSH_BUFFERED_STREAM_ERROR), ex);
-			}
-			try {
-				FastBufferWriter writer = byteStream.convertToWriter(encoding);
-				result = new FastBufferReader(writer);
-///				content = byteStream.toString(encoding);
-			} catch (UnsupportedEncodingException e) {
-				log.warn(Messages.getMessage(Messages.UNSUPPORTED_ENCODING_WARNING_2), e);
-				FastBufferWriter writer = byteStream.convertToWriter();
-				result = new FastBufferReader(writer);
-///				content = byteStream.toString();
-			}
-        } else  {
-            if (log.isDebugEnabled()) {
-                log.debug(Messages.getMessage(Messages.NO_WRITER_CALLED_INFO));
-                }
-                return null;
-        }   	
-//            if (content.length() > 0) {
-//                if (log.isDebugEnabled()) {
-//                    log.debug("XML document to parse in filter, return as Reader: ");
-//						log.debug(content);
-//                }
-//            }
-///            return new StringReader(content);
-        return result;
-    }
-    
-    public PrintWriter getWriter() throws IOException {
-    	if (useStream) {
-			throw new IllegalStateException(Messages.getMessage(Messages.NO_WRITER_POSSIBLE_ERROR));
-		}
-        if (printWriter == null) {
-            if(log.isDebugEnabled()) {
-            	log.debug(Messages.getMessage(Messages.CREATE_WRITER_INFO));
+            printWriter.flush();
+            printWriter.close();
+            result = new FastBufferReader(stringWriter);
+
+//          /         content = stringWriter.toString();
+        } else if (isUseStream()) {
+            try {
+                servletOutputStream.flush();
+            } catch (IOException ex) {
+                LOG.warn(Messages.getMessage(Messages.FLUSH_BUFFERED_STREAM_ERROR), ex);
             }
-            printWriter = new PrintWriter(new ServletStringWriter());
-            useWriter = true;
-        }
-        return printWriter;
-    }
 
-    public ServletOutputStream getOutputStream() throws IOException {
-    	if (useWriter) {
-    		if (isUseNullStream()) {
-				return new NullServletOutputStream();
-			}
-			throw new IllegalStateException(Messages.getMessage(Messages.NO_STREAM_POSSIBLE_ERROR));
-		}
-        if (servletOutputStream == null) {
-//            byteStream = new ByteArrayOutputStream();
-            servletOutputStream = new ByteArrayServletOutputStream();
-        }
-        if(log.isDebugEnabled()) {
-        	log.debug(Messages.getMessage(Messages.CREATE_STREAM_INFO));
-        }
-        useStream = true;
-        return servletOutputStream;
-    }
+            try {
+                FastBufferWriter writer = byteStream.convertToWriter(encoding);
 
+                result = new FastBufferReader(writer);
 
-    public class ByteArrayServletOutputStream extends ServletOutputStream {
-    	
-    	private boolean opened = true;
+//              /             content = byteStream.toString(encoding);
+            } catch (UnsupportedEncodingException e) {
+                LOG.warn(Messages.getMessage(Messages.UNSUPPORTED_ENCODING_WARNING_2), e);
 
-        /* (non-Javadoc)
-		 * @see java.io.OutputStream#close()
-		 */
-		public void close() throws IOException {
-			flush();
-			opened=false;
-		}
-		
+                FastBufferWriter writer = byteStream.convertToWriter();
 
-		/* (non-Javadoc)
-		 * @see java.io.OutputStream#write(byte[])
-		 */
-		public void write(byte[] b) throws IOException {
-			// TODO Auto-generated method stub
-			if (opened) {
-				byteStream.write(b);
-			}
-		}
+                result = new FastBufferReader(writer);
 
+//              /             content = byteStream.toString();
+            }
+        } else {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.NO_WRITER_CALLED_INFO));
+            }
 
-		public ByteArrayServletOutputStream() {
-            byteStream = new FastBufferOutputStream(bufferSize);
+            return null;
         }
 
-        public void write(int b) throws IOException {
-            if (opened) {
-				byteStream.write(b);
-			}
+//      if (content.length() > 0) {
+//          if (LOG.isDebugEnabled()) {
+//              LOG.debug("XML document to parse in filter, return as Reader: ");
+//                LOG.debug(content);
+//          }
+//      }
+///      return new StringReader(content);
+        return result;
+    }
+
+    public PrintWriter getWriter() throws IOException {
+        if (useStream) {
+            throw new IllegalStateException(Messages.getMessage(Messages.NO_WRITER_POSSIBLE_ERROR));
         }
 
-		/* (non-Javadoc)
-		 * @see java.io.OutputStream#write(byte[], int, int)
-		 */
-		public void write(byte[] b, int off, int len) throws IOException {
-			if (opened) {
-				byteStream.write(b, off, len);
-			}
-		}
-    }
-    
-    public static  class NullServletOutputStream extends ServletOutputStream {
+        if (printWriter == null) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.CREATE_WRITER_INFO));
+            }
 
-    	
-		/* (non-Javadoc)
-		 * @see java.io.OutputStream#write(byte[], int, int)
-		 */
-		public void write(byte[] b, int off, int len) throws IOException {
-			// this-is null stream, do nothing !
-		}
+            printWriter = new PrintWriter(new ServletStringWriter());
+            useWriter = true;
+        }
 
-		/* (non-Javadoc)
-		 * @see java.io.OutputStream#write(byte[])
-		 */
-		public void write(byte[] b) throws IOException {
-			// this-is null stream, do nothing !
-		}
-
-		public void write(int b) throws IOException {
-			// this-is null stream, do nothing !
-			
-		}
-    	
+        return printWriter;
     }
-    
-    public class ServletStringWriter extends Writer {
 
-    	private boolean opened = true;
+    public ServletOutputStream getOutputStream() throws IOException {
+        if (useWriter) {
+            if (isUseNullStream()) {
+                return new NullServletOutputStream();
+            }
 
-    	public ServletStringWriter() {
-			super();
-			stringWriter = new FastBufferWriter(bufferSize); 
-		}
+            throw new IllegalStateException(Messages.getMessage(Messages.NO_STREAM_POSSIBLE_ERROR));
+        }
 
-		public void write(char[] cbuf, int off, int len) throws IOException {
-			if (opened) {
-				stringWriter.write(cbuf, off, len); 
-			}			
-		}
+        if (servletOutputStream == null) {
 
-		/* (non-Javadoc)
-		 * @see java.io.Writer#write(char[])
-		 */
-		public void write(char[] cbuf) throws IOException {
-			// TODO Auto-generated method stub
-			if (opened) {
-				stringWriter.write(cbuf);
-			}
-		}
+//          byteStream = new ByteArrayOutputStream();
+            servletOutputStream = new ByteArrayServletOutputStream();
+        }
 
-		/* (non-Javadoc)
-		 * @see java.io.Writer#write(int)
-		 */
-		public void write(int c) throws IOException {
-			// TODO Auto-generated method stub
-			if (opened) {
-				stringWriter.write(c);
-			}
-		}
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(Messages.getMessage(Messages.CREATE_STREAM_INFO));
+        }
 
-		public void flush() throws IOException {
-			stringWriter.flush();
-		}
-		
-		public void close() throws IOException {
-			stringWriter.close();
-			opened = false;
-		}
-    	
+        useStream = true;
+
+        return servletOutputStream;
     }
 
-//    public boolean isCommitted() {
-//	    // NOTE: What makes sense here?
-//	    return false;
-//	}
+//  public boolean isCommitted() {
+//    // NOTE: What makes sense here?
+//    return false;
+//  }
 
-	/**
+    /**
      * Return a charset from a content-type.
      */
     public static String getContentTypeCharset(String contentType) {
-        if (contentType == null)
+        if (contentType == null) {
             return null;
+        }
+
         int semicolumnIndex = contentType.indexOf(";");
-        if (semicolumnIndex == -1)
+
+        if (semicolumnIndex == -1) {
             return null;
+        }
+
         int charsetIndex = contentType.indexOf("charset=", semicolumnIndex);
-        if (charsetIndex == -1)
+
+        if (charsetIndex == -1) {
             return null;
+        }
+
         // FIXME: There may be other attributes after charset, right?
         String afterCharset = contentType.substring(charsetIndex + 8);
+
         afterCharset = afterCharset.replace('"', ' ');
+
         return afterCharset.trim();
     }
-    /* (non-Javadoc)
+
+    /*
+     *  (non-Javadoc)
      * @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String, java.lang.String)
      */
     public void addHeader(String name, String value) {
-    	if("Content-Type".equals(name)){
-    		setContentType(value);
-    	} else {
-    		this.headers.put(name,value);
-    		super.addHeader(name, value);
-    	}
+        if ("Content-Type".equals(name)) {
+            setContentType(value);
+        } else {
+            this.headers.put(name, value);
+            super.addHeader(name, value);
+        }
     }
-    /* (non-Javadoc)
+
+    /*
+     *  (non-Javadoc)
      * @see javax.servlet.http.HttpServletResponse#setHeader(java.lang.String, java.lang.String)
      */
     public void setHeader(String name, String value) {
-    	// HACK - weblogic do not use setContentType, instead directly set header !
-    	if("Content-Type".equals(name)){
-    		setContentType(value);
-    	} else {
-    		this.headers.put(name,value);
-    		super.setHeader(name, value);
-    	}
+
+        // HACK - weblogic do not use setContentType, instead directly set header !
+        if ("Content-Type".equals(name)) {
+            setContentType(value);
+        } else {
+            this.headers.put(name, value);
+            super.setHeader(name, value);
+        }
     }
-    
-    public Map<String, Object> getHeaders(){
+
+    public Map<String, Object> getHeaders() {
         return this.headers;
     }
-    /* (non-Javadoc)
+
+    /*
+     *  (non-Javadoc)
      * @see javax.servlet.ServletResponse#getCharacterEncoding()
      */
     public String getCharacterEncoding() {
-//        return this.charterEncoding;
-         if (null != this.charterEncoding) {
-			return this.charterEncoding;
-		} else {
-		 // For cases of implicit setting
-         return super.getCharacterEncoding();
-		}
+
+//      return this.charterEncoding;
+        if (null != this.charterEncoding) {
+            return this.charterEncoding;
+        } else {
+
+            // For cases of implicit setting
+            return super.getCharacterEncoding();
+        }
     }
-    /* (non-Javadoc)
+
+    /*
+     *  (non-Javadoc)
      * @see javax.servlet.ServletResponse#setCharacterEncoding(java.lang.String)
      */
     public void setCharacterEncoding(String charset) {
         this.charterEncoding = charset;
-        //super.setCharacterEncoding(charset);
+
+        // super.setCharacterEncoding(charset);
     }
+
     public void setContentType(String type) {
         String contentTypeCharset = getContentTypeCharset(type);
-		if (null != contentTypeCharset) {
-			this.charterEncoding = contentTypeCharset;
-		}
+
+        if (null != contentTypeCharset) {
+            this.charterEncoding = contentTypeCharset;
+        }
+
         this.contentType = type;
-//        super.setContentType(type);
+
+//      super.setContentType(type);
     }
+
     public void setLocale(Locale loc) {
         super.setLocale(loc);
     }
 
     public String getContentType() {
-		return contentType;
-	}
-    
-	/**
-	 * Send buffered content directly to output stream.
-	 * @param outputStream
-	 * @throws IOException 
-	 */
-	public void sendContent(ServletOutputStream outputStream) throws IOException {
-		if(getContentLength() >0 ){
-			super.setContentLength(getContentLength());
-		}
+        return contentType;
+    }
+
+    /**
+     * Send buffered content directly to output stream.
+     * @param outputStream
+     * @throws IOException
+     */
+    public void sendContent(ServletOutputStream outputStream) throws IOException {
+        if (getContentLength() > 0) {
+            super.setContentLength(getContentLength());
+        }
+
         if (isUseWriter()) {
-			printWriter.flush();
-			printWriter.close();
-			stringWriter.printTo(outputStream);
-///			outputStream.print(stringWriter.toString());
-		} else if (isUseStream()) {
-        	try {
-				servletOutputStream.flush();
-			} catch (IOException ex) {
-				log.warn(Messages.getMessage(Messages.FLUSH_BUFFERED_STREAM_ERROR), ex);
-			}
-        	byteStream.writeTo(outputStream);
+            printWriter.flush();
+            printWriter.close();
+            stringWriter.printTo(outputStream);
+
+//          /         outputStream.print(stringWriter.toString());
+        } else if (isUseStream()) {
+            try {
+                servletOutputStream.flush();
+            } catch (IOException ex) {
+                LOG.warn(Messages.getMessage(Messages.FLUSH_BUFFERED_STREAM_ERROR), ex);
+            }
+
+            byteStream.writeTo(outputStream);
         }
-	}
+    }
 
-	/**
-	 * Send buffered content directly to output stream.
-	 * @param outputStream
-	 * @throws IOException 
-	 */
-	public void sendContent(Writer output) throws IOException {
-		if(getContentLength() >0 ){
-			super.setContentLength(getContentLength());
-		}
+    /**
+     * Send buffered content directly to output stream.
+     * @param outputStream
+     * @throws IOException
+     */
+    public void sendContent(Writer output) throws IOException {
+        if (getContentLength() > 0) {
+            super.setContentLength(getContentLength());
+        }
+
         if (isUseWriter()) {
-			printWriter.flush();
-			printWriter.close();
-			stringWriter.writeTo(output);
-///			outputStream.print(stringWriter.toString());
-		} else if (isUseStream()) {
-        	try {
-				servletOutputStream.flush();
-			} catch (IOException ex) {
-				log.warn(Messages.getMessage(Messages.FLUSH_BUFFERED_STREAM_ERROR), ex);
-			}
-        	byteStream.writeTo(output,getCharacterEncoding());
+            printWriter.flush();
+            printWriter.close();
+            stringWriter.writeTo(output);
+
+//          /         outputStream.print(stringWriter.toString());
+        } else if (isUseStream()) {
+            try {
+                servletOutputStream.flush();
+            } catch (IOException ex) {
+                LOG.warn(Messages.getMessage(Messages.FLUSH_BUFFERED_STREAM_ERROR), ex);
+            }
+
+            byteStream.writeTo(output, getCharacterEncoding());
         }
-	}
-	/**
-	 * @return Returns the useStream.
-	 */
-	public boolean isUseStream() {
-		return this.useStream;
-	}
+    }
 
-	/**
-	 * @return Returns the useWriter.
-	 */
-	public boolean isUseWriter() {
-		return this.useWriter;
-	}
+    /**
+     * @return Returns the useStream.
+     */
+    public boolean isUseStream() {
+        return this.useStream;
+    }
 
-	/**
-	 * @return
-	 * @throws RuntimeException
-	 */
-	public InputSource getContentAsInputSource() throws RuntimeException {
-		// Create InputSource
-		InputSource inputSource = null;
-		String encoding = this.getCharacterEncoding() ;
-		if(isUseWriter()) {
-			inputSource = new InputSource(getContentAsReader());
-		} else if(isUseStream()) {
-		inputSource = new InputSource(getContentAsStream());
-		        if (encoding != null)
-		            inputSource.setEncoding(encoding);
-		} else {
-            if (log.isDebugEnabled()) {
-                log.debug(Messages.getMessage(Messages.NO_WRITER_CALLED_INFO));
-                }
-                return null;
-		}
-		return inputSource;
-	}
+    /**
+     * @return Returns the useWriter.
+     */
+    public boolean isUseWriter() {
+        return this.useWriter;
+    }
 
-	/* (non-Javadoc)
-	 * @see javax.servlet.ServletResponseWrapper#flushBuffer()
-	 */
-	public void flushBuffer() throws IOException {
-		if(isUseStream()){
-			servletOutputStream.flush();
-		} else if(isUseWriter()){
-			printWriter.flush();
-		}
-	}
+    /**
+     * @return
+     */
+    public InputSource getContentAsInputSource() {
 
-	/* (non-Javadoc)
-	 * @see javax.servlet.ServletResponseWrapper#getBufferSize()
-	 */
-	public int getBufferSize() {
-		// TODO Auto-generated method stub
-		return bufferSize;
-	}
+        // Create InputSource
+        InputSource inputSource = null;
+        String encoding = this.getCharacterEncoding();
 
-	/* (non-Javadoc)
-	 * @see javax.servlet.ServletResponseWrapper#resetBuffer()
-	 */
-	public void resetBuffer() {
-		this.printWriter = null;
-		this.stringWriter = null;
-		this.servletOutputStream = null;
-		this.byteStream = null;
-		this.useStream = false;
-		this.useWriter = false;
-	}
+        if (isUseWriter()) {
+            inputSource = new InputSource(getContentAsReader());
+        } else if (isUseStream()) {
+            inputSource = new InputSource(getContentAsStream());
 
-	/* (non-Javadoc)
-	 * @see javax.servlet.ServletResponseWrapper#setBufferSize(int)
-	 */
-	public void setBufferSize(int arg0) {
-		// TODO Auto-generated method stub
-		bufferSize = arg0;
-	}
+            if (encoding != null) {
+                inputSource.setEncoding(encoding);
+            }
+        } else {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(Messages.getMessage(Messages.NO_WRITER_CALLED_INFO));
+            }
 
-	/* (non-Javadoc)
-	 * @see javax.servlet.ServletResponseWrapper#reset()
-	 */
-	public void reset() {
-		// TODO Auto-generated method stub
-		this.resetBuffer();
-		this.headers = new HashMap<String, Object>();
-		this.contentType=null;
-		this.charterEncoding=null;
-		super.reset();
-	}
+            return null;
+        }
 
-	/**
-	 * @return Returns the contentLength.
-	 */
-	public int getContentLength() {
-		return contentLength;
-	}
+        return inputSource;
+    }
 
-	/**
-	 * @param contentLength The contentLength to set.
-	 */
-	public void setContentLength(int contentLength) {
-		this.contentLength = contentLength;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.servlet.ServletResponseWrapper#flushBuffer()
+     */
+    public void flushBuffer() throws IOException {
+        if (isUseStream()) {
+            servletOutputStream.flush();
+        } else if (isUseWriter()) {
+            printWriter.flush();
+        }
+    }
 
-	/**
-	 * Parse saved content to output stream ( and store as Dom Document tree )
-	 * @param out stream to send parsed content, if null - only build dom tree.
-	 * @return parsed document as dom tree.
-	 * @throws IOException 
-	 */
-	public void parseContent(Writer out,HtmlParser parser) throws IOException {
-		parser.setInputEncoding(getCharacterEncoding());
-		if (isUseWriter()) {
-			parser.parseHtml(getContentAsReader(),out);
-		} else if(isUseStream()){
-			parser.parseHtml(getContentAsStream(),out);
-		}
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.servlet.ServletResponseWrapper#getBufferSize()
+     */
+    public int getBufferSize() {
 
-	public void sendRedirect(String arg0) throws IOException {
-		// TODO Auto-generated method stub
-		this.redirectLocation = arg0;
-	}
+        // TODO Auto-generated method stub
+        return bufferSize;
+    }
 
-	public String getRedirectLocation() {
-		return redirectLocation;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.servlet.ServletResponseWrapper#resetBuffer()
+     */
+    public void resetBuffer() {
+        this.printWriter = null;
+        this.stringWriter = null;
+        this.servletOutputStream = null;
+        this.byteStream = null;
+        this.useStream = false;
+        this.useWriter = false;
+    }
 
-	/**
-	 * @return the useNullStream
-	 */
-	public boolean isUseNullStream() {
-		return useNullStream;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.servlet.ServletResponseWrapper#setBufferSize(int)
+     */
+    public void setBufferSize(int arg0) {
 
-	/**
-	 * @param useNullStream the useNullStream to set
-	 */
-	public void setUseNullStream(boolean useNullStream) {
-		this.useNullStream = useNullStream;
-	}
-	
-	
-	
-	public void addCookie(Cookie cookie) {
-	    cookies.add(cookie);
-	    super.addCookie(cookie);
-	}
-	
-	public Collection<Cookie> getCookies() {
-	    return cookies;
-	}
+        // TODO Auto-generated method stub
+        bufferSize = arg0;
+    }
 
-	public void sendError(int sc) throws IOException {
-		this.error = true;
-		super.sendError(sc);
-	}
-	
-	public void sendError(int sc, String msg) throws IOException {
-		this.error = true;
-		super.sendError(sc, msg);
-	}
-	
-	public boolean isError() {
-		return error;
-	}
+    /*
+     *  (non-Javadoc)
+     * @see javax.servlet.ServletResponseWrapper#reset()
+     */
+    public void reset() {
+
+        // TODO Auto-generated method stub
+        this.resetBuffer();
+        this.headers = new HashMap<String, Object>();
+        this.contentType = null;
+        this.charterEncoding = null;
+        super.reset();
+    }
+
+    /**
+     * @return Returns the contentLength.
+     */
+    public int getContentLength() {
+        return contentLength;
+    }
+
+    /**
+     * @param contentLength The contentLength to set.
+     */
+    public void setContentLength(int contentLength) {
+        this.contentLength = contentLength;
+    }
+
+    /**
+     * Parse saved content to output stream ( and store as Dom Document tree )
+     * @param out stream to send parsed content, if null - only build dom tree.
+     * @return parsed document as dom tree.
+     * @throws IOException
+     */
+    public void parseContent(Writer out, HtmlParser parser) throws IOException {
+        parser.setInputEncoding(getCharacterEncoding());
+
+        if (isUseWriter()) {
+            parser.parseHtml(getContentAsReader(), out);
+        } else if (isUseStream()) {
+            parser.parseHtml(getContentAsStream(), out);
+        }
+    }
+
+    public void sendRedirect(String arg0) throws IOException {
+
+        // TODO Auto-generated method stub
+        this.redirectLocation = arg0;
+    }
+
+    public String getRedirectLocation() {
+        return redirectLocation;
+    }
+
+    /**
+     * @return the useNullStream
+     */
+    public boolean isUseNullStream() {
+        return useNullStream;
+    }
+
+    /**
+     * @param useNullStream the useNullStream to set
+     */
+    public void setUseNullStream(boolean useNullStream) {
+        this.useNullStream = useNullStream;
+    }
+
+    public Collection<Cookie> getCookies() {
+        return cookies;
+    }
+
+    public void addCookie(Cookie cookie) {
+        cookies.add(cookie);
+        super.addCookie(cookie);
+    }
+
+    public void sendError(int sc) throws IOException {
+        this.error = true;
+        super.sendError(sc);
+    }
+
+    public void sendError(int sc, String msg) throws IOException {
+        this.error = true;
+        super.sendError(sc, msg);
+    }
+
+    public boolean isError() {
+        return error;
+    }
+
+    public class ByteArrayServletOutputStream extends ServletOutputStream {
+        private boolean opened = true;
+
+        public ByteArrayServletOutputStream() {
+            byteStream = new FastBufferOutputStream(bufferSize);
+        }
+
+        /*
+         *  (non-Javadoc)
+         * @see java.io.OutputStream#close()
+         */
+        public void close() throws IOException {
+            flush();
+            opened = false;
+        }
+
+        /*
+         *  (non-Javadoc)
+         * @see java.io.OutputStream#write(byte[])
+         */
+        public void write(byte[] b) throws IOException {
+
+            // TODO Auto-generated method stub
+            if (opened) {
+                byteStream.write(b);
+            }
+        }
+
+        public void write(int b) throws IOException {
+            if (opened) {
+                byteStream.write(b);
+            }
+        }
+
+        /*
+         *  (non-Javadoc)
+         * @see java.io.OutputStream#write(byte[], int, int)
+         */
+        public void write(byte[] b, int off, int len) throws IOException {
+            if (opened) {
+                byteStream.write(b, off, len);
+            }
+        }
+    }
+
+
+    public static class NullServletOutputStream extends ServletOutputStream {
+
+        /*
+         *  (non-Javadoc)
+         * @see java.io.OutputStream#write(byte[], int, int)
+         */
+        public void write(byte[] b, int off, int len) throws IOException {
+
+            // this-is null stream, do nothing !
+        }
+
+        /*
+         *  (non-Javadoc)
+         * @see java.io.OutputStream#write(byte[])
+         */
+        public void write(byte[] b) throws IOException {
+
+            // this-is null stream, do nothing !
+        }
+
+        public void write(int b) throws IOException {
+
+            // this-is null stream, do nothing !
+        }
+    }
+
+
+    public class ServletStringWriter extends Writer {
+        private boolean opened = true;
+
+        public ServletStringWriter() {
+            super();
+            stringWriter = new FastBufferWriter(bufferSize);
+        }
+
+        public void write(char[] cbuf, int off, int len) throws IOException {
+            if (opened) {
+                stringWriter.write(cbuf, off, len);
+            }
+        }
+
+        /*
+         *  (non-Javadoc)
+         * @see java.io.Writer#write(char[])
+         */
+        public void write(char[] cbuf) throws IOException {
+
+            // TODO Auto-generated method stub
+            if (opened) {
+                stringWriter.write(cbuf);
+            }
+        }
+
+        /*
+         *  (non-Javadoc)
+         * @see java.io.Writer#write(int)
+         */
+        public void write(int c) throws IOException {
+
+            // TODO Auto-generated method stub
+            if (opened) {
+                stringWriter.write(c);
+            }
+        }
+
+        public void flush() throws IOException {
+            stringWriter.flush();
+        }
+
+        public void close() throws IOException {
+            stringWriter.close();
+            opened = false;
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/HtmlParser.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/HtmlParser.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/HtmlParser.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,46 +19,46 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp;
 
+import org.w3c.dom.Node;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.Reader;
 import java.io.Writer;
 
-import org.w3c.dom.Node;
-
 public interface HtmlParser {
+    public abstract void parseHtml(InputStream input, Writer output) throws IOException;
 
-	public abstract void parseHtml(InputStream input, Writer output)
-			throws IOException;
+    public abstract void parseHtml(Reader input, Writer output) throws IOException;
 
-	public abstract void parseHtml(Reader input, Writer output)
-	throws IOException;
-	/**
-	 * @param encoding
-	 */
-	public abstract void setInputEncoding(String encoding);
+    /**
+     * @param encoding
+     */
+    public abstract void setInputEncoding(String encoding);
 
-	/**
-	 * @param encoding
-	 */
-	public abstract void setOutputEncoding(String encoding);
-	/**
-	 * Setup, must tidy move style etc. elements to head or not.
-	 * @param move
-	 */
-	public abstract void setMoveElements(boolean move);
+    /**
+     * @param encoding
+     */
+    public abstract void setOutputEncoding(String encoding);
 
-	public abstract void setHeadNodes(Node[] events);
+    /**
+     * Setup, must tidy move style etc. elements to head or not.
+     * @param move
+     */
+    public abstract void setMoveElements(boolean move);
 
-	public abstract void setDoctype(String doctype);
+    public abstract void setHeadNodes(Node[] events);
 
-	/**
-	 * @param viewState The viewState to set.
-	 */
-	public abstract void setViewState(String viewState);
+    public abstract void setDoctype(String doctype);
 
-	public abstract boolean setMime(String mimeType);
+    /**
+     * @param viewState The viewState to set.
+     */
+    public abstract void setViewState(String viewState);
 
-}
\ No newline at end of file
+    public abstract boolean setMime(String mimeType);
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/ParserConfig.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/ParserConfig.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/ParserConfig.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,75 +18,77 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.webapp;
 
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 abstract class ParserConfig {
+    private static final Pattern[] ALL_VIEWS_PATTERN = {Pattern.compile(".*")};
+    private static final Pattern SEPARATOR_PATTERN = Pattern.compile("\\s*,\\s*");
+    private Pattern[] patterns = ALL_VIEWS_PATTERN;
+    private ParserConfig next;
 
-	private static final Pattern[] ALL_VIEWS_PATTERN = { Pattern.compile(".*") };
+    protected abstract HtmlParser createParser(String mimetype);
 
-	private static final Pattern SEPARATOR_PATTERN = Pattern
-			.compile("\\s*,\\s*");
+    boolean storeParser(HtmlParser parser) {
+        return false;
+    }
 
-	private Pattern[] patterns = ALL_VIEWS_PATTERN;
+    HtmlParser getParser(String viewId, String mimetype) {
+        HtmlParser result = null;
 
-	private ParserConfig next;
+        if (null != viewId) {
+            for (int i = 0; (i < patterns.length) && (null == result); i++) {
+                Matcher matcher = patterns[i].matcher(viewId);
 
-	protected abstract HtmlParser createParser(String mimetype);
+                if (matcher.matches()) {
+                    result = createParser(mimetype);
+                }
+            }
+        }
 
-	boolean storeParser(HtmlParser parser) {
-		return false;
-	}
+        if (null == result) {
+            if (null != next) {
+                result = next.getParser(viewId, mimetype);
+            } else {
+                result = createParser(mimetype);
+            }
+        }
 
-	HtmlParser getParser(String viewId, String mimetype) {
-		HtmlParser result = null;
-		if (null != viewId) {
-			for (int i = 0; i < patterns.length && null == result; i++) {
-				Matcher matcher = patterns[i].matcher(viewId);
-				if (matcher.matches()) {
-					result = createParser(mimetype);
-				}
-			}
+        return result;
+    }
 
-		}
-		if (null == result) {
-			if (null != next) {
-				result = next.getParser(viewId, mimetype);
-			} else {
-				result = createParser(mimetype);
-			}
-		}
-		return result;
-	}
+    public void reuseParser(HtmlParser parser) {
+        if (!storeParser(parser) && (null != next)) {
+            next.reuseParser(parser);
+        }
+    }
 
-	public void reuseParser(HtmlParser parser) {
-		if (!storeParser(parser) && null != next) {
-			next.reuseParser(parser);
-		}
-	}
+    public ParserConfig getNext() {
+        return next;
+    }
 
-	public ParserConfig getNext() {
-		return next;
-	}
+    public void setNext(ParserConfig next) {
+        this.next = next;
+    }
 
-	public void setNext(ParserConfig next) {
-		this.next = next;
-	}
+    public void setPatterns(String patternsString) {
+        if (null != patternsString) {
+            String[] split = SEPARATOR_PATTERN.split(patternsString);
 
-	public void setPatterns(String patternsString) {
-		if (null != patternsString) {
-			String[] split = SEPARATOR_PATTERN.split(patternsString);
-			patterns = new Pattern[split.length];
-			for (int i = 0; i < split.length; i++) {
-				patterns[i] = Pattern.compile(split[i].trim());
-			}
-		}
-	}
+            patterns = new Pattern[split.length];
 
-	public Pattern[] getPatterns() {
-		return patterns;
-	}
+            for (int i = 0; i < split.length; i++) {
+                patterns[i] = Pattern.compile(split[i].trim());
+            }
+        }
+    }
 
-}
\ No newline at end of file
+    public Pattern[] getPatterns() {
+        return patterns;
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/PollEventsManager.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/PollEventsManager.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/PollEventsManager.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,9 +18,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.webapp;
 
 import java.io.Serializable;
+
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
@@ -30,37 +34,34 @@
  * @author asmirnov
  *
  */
+
 //TODO: deprecate
 public class PollEventsManager implements Serializable {
+    public static final String EVENTS_MANAGER_KEY = PollEventsManager.class.getName();
+    private static final long serialVersionUID = -6257285396790747665L;
 
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -6257285396790747665L;
+    // TODO should use cache - push is application-scoped, not session-scoped
+    private ConcurrentMap<String, PushEventsCounter> counters = new ConcurrentHashMap<String, PushEventsCounter>();
 
-	public static final String EVENTS_MANAGER_KEY = PollEventsManager.class.getName();
+    public void init(ServletContext servletContext) {
+        servletContext.setAttribute(EVENTS_MANAGER_KEY, this);
+    }
 
-	//TODO should use cache - push is application-scoped, not session-scoped
-	private ConcurrentMap<String, PushEventsCounter> counters = new ConcurrentHashMap<String, PushEventsCounter>();
-	
-	public void init(ServletContext servletContext) {
-		servletContext.setAttribute(EVENTS_MANAGER_KEY, this);
-	}
+    public PushEventsCounter getListener(String key) {
+        PushEventsCounter counter = counters.get(key);
 
-	public PushEventsCounter getListener(String key){
-		PushEventsCounter counter = counters.get(key);
-		if (counter != null) {
-			return counter;
-		} else {
-			counter = new PushEventsCounter();
+        if (counter != null) {
+            return counter;
+        } else {
+            counter = new PushEventsCounter();
 
-			PushEventsCounter oldCounter = counters.putIfAbsent(key, counter);
-			if (oldCounter != null) {
-				return oldCounter;
-			} else {
-				return counter;
-			}
-		}
-	}
+            PushEventsCounter oldCounter = counters.putIfAbsent(key, counter);
 
+            if (oldCounter != null) {
+                return oldCounter;
+            } else {
+                return counter;
+            }
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/PushEventsCounter.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/PushEventsCounter.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/PushEventsCounter.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,23 +18,27 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.webapp;
 
+import org.ajax4jsf.event.PushEventListener;
+
 import java.io.Serializable;
+
 import java.util.EventObject;
 
-import org.ajax4jsf.event.PushEventListener;
+public class PushEventsCounter implements PushEventListener, Serializable {
 
-public class PushEventsCounter implements PushEventListener,Serializable {
-    
     /**
-     * 
+     *
      */
     private static final long serialVersionUID = 4060284352186710009L;
     private volatile boolean performed = false;
 
     public void onEvent(EventObject event) {
-	performed = true;
+        performed = true;
     }
 
     /**
@@ -49,6 +53,4 @@
     public void processed() {
         this.performed = false;
     }
-
-    
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/ServletStreamWriter.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/ServletStreamWriter.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/ServletStreamWriter.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp;
 
 import java.io.IOException;
@@ -34,78 +36,88 @@
  *
  */
 final class ServletStreamWriter extends ServletOutputStream {
-	
-	private PrintWriter _writer;
-	
-	private byte[] buff = new byte[1024];
-	
-	private int point = 0;
+    private byte[] buff = new byte[1024];
+    private int point = 0;
+    private String charset;
+    private PrintWriter writer;
 
-	private String _charset;
+    public ServletStreamWriter(PrintWriter writer) {
+        this.writer = writer;
+    }
 
-	/**
-	 * @param writer
-	 * @param charset
-	 */
-	public ServletStreamWriter(PrintWriter writer, String charset) {
-		super();
-		// TODO Auto-generated constructor stub
-		_writer = writer;
-		_charset = charset;
-	}
+    /**
+     * @param writer
+     * @param charset
+     */
+    public ServletStreamWriter(PrintWriter writer, String charset) {
+        super();
 
-	public ServletStreamWriter(PrintWriter writer) {
-		this._writer = writer;
-	}
+        // TODO Auto-generated constructor stub
+        this.writer = writer;
+        this.charset = charset;
+    }
 
-	public void write(int b) throws IOException {
-		buff[point++]=(byte) b;
-		if(point==buff.length){
-			point = 0;
-			String string = null==_charset?new String(buff):new String(buff,_charset);
-			_writer.write(string);
-		}
-	}
+    @Override
+    public void write(int b) throws IOException {
+        buff[point++] = (byte) b;
 
-	/**
-	 * @return Returns the charset.
-	 */
-	public String getCharset() {
-		return _charset;
-	}
+        if (point == buff.length) {
+            point = 0;
 
-	/**
-	 * @param charset The charset to set.
-	 */
-	public void setCharset(String charset) {
-		_charset = charset;
-	}
+            String string = (null == charset) ? new String(buff) : new String(buff, charset);
 
-	/* (non-Javadoc)
-	 * @see java.io.OutputStream#close()
-	 */
-	public void close() throws IOException {
-		this.flush();
-		super.close();
-	}
+            writer.write(string);
+        }
+    }
 
-	/* (non-Javadoc)
-	 * @see java.io.OutputStream#flush()
-	 */
-	public void flush() throws IOException {
-		if(point>0){
-			String string = null==_charset?new String(buff,0,point):new String(buff,0,point,_charset);
-			_writer.write(string);
-			point = 0;			
-		}
-	}
+    /**
+     * @return Returns the charset.
+     */
+    public String getCharset() {
+        return charset;
+    }
 
-	/* (non-Javadoc)
-	 * @see java.io.OutputStream#write(byte[], int, int)
-	 */
-	public void write(byte[] b, int off, int len) throws IOException {
-		this.flush();
-		String string = null==_charset?new String(b,off,len):new String(b,off,len,_charset);
-		_writer.write(string);
-	}
-}
\ No newline at end of file
+    /**
+     * @param charset The charset to set.
+     */
+    public void setCharset(String charset) {
+        this.charset = charset;
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.io.OutputStream#close()
+     */
+    @Override
+    public void close() throws IOException {
+        this.flush();
+        super.close();
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.io.OutputStream#flush()
+     */
+    @Override
+    public void flush() throws IOException {
+        if (point > 0) {
+            String string = (null == charset) ? new String(buff, 0, point) : new String(buff, 0, point, charset);
+
+            writer.write(string);
+            point = 0;
+        }
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see java.io.OutputStream#write(byte[], int, int)
+     */
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        this.flush();
+
+        String string = (null == charset) ? new String(b, off, len) : new String(b, off, len, charset);
+
+        writer.write(string);
+    }
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/WebXml.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/WebXml.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/WebXml.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,341 +19,333 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.webapp;
 
-import java.io.Serializable;
 
-import javax.faces.context.FacesContext;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
+package org.ajax4jsf.webapp;
 
 import org.ajax4jsf.config.WebXMLParser;
+
 import org.richfaces.VersionBean;
 import org.richfaces.VersionBean.Version;
 import org.richfaces.log.RichfacesLogger;
+
 import org.slf4j.Logger;
 
+import java.io.Serializable;
+
+import javax.faces.context.FacesContext;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+
 /**
  * Parse at startup application web.xml and store servlet and filter mappings.
  * at runtime, used for convert resource key to uri, and vice versa.
- * 
+ *
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:59 $
- * 
+ *
  */
 public class WebXml extends WebXMLParser implements Serializable {
+    public static final String CONTEXT_ATTRIBUTE = WebXml.class.getName();
+    public static final String GLOBAL_RESOURCE_URI_PREFIX = "a4j/g";
+    public static final String GLOBAL_RESOURCE_URI_PREFIX_PARAM = "org.ajax4jsf.GLOBAL_RESOURCE_URI_PREFIX";
+    public static final String RESOURCE_URI_PREFIX = "a4j";
+    public static final String RESOURCE_URI_PREFIX_PARAM = "org.ajax4jsf.RESOURCE_URI_PREFIX";
+    public static final String SESSION_RESOURCE_URI_PREFIX = "a4j/s";
+    public static final String SESSION_RESOURCE_URI_PREFIX_PARAM = "org.ajax4jsf.SESSION_RESOURCE_URI_PREFIX";
+    private static final long serialVersionUID = -9042908418843695017L;
+    private static final Logger LOG = RichfacesLogger.WEBAPP.getLogger();
+    public static final String GLOBAL_RESOURCE_URI_PREFIX_VERSIONED;
+    public static final String RESOURCE_URI_PREFIX_VERSIONED;
+    public static final String SESSION_RESOURCE_URI_PREFIX_VERSIONED;
 
-	public static final String CONTEXT_ATTRIBUTE = WebXml.class.getName();
+    static {
+        VersionBean versionBean = new VersionBean();
+        Version version = versionBean.getVersion();
+        String suffix = "/" + version.getMajor() + "_" + version.getMinor() + "_" + version.getRevision();
 
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = -9042908418843695017L;
+        // that's to prevent static compile-time linkage to constant values
+        RESOURCE_URI_PREFIX_VERSIONED = RESOURCE_URI_PREFIX + suffix;
+        GLOBAL_RESOURCE_URI_PREFIX_VERSIONED = GLOBAL_RESOURCE_URI_PREFIX + suffix;
+        SESSION_RESOURCE_URI_PREFIX_VERSIONED = SESSION_RESOURCE_URI_PREFIX + suffix;
+    }
 
-	static final Logger _log = RichfacesLogger.WEBAPP.getLogger();
+    protected boolean prefixMapping = false;
 
-	public static final String RESOURCE_URI_PREFIX = "a4j";
+    /**
+     * Prefix for resources handled by Chameleon framework.
+     */
+    String resourcePrefix = RESOURCE_URI_PREFIX;
+    String globalResourcePrefix;
+    String sessionResourcePrefix;
 
-	public static final String GLOBAL_RESOURCE_URI_PREFIX = "a4j/g";
-	
-	public static final String SESSION_RESOURCE_URI_PREFIX = "a4j/s";
+    public static WebXml getInstance() {
+        return getInstance(FacesContext.getCurrentInstance());
+    }
 
-	public static final String RESOURCE_URI_PREFIX_VERSIONED;
+    public static WebXml getInstance(FacesContext context) {
+        return (WebXml) context.getExternalContext().getApplicationMap().get(WebXml.CONTEXT_ATTRIBUTE);
+    }
 
-	public static final String GLOBAL_RESOURCE_URI_PREFIX_VERSIONED;
+    @Override
+    public void init(ServletContext context, String filterName) throws ServletException {
+        super.init(context, filterName);
+        setupResourcePrefixes(context);
 
-	public static final String SESSION_RESOURCE_URI_PREFIX_VERSIONED;
+        // Store Instance to context attribute.
+        context.setAttribute(CONTEXT_ATTRIBUTE, this);
+    }
 
-	static {
-		VersionBean versionBean = new VersionBean();
-		Version version = versionBean.getVersion();
+    /**
+     * Convert {@link org.ajax4jsf.resource.InternetResource } key to real URL
+     * for handle by chameleon filter, depend of mapping in WEB.XML . For prefix
+     * or * mapping, prepend servlet prefix and default Resource prefix to key.
+     * For suffix mapping, prepend with resource prefix and append default faces
+     * suffix to URL ( before request param ). After conversion, call
+     * {@link javax.faces.application.ViewHandler#getResourceURL(javax.faces.context.FacesContext, java.lang.String)}
+     * and
+     * {@link javax.faces.context.ExternalContext#encodeResourceURL(java.lang.String)} .
+     *
+     * @param context
+     * @param url
+     * @return
+     */
+    public String getFacesResourceURL(FacesContext context, String url, boolean isGlobal) {
+        StringBuffer buf = new StringBuffer();
 
-		String suffix = "/" + version.getMajor() + "_" + version.getMinor() + "_"
-			+ version.getRevision();
-		
-		//that's to prevent static compile-time linkage to constant values
-		RESOURCE_URI_PREFIX_VERSIONED = RESOURCE_URI_PREFIX + suffix;
-		GLOBAL_RESOURCE_URI_PREFIX_VERSIONED = GLOBAL_RESOURCE_URI_PREFIX + suffix;
-		SESSION_RESOURCE_URI_PREFIX_VERSIONED = SESSION_RESOURCE_URI_PREFIX + suffix;
-	}
-	
-	public static final String RESOURCE_URI_PREFIX_PARAM = "org.ajax4jsf.RESOURCE_URI_PREFIX";
+        buf.append(isGlobal ? getGlobalResourcePrefix() : getSessionResourcePrefix()).append(url);
 
-	public static final String GLOBAL_RESOURCE_URI_PREFIX_PARAM = "org.ajax4jsf.GLOBAL_RESOURCE_URI_PREFIX";
+        // Insert suffix mapping
+        if (isPrefixMapping()) {
+            buf.insert(0, getFacesFilterPrefix());
+        } else {
+            int index = buf.indexOf("?");
 
-	public static final String SESSION_RESOURCE_URI_PREFIX_PARAM = "org.ajax4jsf.SESSION_RESOURCE_URI_PREFIX";
+            if (index >= 0) {
+                buf.insert(index, getFacesFilterSuffix());
+            } else {
+                buf.append(getFacesFilterSuffix());
+            }
+        }
 
-	/**
-	 * Prefix for resources handled by Chameleon framework.
-	 */
-	String _resourcePrefix = RESOURCE_URI_PREFIX;
+        String resourceURL = context.getApplication().getViewHandler().getResourceURL(context, buf.toString());
 
-	String _globalResourcePrefix;
+        return resourceURL;
+    }
 
-	String _sessionResourcePrefix;
+    @Deprecated
+    public String getFacesResourceURL(FacesContext context, String url) {
+        return getFacesResourceURL(context, url, false);
+    }
 
-	protected boolean _prefixMapping = false;
+    public String getFacesResourceKey(String resourcePath) {
+        String workingResourcePath = resourcePath;
 
-	public static WebXml getInstance() {
-		return getInstance(FacesContext.getCurrentInstance());
-	}
-	
-	public static WebXml getInstance(FacesContext context) {
-		WebXml webXml = (WebXml) context.getExternalContext()
-				.getApplicationMap().get(WebXml.CONTEXT_ATTRIBUTE);
-		return webXml;
-	}
-	
-	@Override
-	public void init(ServletContext context, String filterName)
-			throws ServletException {
-		super.init(context, filterName);
-		setupResourcePrefixes(context);
-		// Store Instance to context attribute.
-		context.setAttribute(CONTEXT_ATTRIBUTE, this);
+        // Remove JSESSIONID - for expired sessions it will merged to path.
+        int jsesionidStart = workingResourcePath.lastIndexOf(";jsessionid");
 
-	}
-	
-	/**
-	 * Convert {@link org.ajax4jsf.resource.InternetResource } key to real URL
-	 * for handle by chameleon filter, depend of mapping in WEB.XML . For prefix
-	 * or * mapping, prepend servlet prefix and default Resource prefix to key.
-	 * For suffix mapping, prepend with resource prefix and append default faces
-	 * suffix to URL ( before request param ). After conversion, call
-	 * {@link javax.faces.application.ViewHandler#getResourceURL(javax.faces.context.FacesContext, java.lang.String)}
-	 * and
-	 * {@link javax.faces.context.ExternalContext#encodeResourceURL(java.lang.String)} .
-	 * 
-	 * @param context
-	 * @param Url
-	 * @return
-	 */
-	public String getFacesResourceURL(FacesContext context, String Url, boolean isGlobal) {
-		StringBuffer buf = new StringBuffer();
-		buf.append(isGlobal ? getGlobalResourcePrefix() : getSessionResourcePrefix()).append(Url);
-		// Insert suffix mapping
-		if (isPrefixMapping()) {
-			buf.insert(0, getFacesFilterPrefix());
-		} else {
-			int index;
-			if ((index = buf.indexOf("?")) >= 0) {
-				buf.insert(index, getFacesFilterSuffix());
-			} else {
-				buf.append(getFacesFilterSuffix());
-			}
-		}
-		String resourceURL = context.getApplication().getViewHandler()
-				.getResourceURL(context, buf.toString());
-		return resourceURL;
+        if (jsesionidStart >= 0) {
+            workingResourcePath = workingResourcePath.substring(0, jsesionidStart);
+        }
 
-	}
+        String resourcePrefix = getResourcePrefix();
 
-	@Deprecated
-	public String getFacesResourceURL(FacesContext context, String Url) {
-		return getFacesResourceURL(context, Url, false);
-	}
+        if (isPrefixMapping()) {
+            String facesFilterPrefix = getFacesFilterPrefix();
 
-	public String getFacesResourceKey(String resourcePath) {
-		// Remove JSESSIONID - for expired sessions it will merged to path.
-		int jsesionidStart;
-		if ((jsesionidStart = resourcePath.lastIndexOf(";jsessionid")) >= 0) {
-			resourcePath = resourcePath.substring(0, jsesionidStart);
-		}
-		String resourcePrefix = getResourcePrefix();
-		if (isPrefixMapping()) {
-			String facesFilterPrefix = getFacesFilterPrefix();
-			
-			if (resourcePath.startsWith(facesFilterPrefix)) {
-				String sessionResourcePrefix = getSessionResourcePrefix();
-				if (resourcePath.startsWith(sessionResourcePrefix, facesFilterPrefix.length())) {
-					return resourcePath.substring(facesFilterPrefix.length()
-							+ sessionResourcePrefix.length());
-				} else {
-					String globalResourcePrefix = getGlobalResourcePrefix();
-					if (!sessionResourcePrefix.equals(globalResourcePrefix) && 
-							resourcePath.startsWith(globalResourcePrefix, facesFilterPrefix.length())) {
-						
-						return resourcePath.substring(facesFilterPrefix.length()
-								+ globalResourcePrefix.length());
-					} else if (!globalResourcePrefix.equals(resourcePrefix) && 
-							resourcePath.startsWith(resourcePrefix, facesFilterPrefix.length())) {
-						
-						return resourcePath.substring(facesFilterPrefix.length()
-								+ resourcePrefix.length());
-					}
-				}
-			}
-		} else {
-			String sessionResourcePrefix = getSessionResourcePrefix();
-			if (resourcePath.startsWith(sessionResourcePrefix)) {
-				return resourcePath.substring(sessionResourcePrefix.length(),
-						resourcePath.length() - getFacesFilterSuffix().length());
-			} else {
-				String globalResourcePrefix = getGlobalResourcePrefix();
-				if (!sessionResourcePrefix.equals(globalResourcePrefix) && 
-						resourcePath.startsWith(globalResourcePrefix)) {
-					
-					return resourcePath.substring(globalResourcePrefix.length(),
-							resourcePath.length() - getFacesFilterSuffix().length());
-				} else if (!globalResourcePrefix.equals(resourcePrefix) && 
-						resourcePath.startsWith(resourcePrefix)) {
-					
-					return resourcePath.substring(resourcePrefix.length(),
-							resourcePath.length() - getFacesFilterSuffix().length());
-				}
-			}
-		}
-			
-		return null;
-	}
-	
-	/**
-	 * Detect request to resource and extract key from request
-	 * 
-	 * @param request
-	 *            current http request
-	 * @return resource key, or null for ordinary faces request.
-	 */
-	public String getFacesResourceKey(HttpServletRequest request) {
-		String resourcePath = request.getRequestURI().substring(
-				request.getContextPath().length());// isPrefixMapping()?request.getPathInfo():request.getServletPath();
+            if (workingResourcePath.startsWith(facesFilterPrefix)) {
+                String sessionResourcePrefix = getSessionResourcePrefix();
 
-		return getFacesResourceKey(resourcePath);
-	}
+                if (workingResourcePath.startsWith(sessionResourcePrefix, facesFilterPrefix.length())) {
+                    return workingResourcePath.substring(facesFilterPrefix.length() + sessionResourcePrefix.length());
+                } else {
+                    String globalResourcePrefix = getGlobalResourcePrefix();
 
-	/**
-	 * Detect request to {@link javax.faces.webapp.FacesServlet}
-	 * 
-	 * @param request
-	 * @return true if request parsed to JSF.
-	 */
-	public boolean isFacesRequest(HttpServletRequest request) {
-		// String resourcePath =
-		// request.getRequestURI().substring(request.getContextPath().length());//isPrefixMapping()?request.getPathInfo():request.getServletPath();
-		// if(isPrefixMapping() ) {
-		// if (resourcePath.startsWith(getFacesFilterPrefix())) {
-		// return true;
-		// }
-		// } else if (resourcePath.endsWith(getFacesFilterSuffix())) {
-		// return true;
-		// }
-		// return false;
-		return true;
-	}
+                    if (!sessionResourcePrefix.equals(globalResourcePrefix)
+                            && workingResourcePath.startsWith(globalResourcePrefix, facesFilterPrefix.length())) {
+                        return workingResourcePath.substring(facesFilterPrefix.length()
+                                + globalResourcePrefix.length());
+                    } else if (!globalResourcePrefix.equals(resourcePrefix)
+                               && workingResourcePath.startsWith(resourcePrefix, facesFilterPrefix.length())) {
+                        return workingResourcePath.substring(facesFilterPrefix.length() + resourcePrefix.length());
+                    }
+                }
+            }
+        } else {
+            String sessionResourcePrefix = getSessionResourcePrefix();
 
-	/**
-	 * @return Returns the resourcePrefix.
-	 */
-	@Deprecated
-	public String getResourcePrefix() {
-		return _resourcePrefix;
-	}
+            if (workingResourcePath.startsWith(sessionResourcePrefix)) {
+                return workingResourcePath.substring(sessionResourcePrefix.length(),
+                        workingResourcePath.length() - getFacesFilterSuffix().length());
+            } else {
+                String globalResourcePrefix = getGlobalResourcePrefix();
 
-	/**
-	 * @since 3.2.2
-	 * @return
-	 */
-	public String getGlobalResourcePrefix() {
-		return _globalResourcePrefix;
-	}
+                if (!sessionResourcePrefix.equals(globalResourcePrefix)
+                        && workingResourcePath.startsWith(globalResourcePrefix)) {
+                    return workingResourcePath.substring(globalResourcePrefix.length(),
+                            workingResourcePath.length() - getFacesFilterSuffix().length());
+                } else if (!globalResourcePrefix.equals(resourcePrefix)
+                           && workingResourcePath.startsWith(resourcePrefix)) {
+                    return workingResourcePath.substring(resourcePrefix.length(),
+                            workingResourcePath.length() - getFacesFilterSuffix().length());
+                }
+            }
+        }
 
-	/**
-	 * @since 3.2.2
-	 * @return
-	 */
-	public String getSessionResourcePrefix() {
-		return _sessionResourcePrefix;
-	}
+        return null;
+    }
 
-	/**
-	 * @return Returns the prefixMapping.
-	 */
-	public boolean isPrefixMapping() {
-		return _prefixMapping;
-	}
+    /**
+     * Detect request to resource and extract key from request
+     *
+     * @param request
+     *            current http request
+     * @return resource key, or null for ordinary faces request.
+     */
+    public String getFacesResourceKey(HttpServletRequest request) {
+        String resourcePath = request.getRequestURI().substring(request.getContextPath().length());
 
-	/**
-	 * @param resourcePrefix
-	 *            The resourcePrefix to set.
-	 */
-	@Deprecated
-	void setResourcePrefix(String resourcePrefix) {
-		_resourcePrefix = resourcePrefix;
-	}
+        // isPrefixMapping()?request.getPathInfo():request.getServletPath();
 
-	/**
-	 * @since 3.2.2
-	 * @param resourcePrefix
-	 *            The resourcePrefix to set.
-	 */
-	void setGlobalResourcePrefix(String resourcePrefix) {
-		_globalResourcePrefix = resourcePrefix;
-	}
+        return getFacesResourceKey(resourcePath);
+    }
 
-	/**
-	 * @since 3.2.2
-	 * @param resourcePrefix
-	 *            The resourcePrefix to set.
-	 *           
-	 */
-	void setSessionResourcePrefix(String resourcePrefix) {
-		_sessionResourcePrefix = resourcePrefix;
-	}
+    /**
+     * Detect request to {@link javax.faces.webapp.FacesServlet}
+     *
+     * @param request
+     * @return true if request parsed to JSF.
+     */
+    public boolean isFacesRequest(HttpServletRequest request) {
 
-	/**
-	 * @param context
-	 */
-	void setupResourcePrefixes(ServletContext context) {
-		String globalResourcePrefix = (String) context
-			.getInitParameter(GLOBAL_RESOURCE_URI_PREFIX_PARAM);
-	
-		String sessionResourcePrefix = (String) context
-			.getInitParameter(SESSION_RESOURCE_URI_PREFIX_PARAM);
-	
-		String resourcePrefix = (String) context
-			.getInitParameter(RESOURCE_URI_PREFIX_PARAM);
-	
-		if (null != resourcePrefix) {
-			if (globalResourcePrefix == null) {
-				//TODO overriden
-				globalResourcePrefix = resourcePrefix;
-			}
-			
-			if (sessionResourcePrefix == null) {
-				//TODO overriden
-				sessionResourcePrefix = resourcePrefix;
-			}
-		} else {
-			resourcePrefix = RESOURCE_URI_PREFIX_VERSIONED;
-		}
-		
-		if (globalResourcePrefix == null) {
-			//TODO overriden
-			globalResourcePrefix = GLOBAL_RESOURCE_URI_PREFIX_VERSIONED;
-		}
-		
-		if (sessionResourcePrefix == null) {
-			//TODO overriden
-			sessionResourcePrefix = SESSION_RESOURCE_URI_PREFIX_VERSIONED;
-		}
-	
-		if (null != getFacesFilterPrefix()) {
-			_prefixMapping = true;
-			if (getFacesFilterPrefix().endsWith("/")) {
-				setGlobalResourcePrefix(globalResourcePrefix);
-				setSessionResourcePrefix(sessionResourcePrefix);
-				setResourcePrefix(resourcePrefix);
-			} else {
-				setGlobalResourcePrefix("/" + globalResourcePrefix);
-				setSessionResourcePrefix("/" + sessionResourcePrefix);
-				setResourcePrefix("/" + resourcePrefix);
-			}
-		} else if (null != getFacesFilterSuffix()) {
-			_prefixMapping = false;
-			setResourcePrefix("/" + resourcePrefix);
-			setGlobalResourcePrefix("/" + globalResourcePrefix);
-			setSessionResourcePrefix("/" + sessionResourcePrefix);
-		}
-	}
+        // String resourcePath =
+        // request.getRequestURI().substring(request.getContextPath().length());
+        // //isPrefixMapping()?request.getPathInfo():request.getServletPath();
+        // if(isPrefixMapping() ) {
+        // if (resourcePath.startsWith(getFacesFilterPrefix())) {
+        // return true;
+        // }
+        // } else if (resourcePath.endsWith(getFacesFilterSuffix())) {
+        // return true;
+        // }
+        // return false;
+        return true;
+    }
+
+    /**
+     * @return Returns the resourcePrefix.
+     */
+    @Deprecated
+    public String getResourcePrefix() {
+        return resourcePrefix;
+    }
+
+    /**
+     * @since 3.2.2
+     * @return
+     */
+    public String getGlobalResourcePrefix() {
+        return globalResourcePrefix;
+    }
+
+    /**
+     * @since 3.2.2
+     * @return
+     */
+    public String getSessionResourcePrefix() {
+        return sessionResourcePrefix;
+    }
+
+    /**
+     * @return Returns the prefixMapping.
+     */
+    public boolean isPrefixMapping() {
+        return prefixMapping;
+    }
+
+    /**
+     * @param resourcePrefix
+     *            The resourcePrefix to set.
+     */
+    @Deprecated
+    void setResourcePrefix(String resourcePrefix) {
+        this.resourcePrefix = resourcePrefix;
+    }
+
+    /**
+     * @since 3.2.2
+     * @param resourcePrefix
+     *            The resourcePrefix to set.
+     */
+    void setGlobalResourcePrefix(String resourcePrefix) {
+        globalResourcePrefix = resourcePrefix;
+    }
+
+    /**
+     * @since 3.2.2
+     * @param resourcePrefix
+     *            The resourcePrefix to set.
+     *
+     */
+    void setSessionResourcePrefix(String resourcePrefix) {
+        sessionResourcePrefix = resourcePrefix;
+    }
+
+    /**
+     * @param context
+     */
+    void setupResourcePrefixes(ServletContext context) {
+        String globalResourcePrefix = (String) context.getInitParameter(GLOBAL_RESOURCE_URI_PREFIX_PARAM);
+        String sessionResourcePrefix = (String) context.getInitParameter(SESSION_RESOURCE_URI_PREFIX_PARAM);
+        String resourcePrefix = (String) context.getInitParameter(RESOURCE_URI_PREFIX_PARAM);
+
+        if (null != resourcePrefix) {
+            if (globalResourcePrefix == null) {
+
+                // TODO overriden
+                globalResourcePrefix = resourcePrefix;
+            }
+
+            if (sessionResourcePrefix == null) {
+
+                // TODO overriden
+                sessionResourcePrefix = resourcePrefix;
+            }
+        } else {
+            resourcePrefix = RESOURCE_URI_PREFIX_VERSIONED;
+        }
+
+        if (globalResourcePrefix == null) {
+
+            // TODO overriden
+            globalResourcePrefix = GLOBAL_RESOURCE_URI_PREFIX_VERSIONED;
+        }
+
+        if (sessionResourcePrefix == null) {
+
+            // TODO overriden
+            sessionResourcePrefix = SESSION_RESOURCE_URI_PREFIX_VERSIONED;
+        }
+
+        if (null != getFacesFilterPrefix()) {
+            prefixMapping = true;
+
+            if (getFacesFilterPrefix().endsWith("/")) {
+                setGlobalResourcePrefix(globalResourcePrefix);
+                setSessionResourcePrefix(sessionResourcePrefix);
+                setResourcePrefix(resourcePrefix);
+            } else {
+                setGlobalResourcePrefix("/" + globalResourcePrefix);
+                setSessionResourcePrefix("/" + sessionResourcePrefix);
+                setResourcePrefix("/" + resourcePrefix);
+            }
+        } else if (null != getFacesFilterSuffix()) {
+            prefixMapping = false;
+            setResourcePrefix("/" + resourcePrefix);
+            setGlobalResourcePrefix("/" + globalResourcePrefix);
+            setSessionResourcePrefix("/" + sessionResourcePrefix);
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/XMLResponseWriterState.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/XMLResponseWriterState.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/XMLResponseWriterState.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,27 +19,31 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp;
 
+import org.ajax4jsf.Messages;
+
 import java.io.IOException;
 
 import javax.faces.component.UIComponent;
 
-import org.ajax4jsf.Messages;
-
 /**
  * @author shura Class to implement state pattern for
  *         <code>ResponceWriter</code> Real states must extend this. By
  *         default, block any events, ignore output.
- *  
+ *
  */
 class XMLResponseWriterState {
+
     // private ResponseWriter writer;
+
     /**
      * @throws java.io.IOException
      */
-	private static final String ILLEGAL_METOD_STATE = Messages.getMessage(Messages.ILLEGAL_METHOD_STATE);
-	
+    private static final String ILLEGAL_METOD_STATE = Messages.getMessage(Messages.ILLEGAL_METHOD_STATE);
+
     void endDocument() throws IOException {
         throw new IOException(ILLEGAL_METOD_STATE);
     }
@@ -74,8 +78,7 @@
      * @param property
      * @throws java.io.IOException
      */
-    void writeAttribute(String name, Object value, String property)
-            throws IOException {
+    void writeAttribute(String name, Object value, String property) throws IOException {
         throw new IOException(ILLEGAL_METOD_STATE);
     }
 
@@ -112,23 +115,22 @@
      * @param property
      * @throws java.io.IOException
      */
-    void writeURIAttribute(String name, Object value, String property)
-            throws IOException {
+    void writeURIAttribute(String name, Object value, String property) throws IOException {
         throw new IOException(ILLEGAL_METOD_STATE);
     }
 
     /**
-     * 
+     *
      * Main hook for realise <code>Writer</code>. In document writed as
      * comment, outside of document do nothing ....
-     * 
+     *
      * @param cbuf
      * @param off
      * @param len
      * @throws IOException
      */
     void write(char[] cbuf, int off, int len) throws IOException {
+
         // DO NOTHING
-
     }
-}
\ No newline at end of file
+}

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Web application-related stuff: filters, parsers, etc.
  */

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxActionsRule.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxActionsRule.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxActionsRule.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,6 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp.taglib;
 
 import javax.faces.component.ActionSource;
@@ -37,102 +39,91 @@
  *
  */
 public class AjaxActionsRule extends MetaRule {
+    public static final Class<?>[] ACTION_SIG = new Class[0];
+    public static final Class<?>[] ACTION_LISTENER_SIG = new Class[] {ActionEvent.class};
+    public static final AjaxActionsRule INSTANCE = new AjaxActionsRule();
 
-    public final static Class<?>[] ACTION_SIG = new Class[0];
+    public AjaxActionsRule() {
+        super();
+    }
 
-    public final static Class<?>[] ACTION_LISTENER_SIG = new Class[] { ActionEvent.class };
+    @Override
+    public Metadata applyRule(String name, TagAttribute attribute, MetadataTarget meta) {
+        if (meta.isTargetInstanceOf(ActionSource.class)) {
+            if ("action".equals(name)) {
+                if (meta.isTargetInstanceOf(ActionSource2.class)) {
+                    return new ActionMapper2(attribute);
+                } else {
+                    return new ActionMapper(attribute);
+                }
+            }
 
-    public final static class ActionMapper extends Metadata {
+            if ("actionListener".equals(name)) {
+                if (meta.isTargetInstanceOf(ActionSource2.class)) {
+                    return new ActionListenerMapper2(attribute);
+                } else {
+                    return new ActionListenerMapper(attribute);
+                }
+            }
+        }
 
+        return null;
+    }
+
+    public static final class ActionListenerMapper extends Metadata {
         private final TagAttribute attr;
 
-        public ActionMapper(TagAttribute attr) {
+        public ActionListenerMapper(TagAttribute attr) {
             this.attr = attr;
         }
 
         public void applyMetadata(FaceletContext ctx, Object instance) {
-            ((ActionSource2) instance).setActionExpression(
-            		this.attr.getMethodExpression(ctx, String.class,
-                            AjaxActionsRule.ACTION_SIG));
+            ((ActionSource) instance).addActionListener(
+                new MethodExpressionActionListener(
+                    this.attr.getMethodExpression(ctx, null, AjaxActionsRule.ACTION_LISTENER_SIG)));
         }
     }
-    
-    final static class ActionMapper2 extends Metadata {
 
+
+    static final class ActionListenerMapper2 extends Metadata {
         private final TagAttribute attr;
 
-        public ActionMapper2(TagAttribute attr) {
+        public ActionListenerMapper2(TagAttribute attr) {
             this.attr = attr;
         }
 
         public void applyMetadata(FaceletContext ctx, Object instance) {
-            ((ActionSource2) instance).setActionExpression(this.attr
-                    .getMethodExpression(ctx, String.class,
-                    		AjaxActionsRule.ACTION_SIG));
+            ((ActionSource2) instance).addActionListener(
+                new MethodExpressionActionListener(
+                    this.attr.getMethodExpression(ctx, null, AjaxActionsRule.ACTION_LISTENER_SIG)));
         }
-
     }
 
-    public final static class ActionListenerMapper extends Metadata {
 
+    public static final class ActionMapper extends Metadata {
         private final TagAttribute attr;
 
-        public ActionListenerMapper(TagAttribute attr) {
+        public ActionMapper(TagAttribute attr) {
             this.attr = attr;
         }
 
         public void applyMetadata(FaceletContext ctx, Object instance) {
-            ((ActionSource) instance).addActionListener(new MethodExpressionActionListener(this.attr
-                    .getMethodExpression(ctx, null,
-                            AjaxActionsRule.ACTION_LISTENER_SIG)));
+            ((ActionSource2) instance).setActionExpression(this.attr.getMethodExpression(ctx, String.class,
+                    AjaxActionsRule.ACTION_SIG));
         }
-
     }
-    
-    final static class ActionListenerMapper2 extends Metadata {
 
+
+    static final class ActionMapper2 extends Metadata {
         private final TagAttribute attr;
 
-        public ActionListenerMapper2(TagAttribute attr) {
+        public ActionMapper2(TagAttribute attr) {
             this.attr = attr;
         }
 
         public void applyMetadata(FaceletContext ctx, Object instance) {
-            ((ActionSource2) instance)
-                    .addActionListener(new MethodExpressionActionListener(
-                            this.attr.getMethodExpression(ctx, null,
-                            		AjaxActionsRule.ACTION_LISTENER_SIG)));
-
+            ((ActionSource2) instance).setActionExpression(this.attr.getMethodExpression(ctx, String.class,
+                    AjaxActionsRule.ACTION_SIG));
         }
-
     }
-
-    public final static AjaxActionsRule instance = new AjaxActionsRule();
-
-    public AjaxActionsRule() {
-        super();
-    }
-
-    public Metadata applyRule(String name, TagAttribute attribute,
-            MetadataTarget meta) {
-        if (meta.isTargetInstanceOf(ActionSource.class)) {
-            if ("action".equals(name)) {
-            	if (meta.isTargetInstanceOf(ActionSource2.class)) {
-            		return new ActionMapper2(attribute);
-            	} else {
-            		return new ActionMapper(attribute);
-            	}
-            }
-
-            if ("actionListener".equals(name)) {
-            	 if (meta.isTargetInstanceOf(ActionSource2.class)) {
-                     return new ActionListenerMapper2(attribute);
-                 } else {
-                     return new ActionListenerMapper(attribute);
-                 }
-            }
-        }
-        return null;
-    }
-
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxComponentHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxComponentHandler.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxComponentHandler.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,15 +19,17 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp.taglib;
 
+import org.ajax4jsf.component.AjaxContainerBase;
+
 import javax.faces.component.ActionSource;
 import javax.faces.view.facelets.ComponentConfig;
 import javax.faces.view.facelets.ComponentHandler;
 import javax.faces.view.facelets.MetaRuleset;
 
-import org.ajax4jsf.component.AjaxContainerBase;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/02/01 15:31:23 $
@@ -35,28 +37,34 @@
  */
 public class AjaxComponentHandler extends ComponentHandler {
 
-	/**
-	 * @param config
-	 */
-	public AjaxComponentHandler(ComponentConfig config) {
-		super(config);
-		// TODO Auto-generated constructor stub
-	}
+    /**
+     * @param config
+     */
+    public AjaxComponentHandler(ComponentConfig config) {
+        super(config);
 
-	/* (non-Javadoc)
-	 * @see com.sun.facelets.tag.jsf.ComponentHandler#createMetaRuleset(java.lang.Class)
-	 */
-	protected MetaRuleset createMetaRuleset(Class type) {
-		// TODO Auto-generated method stub
-		MetaRuleset metaRules = super.createMetaRuleset(type);
-		if (ActionSource.class.isAssignableFrom(type)) {
-			metaRules.addRule(AjaxActionsRule.instance);
-		}
-		if (AjaxContainerBase.class.isAssignableFrom(type)) {
-			metaRules.addRule(AjaxContainerBaseRule.instance);
-		}
-		metaRules.addRule(AjaxReRendrRule.instance);
-		return metaRules;
-	}
+        // TODO Auto-generated constructor stub
+    }
 
+    /*
+     *  (non-Javadoc)
+     * @see com.sun.facelets.tag.jsf.ComponentHandler#createMetaRuleset(java.lang.Class)
+     */
+    protected MetaRuleset createMetaRuleset(Class type) {
+
+        // TODO Auto-generated method stub
+        MetaRuleset metaRules = super.createMetaRuleset(type);
+
+        if (ActionSource.class.isAssignableFrom(type)) {
+            metaRules.addRule(AjaxActionsRule.INSTANCE);
+        }
+
+        if (AjaxContainerBase.class.isAssignableFrom(type)) {
+            metaRules.addRule(AjaxContainerBaseRule.INSTANCE);
+        }
+
+        metaRules.addRule(AjaxReRendrRule.INSTANCE);
+
+        return metaRules;
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxContainerBaseRule.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxContainerBaseRule.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxContainerBaseRule.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,60 +19,53 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp.taglib;
 
+import org.ajax4jsf.component.AjaxContainerBase;
+import org.ajax4jsf.event.AjaxEvent;
+
 import javax.faces.view.facelets.FaceletContext;
 import javax.faces.view.facelets.MetaRule;
 import javax.faces.view.facelets.Metadata;
 import javax.faces.view.facelets.MetadataTarget;
 import javax.faces.view.facelets.TagAttribute;
 
-import org.ajax4jsf.component.AjaxContainerBase;
-import org.ajax4jsf.event.AjaxEvent;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/02/01 15:31:21 $
  *
  */
 public class AjaxContainerBaseRule extends MetaRule {
+    public static final Class[] AJAX_LISTENER_SIG = new Class[] {AjaxEvent.class};
+    public static final AjaxContainerBaseRule INSTANCE = new AjaxContainerBaseRule();
 
-    public final static Class[] AJAX_LISTENER_SIG = new Class[] { AjaxEvent.class };
-
-    public final static class AjaxListenerMapper extends Metadata {
-
-        private final TagAttribute attr;
-
-        public AjaxListenerMapper(TagAttribute attr) {
-            this.attr = attr;
-        }
-
-        public void applyMetadata(FaceletContext ctx, Object instance) {
-            ((AjaxContainerBase) instance)
-                    .setAjaxListener(this.attr
-                            .getMethodExpression(ctx, null,
-                                    AJAX_LISTENER_SIG));
-        }
-
-    }
-
-    public final static AjaxContainerBaseRule instance = new AjaxContainerBaseRule();
-
     public AjaxContainerBaseRule() {
         super();
     }
 
-    public Metadata applyRule(String name, TagAttribute attribute,
-            MetadataTarget meta) {
+    @Override
+    public Metadata applyRule(String name, TagAttribute attribute, MetadataTarget meta) {
         if (meta.isTargetInstanceOf(AjaxContainerBase.class)) {
-
-
             if ("ajaxListener".equals(name)) {
-                    return new AjaxListenerMapper(attribute);
+                return new AjaxListenerMapper(attribute);
             }
-
         }
+
         return null;
     }
 
+    public static final class AjaxListenerMapper extends Metadata {
+        private final TagAttribute attr;
+
+        public AjaxListenerMapper(TagAttribute attr) {
+            this.attr = attr;
+        }
+
+        @Override
+        public void applyMetadata(FaceletContext ctx, Object instance) {
+            ((AjaxContainerBase) instance).setAjaxListener(this.attr.getMethodExpression(ctx, null, AJAX_LISTENER_SIG));
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxReRendrRule.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxReRendrRule.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/AjaxReRendrRule.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,8 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp.taglib;
 
+import org.ajax4jsf.component.AjaxComponent;
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
+
 import java.util.Set;
 
 import javax.faces.view.facelets.FaceletContext;
@@ -29,60 +34,58 @@
 import javax.faces.view.facelets.MetadataTarget;
 import javax.faces.view.facelets.TagAttribute;
 
-import org.ajax4jsf.component.AjaxComponent;
-import org.ajax4jsf.renderkit.AjaxRendererUtils;
-
 /**
  * @author shura (latest modification by $Author: alexsmirnov $)
  * @version $Revision: 1.1.2.1 $ $Date: 2007/02/01 15:31:22 $
  *
  */
 public class AjaxReRendrRule extends MetaRule {
+    public static final AjaxReRendrRule INSTANCE = new AjaxReRendrRule();
 
-	public static final AjaxReRendrRule instance = new AjaxReRendrRule();
-	/**
-	 * 
-	 */
-	public AjaxReRendrRule() {
-		super();
-		// TODO Auto-generated constructor stub
-	}
+    public AjaxReRendrRule() {
+        super();
 
-	/* (non-Javadoc)
-	 * @see com.sun.facelets.tag.MetaRule#applyRule(java.lang.String, com.sun.facelets.tag.TagAttribute, com.sun.facelets.tag.MetadataTarget)
-	 */
-	public Metadata applyRule(String name, TagAttribute attribute,
-			MetadataTarget meta) {
+        // TODO Auto-generated constructor stub
+    }
+
+    /*
+     *  (non-Javadoc)
+     * @see com.sun.facelets.tag.MetaRule#applyRule(java.lang.String, com.sun.facelets.tag.TagAttribute,
+     * com.sun.facelets.tag.MetadataTarget)
+     */
+    @Override
+    public Metadata applyRule(String name, TagAttribute attribute, MetadataTarget meta) {
         if (meta.isTargetInstanceOf(AjaxComponent.class)) {
-        	if ("reRender".equals(name)) {
-				if (attribute.isLiteral()) {
-					return new ReRendersSetMataData(attribute.getValue());
-				} else {
-					// Process as usual expression
-					return null;
-				}
-			}
+            if ("reRender".equals(name)) {
+                if (attribute.isLiteral()) {
+                    return new ReRendersSetMataData(attribute.getValue());
+                } else {
+
+                    // Process as usual expression
+                    return null;
+                }
+            }
         }
-		return null;
-	}
 
-	static class ReRendersSetMataData extends Metadata{
+        return null;
+    }
 
-		private Set _reRender;
-		/**
-		 * @param value
-		 */
-		public ReRendersSetMataData(String value) {
-			_reRender = AjaxRendererUtils.asSet(value);
-		}
+    static class ReRendersSetMataData extends Metadata {
+        private Set reRender;
 
-		/* (non-Javadoc)
-		 * @see com.sun.facelets.tag.Metadata#applyMetadata(com.sun.facelets.FaceletContext, java.lang.Object)
-		 */
-		public void applyMetadata(FaceletContext ctx, Object instance) {
-			((AjaxComponent) instance).setReRender(_reRender);
-			
-		}
-		
-	}
+        /**
+         * @param value
+         */
+        public ReRendersSetMataData(String value) {
+            reRender = AjaxRendererUtils.asSet(value);
+        }
+
+        /*
+         *  (non-Javadoc)
+         * @see com.sun.facelets.tag.Metadata#applyMetadata(com.sun.facelets.FaceletContext, java.lang.Object)
+         */
+        public void applyMetadata(FaceletContext ctx, Object instance) {
+            ((AjaxComponent) instance).setReRender(reRender);
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/EmptyHandler.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/EmptyHandler.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/EmptyHandler.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,11 +18,15 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.webapp.taglib;
 
 import java.io.IOException;
 
 import javax.el.ELException;
+
 import javax.faces.FacesException;
 import javax.faces.component.UIComponent;
 import javax.faces.view.facelets.FaceletContext;
@@ -37,18 +41,17 @@
  *
  */
 public class EmptyHandler extends TagHandler {
+    public EmptyHandler(TagConfig config) {
+        super(config);
+    }
 
-	public EmptyHandler(TagConfig config) {
-		super(config);
-	}
-
-	/* (non-Javadoc)
-	 * @see com.sun.facelets.FaceletHandler#apply(com.sun.facelets.FaceletContext, javax.faces.component.UIComponent)
-	 */
-	public void apply(FaceletContext ctx, UIComponent parent)
-			throws IOException, FacesException, FaceletException, ELException {
-		this.nextHandler.apply(ctx, parent);
-
-	}
-
+    /*
+     *  (non-Javadoc)
+     * @see com.sun.facelets.FaceletHandler#apply(com.sun.facelets.FaceletContext, javax.faces.component.UIComponent)
+     */
+    public void apply(FaceletContext ctx, UIComponent parent)
+        throws IOException, FacesException, FaceletException, ELException {
+        
+        this.nextHandler.apply(ctx, parent);
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/HtmlComponentTagBase.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/HtmlComponentTagBase.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/HtmlComponentTagBase.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,14 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
-package org.ajax4jsf.webapp.taglib;
 
-import javax.el.ValueExpression;
-import javax.faces.component.UIComponent;
 
+package org.ajax4jsf.webapp.taglib;
+
 import org.ajax4jsf.renderkit.RendererUtils.HTML;
 
+import javax.el.ValueExpression;
 
+import javax.faces.component.UIComponent;
+
 /**
  * Base tag for all components with common Html attributes.
  * @author asmirnov at exadel.com (latest modification by $Author: alexsmirnov $)
@@ -34,139 +36,123 @@
  *
  */
 public abstract class HtmlComponentTagBase extends UIComponentTagBase {
-    //HTML universal attributes
-    private ValueExpression _dir;
-    private ValueExpression _lang;
-    private ValueExpression _style;
-    private ValueExpression _styleClass;
-    private ValueExpression _title;
 
-    //HTML event handler attributes
-    private ValueExpression _onclick;
-    private ValueExpression _ondblclick;
-    private ValueExpression _onkeydown;
-    private ValueExpression _onkeypress;
-    private ValueExpression _onkeyup;
-    private ValueExpression _onmousedown;
-    private ValueExpression _onmousemove;
-    private ValueExpression _onmouseout;
-    private ValueExpression _onmouseover;
-    private ValueExpression _onmouseup;
+    // HTML universal attributes
+    private ValueExpression dir;
+    private ValueExpression lang;
 
+    // HTML event handler attributes
+    private ValueExpression onclick;
+    private ValueExpression ondblclick;
+    private ValueExpression onkeydown;
+    private ValueExpression onkeypress;
+    private ValueExpression onkeyup;
+    private ValueExpression onmousedown;
+    private ValueExpression onmousemove;
+    private ValueExpression onmouseout;
+    private ValueExpression onmouseover;
+    private ValueExpression onmouseup;
+    private ValueExpression style;
+    private ValueExpression styleClass;
+    private ValueExpression title;
+
+    @Override
     public void release() {
         super.release();
-
-        _dir=null;
-        _lang=null;
-        _style=null;
-        _styleClass=null;
-        _title=null;
-        _onclick=null;
-        _ondblclick=null;
-        _onkeydown=null;
-        _onkeypress=null;
-        _onkeyup=null;
-        _onmousedown=null;
-        _onmousemove=null;
-        _onmouseout=null;
-        _onmouseover=null;
-        _onmouseup=null;
-
+        dir = null;
+        lang = null;
+        style = null;
+        styleClass = null;
+        title = null;
+        onclick = null;
+        ondblclick = null;
+        onkeydown = null;
+        onkeypress = null;
+        onkeyup = null;
+        onmousedown = null;
+        onmousemove = null;
+        onmouseout = null;
+        onmouseover = null;
+        onmouseup = null;
     }
 
-    protected void setProperties(UIComponent component)
-    {
+    @Override
+    protected void setProperties(UIComponent component) {
         super.setProperties(component);
-        setProperty(component, HTML.dir_ATTRIBUTE, _dir);
-        setProperty(component, HTML.lang_ATTRIBUTE, _lang);
-        setProperty(component, HTML.style_ATTRIBUTE, _style);
-        setProperty(component, HTML.title_ATTRIBUTE, _title);
-        setProperty(component, HTML.STYLE_CLASS_ATTR, _styleClass);
-        setProperty(component, HTML.onclick_ATTRIBUTE, _onclick);
-        setProperty(component, HTML.ondblclick_ATTRIBUTE, _ondblclick);
-        setProperty(component, HTML.onmousedown_ATTRIBUTE, _onmousedown);
-        setProperty(component, HTML.onmouseup_ATTRIBUTE, _onmouseup);
-        setProperty(component, HTML.onmouseover_ATTRIBUTE, _onmouseover);
-        setProperty(component, HTML.onmousemove_ATTRIBUTE, _onmousemove);
-        setProperty(component, HTML.onmouseout_ATTRIBUTE, _onmouseout);
-        setProperty(component, HTML.onkeypress_ATTRIBUTE, _onkeypress);
-        setProperty(component, HTML.onkeydown_ATTRIBUTE, _onkeydown);
-        setProperty(component, HTML.onkeyup_ATTRIBUTE, _onkeyup);
+        setProperty(component, HTML.DIR_ATTRIBUTE, dir);
+        setProperty(component, HTML.LANG_ATTRIBUTE, lang);
+        setProperty(component, HTML.STYLE_ATTRIBUTE, style);
+        setProperty(component, HTML.TITLE_ATTRIBUTE, title);
+        setProperty(component, HTML.STYLE_CLASS_ATTR, styleClass);
+        setProperty(component, HTML.ONCLICK_ATTRIBUTE, onclick);
+        setProperty(component, HTML.ONDBLCLICK_ATTRIBUTE, ondblclick);
+        setProperty(component, HTML.ONMOUSEDOWN_ATTRIBUTE, onmousedown);
+        setProperty(component, HTML.ONMOUSEUP_ATTRIBUTE, onmouseup);
+        setProperty(component, HTML.ONMOUSEOVER_ATTRIBUTE, onmouseover);
+        setProperty(component, HTML.ONMOUSEMOVE_ATTRIBUTE, onmousemove);
+        setProperty(component, HTML.ONMOUSEOUT_ATTRIBUTE, onmouseout);
+        setProperty(component, HTML.ONKEYPRESS_ATTRIBUTE, onkeypress);
+        setProperty(component, HTML.ONKEYDOWN_ATTRIBUTE, onkeydown);
+        setProperty(component, HTML.ONKEYUP_ATTRIBUTE, onkeyup);
     }
 
-    public void setStyleClass(ValueExpression styleClass)
-    {
-        _styleClass = styleClass;
+    public void setStyleClass(ValueExpression styleClass) {
+        this.styleClass = styleClass;
     }
 
-    public void setDir(ValueExpression dir)
-    {
-        _dir = dir;
+    public void setDir(ValueExpression dir) {
+        this.dir = dir;
     }
 
-    public void setLang(ValueExpression lang)
-    {
-        _lang = lang;
+    public void setLang(ValueExpression lang) {
+        this.lang = lang;
     }
 
-    public void setStyle(ValueExpression style)
-    {
-        _style = style;
+    public void setStyle(ValueExpression style) {
+        this.style = style;
     }
 
-    public void setTitle(ValueExpression title)
-    {
-        _title = title;
+    public void setTitle(ValueExpression title) {
+        this.title = title;
     }
 
-    public void setOnclick(ValueExpression onclick)
-    {
-        _onclick = onclick;
+    public void setOnclick(ValueExpression onclick) {
+        this.onclick = onclick;
     }
 
-    public void setOndblclick(ValueExpression ondblclick)
-    {
-        _ondblclick = ondblclick;
+    public void setOndblclick(ValueExpression ondblclick) {
+        this.ondblclick = ondblclick;
     }
 
-    public void setOnmousedown(ValueExpression onmousedown)
-    {
-        _onmousedown = onmousedown;
+    public void setOnmousedown(ValueExpression onmousedown) {
+        this.onmousedown = onmousedown;
     }
 
-    public void setOnmouseup(ValueExpression onmouseup)
-    {
-        _onmouseup = onmouseup;
+    public void setOnmouseup(ValueExpression onmouseup) {
+        this.onmouseup = onmouseup;
     }
 
-    public void setOnmouseover(ValueExpression onmouseover)
-    {
-        _onmouseover = onmouseover;
+    public void setOnmouseover(ValueExpression onmouseover) {
+        this.onmouseover = onmouseover;
     }
 
-    public void setOnmousemove(ValueExpression onmousemove)
-    {
-        _onmousemove = onmousemove;
+    public void setOnmousemove(ValueExpression onmousemove) {
+        this.onmousemove = onmousemove;
     }
 
-    public void setOnmouseout(ValueExpression onmouseout)
-    {
-        _onmouseout = onmouseout;
+    public void setOnmouseout(ValueExpression onmouseout) {
+        this.onmouseout = onmouseout;
     }
 
-    public void setOnkeypress(ValueExpression onkeypress)
-    {
-        _onkeypress = onkeypress;
+    public void setOnkeypress(ValueExpression onkeypress) {
+        this.onkeypress = onkeypress;
     }
 
-    public void setOnkeydown(ValueExpression onkeydown)
-    {
-        _onkeydown = onkeydown;
+    public void setOnkeydown(ValueExpression onkeydown) {
+        this.onkeydown = onkeydown;
     }
 
-    public void setOnkeyup(ValueExpression onkeyup)
-    {
-        _onkeyup = onkeyup;
+    public void setOnkeyup(ValueExpression onkeyup) {
+        this.onkeyup = onkeyup;
     }
-
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/MethodExpressionAjaxListener.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/MethodExpressionAjaxListener.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/MethodExpressionAjaxListener.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -19,62 +19,64 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
+
+
 package org.ajax4jsf.webapp.taglib;
 
+import org.ajax4jsf.event.AjaxEvent;
+import org.ajax4jsf.event.AjaxListener;
+
 import javax.el.MethodExpression;
+
 import javax.faces.component.StateHolder;
 import javax.faces.component.UIComponentBase;
 import javax.faces.context.FacesContext;
 
-import org.ajax4jsf.event.AjaxEvent;
-import org.ajax4jsf.event.AjaxListener;
-
 /**
  * @author Nick Belaevski
  * @since 3.2.2
  */
-
 public class MethodExpressionAjaxListener implements AjaxListener, StateHolder {
+    private MethodExpression expression;
 
-	private MethodExpression expression;
-	
-	public MethodExpressionAjaxListener() {
-		super();
-	}
-	
-	public MethodExpressionAjaxListener(MethodExpression expression) {
-		super();
-		this.expression = expression;
-	}
+    public MethodExpressionAjaxListener() {
+        super();
+    }
 
-	public MethodExpression getExpression() {
-		return expression;
-	}
+    public MethodExpressionAjaxListener(MethodExpression expression) {
+        super();
+        this.expression = expression;
+    }
 
-	/* (non-Javadoc)
-	 * @see org.ajax4jsf.event.AjaxListener#processAjax(org.ajax4jsf.event.AjaxEvent)
-	 */
-	public void processAjax(AjaxEvent event) {
-		FacesContext facesContext = FacesContext.getCurrentInstance();
-		expression.invoke(facesContext.getELContext(), new Object[] {event});
-	}
+    public MethodExpression getExpression() {
+        return expression;
+    }
 
-	public void restoreState(FacesContext context, Object state) {
-		this.expression = (MethodExpression) UIComponentBase.restoreAttachedState(context, state);
-	}
+    /*
+     *  (non-Javadoc)
+     * @see org.ajax4jsf.event.AjaxListener#processAjax(org.ajax4jsf.event.AjaxEvent)
+     */
+    public void processAjax(AjaxEvent event) {
+        FacesContext facesContext = FacesContext.getCurrentInstance();
 
-	public Object saveState(FacesContext context) {
-		return UIComponentBase.saveAttachedState(context, this.expression);
-	}
+        expression.invoke(facesContext.getELContext(), new Object[] {event});
+    }
 
-	public boolean isTransient() {
-		return false;
-	}
+    public void restoreState(FacesContext context, Object state) {
+        this.expression = (MethodExpression) UIComponentBase.restoreAttachedState(context, state);
+    }
 
-	public void setTransient(boolean newTransientValue) {
-		if (newTransientValue) {
-			throw new IllegalArgumentException();
-		}
-	}
+    public Object saveState(FacesContext context) {
+        return UIComponentBase.saveAttachedState(context, this.expression);
+    }
 
+    public boolean isTransient() {
+        return false;
+    }
+
+    public void setTransient(boolean newTransientValue) {
+        if (newTransientValue) {
+            throw new IllegalArgumentException();
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/RowKeyConverterRule.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/RowKeyConverterRule.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/RowKeyConverterRule.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,8 +18,13 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.webapp.taglib;
 
+import org.richfaces.component.UIDataAdaptor;
+
 import javax.faces.convert.Converter;
 import javax.faces.view.facelets.FaceletContext;
 import javax.faces.view.facelets.MetaRule;
@@ -27,75 +32,65 @@
 import javax.faces.view.facelets.MetadataTarget;
 import javax.faces.view.facelets.TagAttribute;
 
-import org.richfaces.component.UIDataAdaptor;
-
 /**
  * Apply rowKeyConverter to component
  * @author Maksim Kaszynski
  * @since 3.3.1
  */
 public class RowKeyConverterRule extends MetaRule {
+    public static final RowKeyConverterRule INSTANCE = new RowKeyConverterRule();
 
-	static final class DynamicConverterMetaData extends Metadata {
+    /*
+     * (non-Javadoc)
+     *
+     * @see com.sun.facelets.tag.MetaRule#applyRule(java.lang.String,
+     *      com.sun.facelets.tag.TagAttribute,
+     *      com.sun.facelets.tag.MetadataTarget)
+     */
+    @Override
+    public Metadata applyRule(String name, TagAttribute attribute, MetadataTarget meta) {
+        if (meta.isTargetInstanceOf(UIDataAdaptor.class)) {
+            if ("rowKeyConverter".equals(name)) {
+                if (attribute.isLiteral()) {
+                    return new StaticConverterMetadata(attribute.getValue());
+                } else {
+                    return new DynamicConverterMetaData(attribute);
+                }
+            }
+        }
 
-		private final TagAttribute attribute;
+        return null;
+    }
 
-		public DynamicConverterMetaData(TagAttribute attribute) {
-			super();
-			this.attribute = attribute;
-		}
+    static final class DynamicConverterMetaData extends Metadata {
+        private final TagAttribute attribute;
 
-		@Override
-		public void applyMetadata(FaceletContext ctx, Object instance) {
-			((UIDataAdaptor) instance).setValueExpression("rowKeyConverter",
-					attribute.getValueExpression(ctx, Converter.class));
+        public DynamicConverterMetaData(TagAttribute attribute) {
+            super();
+            this.attribute = attribute;
+        }
 
-		}
-	}
+        @Override
+        public void applyMetadata(FaceletContext ctx, Object instance) {
+            ((UIDataAdaptor) instance).setValueExpression("rowKeyConverter",
+                    attribute.getValueExpression(ctx, Converter.class));
+        }
+    }
 
-	static final class StaticConverterMetadata extends Metadata {
 
-		private final String converterId;
+    static final class StaticConverterMetadata extends Metadata {
+        private final String converterId;
 
-		public StaticConverterMetadata(String converterId) {
-			super();
-			this.converterId = converterId;
-		}
+        public StaticConverterMetadata(String converterId) {
+            super();
+            this.converterId = converterId;
+        }
 
-		@Override
-		public void applyMetadata(FaceletContext ctx, Object instance) {
-			Converter converter = ctx.getFacesContext().getApplication()
-					.createConverter(converterId);
-			((UIDataAdaptor) instance).setRowKeyConverter(converter);
+        @Override
+        public void applyMetadata(FaceletContext ctx, Object instance) {
+            Converter converter = ctx.getFacesContext().getApplication().createConverter(converterId);
 
-		}
-	}
-
-	public static final RowKeyConverterRule INSTANCE = new RowKeyConverterRule();
-	
-	
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see com.sun.facelets.tag.MetaRule#applyRule(java.lang.String,
-	 *      com.sun.facelets.tag.TagAttribute,
-	 *      com.sun.facelets.tag.MetadataTarget)
-	 */
-	@Override
-	public Metadata applyRule(String name, TagAttribute attribute,
-			MetadataTarget meta) {
-		
-		if (meta.isTargetInstanceOf(UIDataAdaptor.class)) {
-			if ("rowKeyConverter".equals(name)) {
-				if (attribute.isLiteral()) {
-					return new StaticConverterMetadata(attribute.getValue());
-				} else {
-					return new DynamicConverterMetaData(attribute);
-				}
-			}
-		}
-		
-		return null;
-	}
-
+            ((UIDataAdaptor) instance).setRowKeyConverter(converter);
+        }
+    }
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/UIComponentTagBase.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/UIComponentTagBase.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/UIComponentTagBase.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -18,11 +18,17 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
  */
+
+
+
 package org.ajax4jsf.webapp.taglib;
 
+import org.richfaces.webapp.taglib.UIComponentELTagBase;
+
 import javax.el.ExpressionFactory;
 import javax.el.MethodExpression;
 import javax.el.ValueExpression;
+
 import javax.faces.component.UICommand;
 import javax.faces.component.UIComponent;
 import javax.faces.component.UIGraphic;
@@ -32,155 +38,143 @@
 import javax.faces.event.ActionEvent;
 import javax.faces.event.ValueChangeEvent;
 
-import org.richfaces.webapp.taglib.UIComponentELTagBase;
-
 /**
  * @author Maksim Kaszynski
- * 
+ *
  */
 public abstract class UIComponentTagBase extends UIComponentELTagBase {
+    protected ExpressionFactory getExpressionFactory() {
+        return getFacesContext().getApplication().getExpressionFactory();
+    }
 
-	protected ExpressionFactory getExpressionFactory() {
-		return getFacesContext().getApplication().getExpressionFactory();
-	}
+    protected void setProperty(UIComponent component, String propName, ValueExpression valueExpression) {
+        if (valueExpression != null) {
+            if (valueExpression.isLiteralText()) {
+                component.getAttributes().put(propName, valueExpression.getValue(getELContext()));
+            } else {
+                component.setValueExpression(propName, valueExpression);
+            }
+        }
+    }
 
-	protected void setProperty(UIComponent component, String propName, ValueExpression valueExpression) {
-		if (valueExpression != null) {
-			if (valueExpression.isLiteralText()) {
-				component.getAttributes().put(propName,valueExpression.getValue(getELContext()));
-			} else {
-				component.setValueExpression(propName, valueExpression);
-			}
-		}
-	}
-	
-	protected void setProperty(UIComponent component, Class<?> type,
-			String propName, String value) {
-		if (value != null) {
-			ValueExpression valueExpression = getExpressionFactory()
-					.createValueExpression(getELContext(), value, type);
-			setProperty(component, propName, valueExpression);
-		}
-	}
+    protected void setProperty(UIComponent component, Class<?> type, String propName, String value) {
+        if (value != null) {
+            ValueExpression valueExpression = getExpressionFactory().createValueExpression(getELContext(), value, type);
 
-	protected void setIntegerProperty(UIComponent component, String propName,
-			ValueExpression value) {
-		setProperty(component, propName, value);
-	}
+            setProperty(component, propName, valueExpression);
+        }
+    }
 
-	protected void setLongProperty(UIComponent component, String propName,
-			ValueExpression value) {
-		setProperty(component, propName, value);
-	}
+    protected void setIntegerProperty(UIComponent component, String propName, ValueExpression value) {
+        setProperty(component, propName, value);
+    }
 
-	protected void setFloatProperty(UIComponent component, String propName,
-			ValueExpression value) {
-		setProperty(component, propName, value);
-	}
+    protected void setLongProperty(UIComponent component, String propName, ValueExpression value) {
+        setProperty(component, propName, value);
+    }
 
-	protected void setDoubleProperty(UIComponent component, String propName,
-			ValueExpression value) {
-		setProperty(component, propName, value);
-	}
+    protected void setFloatProperty(UIComponent component, String propName, ValueExpression value) {
+        setProperty(component, propName, value);
+    }
 
-	protected void setStringProperty(UIComponent component, String propName,
-			ValueExpression value) {
-		setProperty(component, propName, value);
-	}
+    protected void setDoubleProperty(UIComponent component, String propName, ValueExpression value) {
+        setProperty(component, propName, value);
+    }
 
-	protected void setBooleanProperty(UIComponent component, String propName,
-			ValueExpression value) {
-		setProperty(component, propName, value);
-	}
+    protected void setStringProperty(UIComponent component, String propName, ValueExpression value) {
+        setProperty(component, propName, value);
+    }
 
-	protected void setIntegerProperty(UIComponent component, String propName,
-			String value) {
-		setProperty(component, Integer.class, propName, value);
-	}
+    protected void setBooleanProperty(UIComponent component, String propName, ValueExpression value) {
+        setProperty(component, propName, value);
+    }
 
-	protected void setLongProperty(UIComponent component, String propName,
-			String value) {
-		setProperty(component, Long.class, propName, value);
-	}
+    protected void setIntegerProperty(UIComponent component, String propName, String value) {
+        setProperty(component, Integer.class, propName, value);
+    }
 
-	protected void setFloatProperty(UIComponent component, String propName,
-			String value) {
-		setProperty(component, Float.class, propName, value);
-	}
+    protected void setLongProperty(UIComponent component, String propName, String value) {
+        setProperty(component, Long.class, propName, value);
+    }
 
-	protected void setDoubleProperty(UIComponent component, String propName,
-			String value) {
-		setProperty(component, Double.class, propName, value);
-	}
+    protected void setFloatProperty(UIComponent component, String propName, String value) {
+        setProperty(component, Float.class, propName, value);
+    }
 
-	protected void setStringProperty(UIComponent component, String propName,
-			String value) {
-		setProperty(component, String.class, propName, value);
-	}
+    protected void setDoubleProperty(UIComponent component, String propName, String value) {
+        setProperty(component, Double.class, propName, value);
+    }
 
-	protected void setBooleanProperty(UIComponent component, String propName,
-			String value) {
-		setProperty(component, Boolean.class, propName, value);
-	}
-	protected void setValueProperty(UIComponent component, String value) {
-		if (value != null) {
-			ValueExpression expression = getExpressionFactory()
-					.createValueExpression(getELContext(), value, Object.class);
+    protected void setStringProperty(UIComponent component, String propName, String value) {
+        setProperty(component, String.class, propName, value);
+    }
 
-			setValueProperty(component, expression);
-		}
-	}
-	protected void setValueProperty(UIComponent component, ValueExpression expression) {
-		if (expression != null) {
-			String value = expression.getExpressionString();
-			if (!expression.isLiteralText()) {
-				component.setValueExpression("value", expression);
-			} else if (component instanceof UICommand) {
-				((UICommand) component).setValue(value);
-			} else if (component instanceof UIParameter) {
-				((UIParameter) component).setValue(value);
-			} else if (component instanceof UISelectBoolean) {
-				((UISelectBoolean) component).setValue(Boolean.valueOf(value));
-			} else if (component instanceof UIGraphic) {
-				((UIGraphic) component).setValue(value);
-			}
-			// Since many input components are ValueHolders the special
-			// components
-			// must come first, ValueHolder is the last resort.
-			else if (component instanceof ValueHolder) {
-				((ValueHolder) component).setValue(value);
-			} else {
-				component.getAttributes().put("value", value);
-			}
-		}
-	}
+    protected void setBooleanProperty(UIComponent component, String propName, String value) {
+        setProperty(component, Boolean.class, propName, value);
+    }
 
-	public boolean isValueReference(String s) {
-		return !getExpressionFactory().createValueExpression(s, Object.class).isLiteralText();
-	}
-	
+    protected void setValueProperty(UIComponent component, String value) {
+        if (value != null) {
+            ValueExpression expression = getExpressionFactory().createValueExpression(getELContext(), value,
+                                             Object.class);
+
+            setValueProperty(component, expression);
+        }
+    }
+
+    protected void setValueProperty(UIComponent component, ValueExpression expression) {
+        if (expression != null) {
+            String value = expression.getExpressionString();
+
+            if (!expression.isLiteralText()) {
+                component.setValueExpression("value", expression);
+            } else if (component instanceof UICommand) {
+                ((UICommand) component).setValue(value);
+            } else if (component instanceof UIParameter) {
+                ((UIParameter) component).setValue(value);
+            } else if (component instanceof UISelectBoolean) {
+                ((UISelectBoolean) component).setValue(Boolean.valueOf(value));
+            } else if (component instanceof UIGraphic) {
+                ((UIGraphic) component).setValue(value);
+            } else if (component instanceof ValueHolder) {
+
+                // Since many input components are ValueHolders the special components
+                // must come first, ValueHolder is the last resort.
+                ((ValueHolder) component).setValue(value);
+            } else {
+                component.getAttributes().put("value", value);
+            }
+        }
+    }
+
+    public boolean isValueReference(String s) {
+        return !getExpressionFactory().createValueExpression(s, Object.class).isLiteralText();
+    }
+
     protected void setActionProperty(UIComponent component, String action) {
         if (action != null) {
-        	MethodExpression expression = 
-        		getExpressionFactory().createMethodExpression(getELContext(), action, String.class, new Class[] {});
-        	setActionProperty(component, expression);
+            MethodExpression expression = getExpressionFactory().createMethodExpression(getELContext(), action,
+                                              String.class, new Class[] {});
+
+            setActionProperty(component, expression);
         }
     }
 
-    protected void setActionListenerProperty(UIComponent component, String actionListener){
+    protected void setActionListenerProperty(UIComponent component, String actionListener) {
         if (actionListener != null) {
-        	MethodExpression expression = 
-        		getExpressionFactory().createMethodExpression(getELContext(), actionListener, String.class, new Class[] {ActionEvent.class});
-        	setActionListenerProperty(component, expression);
+            MethodExpression expression = getExpressionFactory().createMethodExpression(getELContext(), actionListener,
+                                              String.class, new Class[] {ActionEvent.class});
+
+            setActionListenerProperty(component, expression);
         }
     }
 
     protected void setValueChangedListenerProperty(UIComponent component, String valueChangedListener) {
         if (valueChangedListener != null) {
-        	MethodExpression expression = 
-        		getExpressionFactory().createMethodExpression(getELContext(), valueChangedListener, String.class, new Class[] {ValueChangeEvent.class});
-        	setValueChangeListenerProperty(component, expression);
+            MethodExpression expression = getExpressionFactory().createMethodExpression(getELContext(),
+                                              valueChangedListener, String.class, new Class[] {ValueChangeEvent.class});
+
+            setValueChangeListenerProperty(component, expression);
         }
     }
-
 }

Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/package-info.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/package-info.java	2009-11-01 16:51:11 UTC (rev 15798)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/webapp/taglib/package-info.java	2009-11-01 17:06:52 UTC (rev 15799)
@@ -1,3 +1,4 @@
+
 /**
  * Basic tag classes
  */



More information about the richfaces-svn-commits mailing list