You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@myfaces.apache.org by ar...@apache.org on 2008/10/09 00:23:43 UTC

svn commit: r703009 - in /myfaces/trinidad/trunk: ./ trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/ trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/xhtml/ trinidad-impl/src/main/java/org/a...

Author: arobinson74
Date: Wed Oct  8 15:23:39 2008
New Revision: 703009

URL: http://svn.apache.org/viewvc?rev=703009&view=rev
Log:
Fix for TRINIDAD-205
Implemented the fix using the recommended method by Jeanne Waldman and used the previous changes by Simon Lessard to handle the multiple CSS files

Added:
    myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/util/StyleWriterFactory.java
      - copied unchanged from r702988, myfaces/trinidad/trunk_1.2.x/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/util/StyleWriterFactory.java
Modified:
    myfaces/trinidad/trunk/   (props changed)
    myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/CoreRenderingContext.java
    myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/StyleContextImpl.java
    myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/xhtml/StyleSheetRenderer.java
    myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/skin/SkinStyleProvider.java
    myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/StyleProvider.java
    myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/cache/FileSystemStyleCache.java
    myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/util/CSSGenerationUtils.java

Propchange: myfaces/trinidad/trunk/
------------------------------------------------------------------------------
    svn:mergeinfo = /myfaces/trinidad/trunk_1.2.x:702988,703003

Modified: myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/CoreRenderingContext.java
URL: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/CoreRenderingContext.java?rev=703009&r1=703008&r2=703009&view=diff
==============================================================================
--- myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/CoreRenderingContext.java (original)
+++ myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/CoreRenderingContext.java Wed Oct  8 15:23:39 2008
@@ -31,36 +31,30 @@
 import javax.servlet.ServletContext;
 
 import org.apache.myfaces.trinidad.context.AccessibilityProfile;
-import org.apache.myfaces.trinidad.logging.TrinidadLogger;
-
 import org.apache.myfaces.trinidad.context.Agent;
-import org.apache.myfaces.trinidad.context.RequestContext;
-
 import org.apache.myfaces.trinidad.context.FormData;
 import org.apache.myfaces.trinidad.context.LocaleContext;
-import org.apache.myfaces.trinidad.context.RenderingContext;
 import org.apache.myfaces.trinidad.context.PartialPageContext;
-
+import org.apache.myfaces.trinidad.context.RenderingContext;
+import org.apache.myfaces.trinidad.context.RequestContext;
+import org.apache.myfaces.trinidad.logging.TrinidadLogger;
+import org.apache.myfaces.trinidad.skin.Icon;
 import org.apache.myfaces.trinidad.skin.Skin;
 import org.apache.myfaces.trinidad.skin.SkinFactory;
-import org.apache.myfaces.trinidad.skin.Icon;
-
+import org.apache.myfaces.trinidadinternal.agent.AgentUtil;
 import org.apache.myfaces.trinidadinternal.agent.TrinidadAgent;
 import org.apache.myfaces.trinidadinternal.agent.TrinidadAgentImpl;
-import org.apache.myfaces.trinidadinternal.agent.AgentUtil;
-
-
-import org.apache.myfaces.trinidadinternal.skin.SkinNotAvailable;
-
-import org.apache.myfaces.trinidadinternal.style.StyleContext;
-import org.apache.myfaces.trinidadinternal.style.util.StyleUtils;
 import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.PartialPageUtils;
 import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.XhtmlConstants;
 import org.apache.myfaces.trinidadinternal.share.nls.MutableDecimalFormatContext;
 import org.apache.myfaces.trinidadinternal.share.nls.MutableLocaleContext;
 import org.apache.myfaces.trinidadinternal.skin.RequestSkinWrapper;
+import org.apache.myfaces.trinidadinternal.skin.SkinNotAvailable;
+import org.apache.myfaces.trinidadinternal.style.StyleContext;
+import org.apache.myfaces.trinidadinternal.style.util.StyleUtils;
 import org.apache.myfaces.trinidadinternal.util.nls.LocaleUtils;
 
+
 public class CoreRenderingContext extends RenderingContext
 {
   /**
@@ -246,8 +240,7 @@
     if (_styleContext == null)
     {
       FacesContext fContext = FacesContext.getCurrentInstance();
-      _styleContext = new StyleContextImpl(this,
-                                           getTemporaryDirectory(fContext));
+      _styleContext = new StyleContextImpl(this, getTemporaryDirectory(fContext));
     }
 
     return _styleContext;

Modified: myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/StyleContextImpl.java
URL: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/StyleContextImpl.java?rev=703009&r1=703008&r2=703009&view=diff
==============================================================================
--- myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/StyleContextImpl.java (original)
+++ myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/StyleContextImpl.java Wed Oct  8 15:23:39 2008
@@ -6,9 +6,9 @@
  *  to you 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
@@ -38,6 +38,7 @@
 import org.apache.myfaces.trinidadinternal.style.StyleMap;
 import org.apache.myfaces.trinidadinternal.style.StyleProvider;
 
+
 class StyleContextImpl implements StyleContext
 {
   public StyleContextImpl(
@@ -47,7 +48,7 @@
     _arc = arc;
     _generatedFilesPath = generatedFilesPath;
 
-    // Our style/skin code assumes that we have access to a 
+    // Our style/skin code assumes that we have access to a
     // non-null accessibility profile.  Check that here.
     assert(_arc.getAccessibilityProfile() != null);
   }
@@ -145,12 +146,12 @@
     {
       return null;
     }
-    
+
     public Map<String, String> getShortStyleClasses(StyleContext context)
     {
       return null;
     }
-    
+
     public List<String> getStyleSheetURIs(StyleContext context)
     {
       return null;
@@ -165,12 +166,12 @@
     {
       return null;
     }
-    
+
     public ConcurrentMap<Object, Object> getSkinProperties(StyleContext context)
     {
       return null;
     }
-    
+
     private static StyleProvider _sInstance;
   }
 

Modified: myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/xhtml/StyleSheetRenderer.java
URL: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/xhtml/StyleSheetRenderer.java?rev=703009&r1=703008&r2=703009&view=diff
==============================================================================
--- myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/xhtml/StyleSheetRenderer.java (original)
+++ myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/renderkit/core/xhtml/StyleSheetRenderer.java Wed Oct  8 15:23:39 2008
@@ -19,6 +19,7 @@
 package org.apache.myfaces.trinidadinternal.renderkit.core.xhtml;
 
 import java.io.IOException;
+
 import java.util.List;
 import java.util.Map;
 
@@ -35,6 +36,7 @@
 import org.apache.myfaces.trinidadinternal.style.StyleContext;
 import org.apache.myfaces.trinidadinternal.style.StyleProvider;
 
+
 /**
  * Renderer for meta data section of the document--a.k.a &lt;head&gt;.
  * <p>
@@ -86,7 +88,7 @@
     StyleProvider provider = sContext.getStyleProvider();
     if (provider != null)
     {
-      List<String> hrefs = provider.getStyleSheetURIs(sContext);
+      List<String> uris = provider.getStyleSheetURIs(sContext);
 
       // If the requestMap has a skin-id, a skin's stylesheet's id and suppressStylesheet
       // is true, and the skin information matches our current skin, then it is safe
@@ -95,33 +97,36 @@
       boolean suppressStylesheet = _isSuppressStylesheet(context, arc);
       if (!suppressStylesheet)
       {
-        if (hrefs != null && !hrefs.isEmpty())
+        if (uris != null && !uris.isEmpty())
         {
           ExternalContext externalContext = context.getExternalContext();
           String contextUri = externalContext.getRequestContextPath();
           String baseURL = contextUri + XhtmlConstants.STYLES_CACHE_DIRECTORY;
 
           String outputMode = arc.getOutputMode();
-          boolean asScript = XhtmlConstants.OUTPUT_MODE_PORTLET.equals(outputMode) 
-              && supportsScripting(arc);
-          
-          for (String href : hrefs)
+          // =-=AEW Don't like hardcoding facet names...
+          if (XhtmlConstants.OUTPUT_MODE_PORTLET.equals(outputMode) &&
+              supportsScripting(arc))
           {
-            String url = baseURL + href;
-            if (asScript)
+            writer.startElement("script", null);
+            writer.writeText("var _adfSS;if(!_adfSS){_adfSS=1;", null);
+            for (String uri : uris)
             {
-              writer.startElement("script", null);
-              writer.writeText("var _adfSS;if(!_adfSS){_adfSS=1;document.write(\"" +
+              writer.writeText("document.write(\"" +
                             "<link rel=\\\"stylesheet\\\" "+
                             "charset=\\\"UTF-8\\\" type=\\\"text/css\\\" " +
                             "href=\\\"",
                 null);
-              String uri = context.getExternalContext().encodeResourceURL(url);
+              uri = context.getExternalContext().encodeResourceURL(baseURL + uri);
               writer.writeText(uri, null);
-              writer.writeText("\\\">\")}", null);
-              writer.endElement("script");
+              writer.writeText("\\\">\");", null);
             }
-            else
+            writer.writeText("}", null);
+            writer.endElement("script");
+          }
+          else
+          {
+            for (String uri : uris)
             {
               writer.startElement("link", null);
               renderId(context, comp);
@@ -131,7 +136,7 @@
               String type = provider.getContentStyleType(sContext);
               writer.writeAttribute("type", type, null);
 
-              renderEncodedResourceURI(context, "href", url);
+              renderEncodedResourceURI(context, "href", baseURL + uri);
               writer.endElement("link");
             }
           }
@@ -160,11 +165,11 @@
   }
 
   // returns true if we want to suppress the stylesheet.
-  // It checks for suppressStylesheet flag on the request map and 
+  // It checks for suppressStylesheet flag on the request map and
   // for the skin-id on the request map to exist identically on the server.
   //
   // This is usually called in a portal environment when we want to suppress the
-  // producer (portlet)'s stylesheet and use the consumer (portal container)'s 
+  // producer (portlet)'s stylesheet and use the consumer (portal container)'s
   // instead for performance enhancements.
   private boolean _isSuppressStylesheet(FacesContext context,  RenderingContext arc)
   {

Modified: myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/skin/SkinStyleProvider.java
URL: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/skin/SkinStyleProvider.java?rev=703009&r1=703008&r2=703009&view=diff
==============================================================================
--- myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/skin/SkinStyleProvider.java (original)
+++ myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/skin/SkinStyleProvider.java Wed Oct  8 15:23:39 2008
@@ -193,12 +193,11 @@
   @Override
   protected String getTargetStyleSheetName(
     StyleContext       context,
-    StyleSheetDocument document,
-    int                partNumber
+    StyleSheetDocument document
     )
   {
     // Get the base name from the FileSystemStyleCache.
-    String name = super.getTargetStyleSheetName(context, document, partNumber);
+    String name = super.getTargetStyleSheetName(context, document);
 
     // Use the LAF's id as a prefix
     String id = _skin.getId();

Modified: myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/StyleProvider.java
URL: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/StyleProvider.java?rev=703009&r1=703008&r2=703009&view=diff
==============================================================================
--- myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/StyleProvider.java (original)
+++ myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/StyleProvider.java Wed Oct  8 15:23:39 2008
@@ -6,9 +6,9 @@
  *  to you 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
@@ -24,13 +24,14 @@
 
 import org.apache.myfaces.trinidad.skin.Icon;
 
+
 /**
  * The StyleProvider API is used to access context-dependent style
  * information.  Style information is exposed in two ways - as
  * CSS style sheet URIs (via getStyleSheetURI()), or as Style objects
  * (via getStyleMap()).  Both methods take a StyleContext object,
  * which describes the target end user environment.
- * 
+ *
  * In addition to providing access to style-related information, the
  * StyleProvider also provides access to Icons which are defined within
  * style sheets via the getIcons() API.
@@ -48,7 +49,7 @@
    * defined by the StyleProvider.
    */
   public String getContentStyleType(StyleContext context);
-  
+
   /**
    * Returns a Map which maps style class names to
    * equivalent shorter names.
@@ -60,19 +61,19 @@
   public Map<String, String> getShortStyleClasses(StyleContext context);
 
   /**
-   * Returns the URIs of the CSS style sheet to use for the
+   * Returns the URI of the CSS style sheet to use for the
    * end user environment specified via the StyleContext.
-   * @param context The context which describes the end user 
+   * @param context The context which describes the end user
    *   environment for this request
-   * @return A CSS style sheet URI
+   * @return A list of CSS style sheet URIs
    */
   public List<String> getStyleSheetURIs(StyleContext context);
 
   /**
-   * Returns a StyleMap object, which can be used to 
+   * Returns a StyleMap object, which can be used to
    * retreive Style objects for the specified context.
    *
-   * @param context The context which describes the target end user 
+   * @param context The context which describes the target end user
    *   environment
    * @return A StyleMap object which exposes the Styles for the
    *  specified context.
@@ -81,11 +82,11 @@
 
   /**
    * Returns a map of icon names to Icon instances.
-   * 
+   *
    * The returned map is both mutable and threadsafe.  This allows
    * request/context-specific icons to be cached on the icon map.
-   * 
-   * @param context The context which describes the target end user 
+   *
+   * @param context The context which describes the target end user
    *   environment
    * @return A ConcurrentMap which exposes the Icons for the
    *  specified context.
@@ -94,14 +95,14 @@
 
   /**
    * Returns a map of skin property keys to skin property Object instances.
-   * 
+   *
    * The returned map is both mutable and threadsafe.  This allows
    * request/context-specific skin properties to be cached on the skin property map.
-   * 
-   * @param context The context which describes the target end user 
+   *
+   * @param context The context which describes the target end user
    *   environment
    * @return A ConcurrentMap which exposes the skin properties for the
    *  specified context.
    */
-  public ConcurrentMap<Object, Object> getSkinProperties(StyleContext context);  
+  public ConcurrentMap<Object, Object> getSkinProperties(StyleContext context);
 }

Modified: myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/cache/FileSystemStyleCache.java
URL: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/cache/FileSystemStyleCache.java?rev=703009&r1=703008&r2=703009&view=diff
==============================================================================
--- myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/cache/FileSystemStyleCache.java (original)
+++ myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/cache/FileSystemStyleCache.java Wed Oct  8 15:23:39 2008
@@ -22,10 +22,10 @@
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.io.UnsupportedEncodingException;
+
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -33,6 +33,7 @@
 import java.util.HashSet;
 import java.util.Hashtable;
 import java.util.Iterator;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -67,6 +68,7 @@
 import org.apache.myfaces.trinidadinternal.style.StyleProvider;
 import org.apache.myfaces.trinidadinternal.style.util.CSSGenerationUtils;
 import org.apache.myfaces.trinidadinternal.style.util.NameUtils;
+import org.apache.myfaces.trinidadinternal.style.util.StyleWriterFactory;
 import org.apache.myfaces.trinidadinternal.style.xml.StyleSheetDocumentUtils;
 import org.apache.myfaces.trinidadinternal.style.xml.parse.IconNode;
 import org.apache.myfaces.trinidadinternal.style.xml.parse.PropertyNode;
@@ -75,8 +77,10 @@
 import org.apache.myfaces.trinidadinternal.style.xml.parse.StyleSheetDocument;
 import org.apache.myfaces.trinidadinternal.style.xml.parse.StyleSheetNode;
 import org.apache.myfaces.trinidadinternal.util.nls.LocaleUtils;
+
 import org.xml.sax.SAXException;
 
+
 /**
  * The FileSystemStyleCache is a StyleProvider implementation which
  * caches generated CSS style sheets on the file system.
@@ -105,7 +109,6 @@
     return "text/css";
   }
 
-
   /**
    * Creates a FileSystemStyleCache.
    *
@@ -157,13 +160,14 @@
    */
   public List<String> getStyleSheetURIs(StyleContext context)
   {
-
     Entry entry = _getEntry(context);
 
     if (entry == null)
+    {
       return null;
+    }
 
-    return entry.uriList;
+    return entry.uris;
   }
 
   /**
@@ -305,9 +309,10 @@
    * @param context The StyleContext
    * @param document The StyleSheetDocument which provides the styles
    */
-  protected String getTargetStyleSheetName(StyleContext       context,
-                                           StyleSheetDocument document, 
-                                           int 			          partNumber)
+  protected String getTargetStyleSheetName(
+    StyleContext       context,
+    StyleSheetDocument document
+    )
   {
     StringBuffer buffer = new StringBuffer();
 
@@ -331,12 +336,6 @@
       buffer.append(_COMPRESSED);
     }
     
-    if (partNumber > 1)
-    {
-        buffer.append(_NAME_SEPARATOR);
-        buffer.append(partNumber);
-    }
-    
     buffer.append(_CSS_EXTENSION);
 
     return buffer.toString();
@@ -424,12 +423,8 @@
       return entry;
 
     // Next see if this is an entry which is compatible with this request
-    entry = _getCompatibleEntry( context,
-                                 document,
-                                 cache,
-                                 key,
-                                 entryCache,
-                                 checkModified);
+    entry = _getCompatibleEntry(context, document, cache, key, entryCache, checkModified);
+
     if (entry != null)
       return entry;
 
@@ -445,16 +440,11 @@
                         checkModified);
   }
 
-  // Returns the cache entry with the specified key
   private Entry _getEntry(
-    Hashtable<Key, Entry> cache,
-    Key                   key,
-    boolean               checkModified)
-  {
-    return _getEntryInternal(cache, key, checkModified);
-  }
-
-  private Entry _getEntryInternal(Hashtable<?, Entry> cache, Object key, boolean checkModified)
+    Map<?, Entry> cache,
+    Object        key,
+    boolean       checkModified
+    )
   {
     Entry entry = cache.get(key);
     if (entry == null)
@@ -464,12 +454,11 @@
     
     if (checkModified)
     {
-      List<String> uris = entry.uriList;
-      assert uris != null;
-      assert !uris.isEmpty();
+      List<String> uris = entry.uris;
+      assert uris != null && !uris.isEmpty();
 
       boolean valid = true;
-      List<File> existing = new ArrayList<File>(uris.size());
+      List<File> existing = new LinkedList<File>();
       // Make sure the entry's file exists.  If it no longer
       // exists, we remove the entry from the cache
       for (String name : uris)
@@ -504,11 +493,13 @@
     return entry;
   }
 
-  // Creates and caches an Entry for the specified StyleContext
-  // This generates a style sheet for the specific StyleContext
-  // (locale, direction, etc), and puts that style sheet's uri in the Entry.
-  // It also caches it in the "normal" cache (the one that is based on the StyleContext),
-  // and the entry cache (the one that is based on the StyleSheetNodes)
+  /**
+   * Creates and caches an Entry for the specified StyleContext
+   * This generates a style sheet for the specific StyleContext
+   * (locale, direction, etc), and puts that style sheet's uri in the Entry.
+   * It also caches it in the "normal" cache (the one that is based on the StyleContext),
+   * and the entry cache (the one that is based on the StyleSheetNodes)
+   */
   private Entry _createEntry(
     StyleContext             context,
     StyleSheetDocument       document,
@@ -525,29 +516,32 @@
     // info that is in the StyleContext.
     StyleNode[] styles = _getStyleContextResolvedStyles(context, document);
     if (styles == null)
-    {
       return null;
-    }
 
     // Generate the style sheet file, if it isn't already generated,
     // and return the uri.
-    List<String> fileNames = _createStyleSheetFile(context, document, styles,
-                                                   shortStyleClassMap, namespacePrefixes, 
+    List<String> uris = _createStyleSheetFiles(context,
+                                       document,
+                                       styles,
+                                       shortStyleClassMap,
+                                       namespacePrefixes,
                                                    checkModified);
 
-    _LOG.fine("Finished processing stylesheets {0}", fileNames);
+    _LOG.fine("Finished processing stylesheet {0}", uris);
     
     
     // Next, get the fully resolved icons and skin properties for this context.
     // This will be those Icons and Skin Properties that match the locale, direction,
     // browser, etc -- the info that is in the StyleContext
-    ConcurrentMap<String, Icon> icons = _getStyleContextResolvedIcons(context, document);
-    ConcurrentMap<Object, Object> skinProperties = _getStyleContextResolvedSkinProperties(context, document);
+    ConcurrentMap<String, Icon> icons =
+      _getStyleContextResolvedIcons(context, document);
+    ConcurrentMap<Object, Object> skinProperties =
+      _getStyleContextResolvedSkinProperties(context, document);
 
     // Create a new entry and cache it in the "normal" cache. The "normal" cache is one
     // where the key is the Key object which is built based on information from the StyleContext,
     // like browser, agent, locale, direction.
-    Entry entry = new Entry(fileNames, new StyleMapImpl(), icons, skinProperties);
+    Entry entry = new Entry(uris, new StyleMapImpl(), icons, skinProperties);
     cache.put(key, entry);
 
     // Also, cache the new entry in the entry cache
@@ -557,31 +551,34 @@
     return entry;
   }
 
-  // Look in the entry cache for a compatible entry.
-  // A compatible entry is one with the same DerivationKey, which is essentially the
-  // same StyleSheetNodes.
+  /**
+   * Look in the entry cache for a compatible entry.
+   * A compatible entry is one with the same DerivationKey, which is essentially the
+   * same StyleSheetNodes.
+   */
   private Entry _getCompatibleEntry(
     StyleContext             context,
     StyleSheetDocument       document,
-    Hashtable<Key, Entry>    cache,
+    Map<Key, Entry>    cache,
     Key                      key,
-    Hashtable<Object, Entry> entryCache,
+    Map<Object, Entry> entryCache,
     boolean                  checkModified
     )
   {
     DerivationKey derivationKey = _getDerivationKey(context, document);
-    Entry entry = _getEntryInternal(entryCache, derivationKey, checkModified);
+    Entry entry = _getEntry(entryCache, derivationKey, checkModified);
     if (entry != null)
     {
       // If we've got a compatible entry, cache it
       cache.put(key, entry);
     }
-    
     return entry;
   }
 
-  // Returns the derivation key that would be used for entries
-  // based on the provided context
+  /**
+   * Returns the derivation key that would be used for entries
+   * based on the provided context
+   */
   private DerivationKey _getDerivationKey(
     StyleContext context,
     StyleSheetDocument document
@@ -608,7 +605,9 @@
     return new DerivationKey(context, styleSheets);
   }
 
-  // Returns the StyleSheetDocument, parsing the source file if necessary
+  /**
+   * Returns the StyleSheetDocument, parsing the source file if necessary
+   */
   private StyleSheetDocument _getStyleSheetDocument(StyleContext context)
   {
     StyleSheetDocument document = _document;
@@ -637,10 +636,12 @@
     return document;
   }
 
-  // Returns an array of fully resolved StyleNodes for the
-  // specified StyleContext  and StyleSheetDocument.
-  // This will be those StyleNodes that match the locale, direction, browser, etc -- the
-  // info that is in the StyleContext.
+  /**
+   * Returns an array of fully resolved StyleNodes for the
+   * specified StyleContext  and StyleSheetDocument.
+   * This will be those StyleNodes that match the locale, direction, browser, etc -- the
+   * info that is in the StyleContext.
+   */
   private StyleNode[] _getStyleContextResolvedStyles(
     StyleContext context,
     StyleSheetDocument document
@@ -661,8 +662,10 @@
     return v.toArray(new StyleNode[v.size()]);
   }
 
-  // Returns a Map of skin property names to values for the specified
-  // styleSheetNodes that have been filtered from the StyleContext and StyleSheetDocument.
+  /**
+   * Returns a Map of skin property names to values for the specified
+   * styleSheetNodes that have been filtered from the StyleContext and StyleSheetDocument.
+   */
   private ConcurrentMap<Object, Object> _getStyleContextResolvedSkinProperties(
     StyleContext       context,
     StyleSheetDocument document
@@ -688,8 +691,10 @@
     return skinProperties;
   }
 
-  // Returns a Map of icon names to Icons for the specified
-  // styleSheetNodes that have been filtered from the StyleContext and StyleSheetDocument.
+  /**
+   * Returns a Map of icon names to Icons for the specified
+   * styleSheetNodes that have been filtered from the StyleContext and StyleSheetDocument.
+   */
   private ConcurrentMap<String, Icon> _getStyleContextResolvedIcons(
     StyleContext       context,
     StyleSheetDocument document
@@ -715,9 +720,11 @@
     return icons;
   }
 
-  // Generates the CSS file for the specified context and styles.
-  // Returns the name of the generated CSS file.
-  private List<String> _createStyleSheetFile(
+  /**
+   * Generates the CSS files for the specified context and styles.
+   * @return the names of the generated CSS files.
+   */
+  private List<String> _createStyleSheetFiles(
     StyleContext        context,
     StyleSheetDocument  document,
     StyleNode[]         styles,
@@ -725,85 +732,81 @@
     String[]            namespacePrefixes,
     boolean             checkModified)
   {
-	  int maxSelectorPerFile;
-	  if (TrinidadAgent.APPLICATION_IEXPLORER == context.getAgent().getAgentApplication())
+    // Get the current files
+    List<File> outputFiles = _getOutputFiles(context, document);
+
+    // If at least one output file exists, check the last modified time.
+    if (!outputFiles.isEmpty())
 	  {
-		  maxSelectorPerFile = _MSIE_SELECTOR_LIMIT;
-	  }
-	  else
+      if (checkModified)
 	  {
-	    maxSelectorPerFile = styles.length;
+        if (!_checkSourceModified(document, outputFiles.get(0)))
+        {
+          return _getFileNames(outputFiles);
 	  }
-	  
-    // Get a name for the new style sheet
-    File[] outputFiles = _getOutputFiles(context, document, styles.length, maxSelectorPerFile);
-    if (outputFiles[0].exists())
-    {
-      if (_isDirty(document, outputFiles[0], checkModified))
-      {
+        // If the output file is older than the source file, we
+        // need to regenerate the output file.  But first we
+        // need to delete the old output file before we attempt to
+        // create a new version.
         _deleteAll(outputFiles);
       }
       else
       {
-        return getFileNames(outputFiles);
+        return _getFileNames(outputFiles);
       }
     }
     
-    Skin skin = RenderingContext.getCurrentInstance().getSkin();
+    // Make sure the output directory exists in case it's been
+    // blown away since the creation of the cache
+    File outputDir = new File(_targetPath);
+    if (!outputDir.exists())
+      outputDir.mkdirs();
     
+    // Write out the style sheet
     // First figure out whether or not we need to compress the style classes.
     // We don't compress the style classes if the content compression flag is disabled or
     // if the skin is a portlet skin.
+    Skin skin = RenderingContext.getCurrentInstance().getSkin();
     boolean compressStyles = _isCompressStyles(skin);
 
-    List<File> createdFiles = new ArrayList<File>(outputFiles.length);
-    for (int i = 0; i < outputFiles.length; i++)
-    {
-      File file = outputFiles[i];
+    StyleWriterFactoryImpl writerFactory = new StyleWriterFactoryImpl(_targetPath,
+      getTargetStyleSheetName(context, document));
+    CSSGenerationUtils.writeCSS(context,
+                                skin.getStyleSheetName(),
+                                styles,
+                                writerFactory,
+                                compressStyles,
+                                shortStyleClassMap,
+                                namespacePrefixes,
+                                _STYLE_KEY_MAP
+                                );
       
-      // Now, try to create the files and get the writer to output to
-      PrintWriter writer = _getWriterToNewFile(file);
-      if (writer == null)
-      {
-        _deleteAll(createdFiles);
-        return null;
+    writerFactory.close();
+
+    // Return the name of the new style sheet
+    return _getFileNames(writerFactory.getFiles());
       }
       
-      try
+  private File _getOutputFile(String name, int number)
       {
-        // Write out the style sheet
-        CSSGenerationUtils.writeCSS(context, skin.getStyleSheetName(), styles, writer,
-                                    compressStyles, shortStyleClassMap, namespacePrefixes,
-                                    _STYLE_KEY_MAP, i * maxSelectorPerFile, maxSelectorPerFile);
-      }
-      finally
+    assert number >= 1;
+    if (number == 1)
       {
-        writer.close();
+      return new File(_targetPath, name);
       }
-
-      // We never want to do anything other then read it or delete it:
-      file.setReadOnly();
-    }
-
-    return getFileNames(outputFiles);
-  }
-  
-  private boolean _isDirty(StyleSheetDocument document, File file, boolean checkModified)
+    int index = name.lastIndexOf(".");
+    if (index < 0)
   {
-	  // If the output file already exists, check the last modified time.
-		return checkModified && _checkSourceModified(document, file);
+      return new File(_targetPath, name + number);
   }
-  
-  private void _deleteAll(File[] files)
+    else
   {
-    for (File file : files)
-    {
-      if (file.exists())
-      {
-        file.delete();
+      // file name + number + file extension
+      return new File(_targetPath,
+        new StringBuilder(name.length() + 2).append(name.substring(0, index)).append(number)
+          .append(name.substring(index)).toString());
       }
     }
-  }
   
   private void _deleteAll(Iterable<File> files)
   {
@@ -816,9 +819,11 @@
     }
   }
   
-  // First figure out whether or not we need to compress the style classes.
-  // We don't compress the style classes if the content compression flag is disabled or
-  // if the skin is a portlet skin.
+  /**
+   * First figure out whether or not we need to compress the style classes.
+   * We don't compress the style classes if the content compression flag is disabled or
+   * if the skin is a portlet skin.
+   */
   private boolean _isCompressStyles(Skin skin)
   {
     if (skin == null)
@@ -836,66 +841,70 @@
                                              !isPortletSkin;
   }
 
-  // Returns the name of the output file to use for the
-  // style sheet associated with the specified context
-  private File[] _getOutputFiles(
+  private List<String> _getFileNames(List<File> files)
+  {
+    List<String> names = new ArrayList<String>(files.size());
+    for (File file : files)
+    {
+      names.add(file.getName());
+    }
+    return Collections.unmodifiableList(names);
+  }
+
+  /**
+   * Returns the name of the output files that have been created for the given context and
+   * document. If there are no files found, and empty list will be returned.
+   * @return The list of list that currently exist, or null if none found
+   */
+  private List<File> _getOutputFiles(
     StyleContext context,
-    StyleSheetDocument document,
-    int selectorCount,
-    int maxSelectorPerFile
+    StyleSheetDocument document
     )
   {
-    int fileCount = selectorCount / maxSelectorPerFile;
-    if (selectorCount % maxSelectorPerFile != 0)
-    {
-      fileCount++;
+    // use a linked list as we only iterate and linked lists are faster for iteration & appending
+    // than array lists.
+    List<File> files = new LinkedList<File>();
+    String name = getTargetStyleSheetName(context, document);
+    for (int i = 1; true; ++i)
+    {
+      // we don't know in advance if there are any files, and if there are, how many of them
+      // there are. Therefore, we keep incrementing the counter until the file doesn't exist and
+      // at that point we know we have all of them
+      File f = _getOutputFile(name, i);
+      if (f.exists())
+      {
+        files.add(f);
     }
-	  
-	  File[] outputFiles = new File[fileCount];
-	  
-	  for (int i = 0; i < fileCount; i++)
+      else
 	  {
-		  String name = getTargetStyleSheetName(context, document, i + 1);
-		  outputFiles[i] = new File(_targetPath, name);
+        break;
 	  }
+    }
 
-	  return outputFiles;
+    return files;
   }
 
-  // Returns the PrintWriter to use for the specified file
-  private PrintWriter _getWriterToNewFile(File file)
+  /**
+   * Returns the PrintWriter to use for the specified file
+   */
+  private PrintWriter _getWriter(File file)
   {
+    PrintWriter out = null;
 
     try
     {
       File parentFile = file.getParentFile();
       if (parentFile != null)
-      {
         parentFile.mkdirs();
-      }
 
-      if (!file.createNewFile())
-      {
-        if (_LOG.isWarning())
-        {
-          _LOG.warning("\nUnable to generate the style sheet "
-                       + file.getName() + " in cache directory\n"
-                       + file.getParent() + ".\n"
-                       + "Please make sure that the cache directory exists "
-                       + "and is writable.\n" );
-        }
+      FileOutputStream fos = new FileOutputStream(file);
+      OutputStreamWriter writer = null;
         
-        return null;
-      }
-      
-      OutputStream ostream = new FileOutputStream(file);
-      
-      OutputStreamWriter writer;
-
-      // Use UTF8 encoding for output, in case font names have non-ascii characters.
+      // Use UTF8 encoding for output, in case font names have non-ascii
+      // characters.
       try
       {
-        writer = new OutputStreamWriter(ostream, _UTF8_ENCODING);
+        writer = new OutputStreamWriter(fos, _UTF8_ENCODING);
       }
       catch (UnsupportedEncodingException e)
       {
@@ -903,26 +912,26 @@
         assert false;
 
         // Just use default encoding instead
-        writer = new OutputStreamWriter(ostream);
+        writer = new OutputStreamWriter(fos);
       }
 
-      return new PrintWriter(new BufferedWriter(writer));
+      out = new PrintWriter(new BufferedWriter(writer));
     }
     catch (IOException e)
     {
       if (_LOG.isWarning())
-      {
         _LOG.warning("IOEXCEPTION_OPENNING_FILE", file);
         _LOG.warning(e);
       }
-    }
     
-    return null;
+    return out;
   }
 
-  // Checks to see whether the source file has been modified
-  // since the specified output file was generated.  If so,
-  // we need to regenerate the output file.
+  /**
+   * Checks to see whether the source file has been modified
+   * since the specified output file was generated.  If so,
+   * we need to regenerate the output file.
+   */
   private boolean _checkSourceModified(
     StyleSheetDocument document,
     File               outputFile
@@ -933,7 +942,9 @@
     return (document.getDocumentTimestamp() > outputFile.lastModified());
   }
 
-  // Gets the InputStreamProvider for the source file
+  /**
+   * Gets the InputStreamProvider for the source file
+   */
   private InputStreamProvider _getInputStreamProvider()
   {
     // Source file may be null
@@ -956,7 +967,9 @@
     return null;
   }
 
-  // Initiializes the NameResolver
+  /**
+   * Initiializes the NameResolver
+   */
   private void _initResolver()
   {
     // Synchronize just in case two different threads hit this
@@ -983,7 +996,9 @@
     }
   }
 
-  // Copies an enumeration into a Vector
+  /**
+   * Copies an enumeration into a Vector
+   */
   private <T> Vector<T> _copyIterator(Iterator<T> e)
   {
     if (e == null)
@@ -996,18 +1011,9 @@
     return v;
   }
   
-  private static List<String> getFileNames(File[] files)
-  {
-    List<String> names = new ArrayList<String>(files.length);
-    for (File file : files)
-    {
-      names.add(file.getName());
-    }
-    
-    return Collections.unmodifiableList(names);
-  }
-
-  // Create an array of all the namespace prefixes in the xss/css file. E.g., "af|" or "tr|"
+  /**
+   * Create an array of all the namespace prefixes in the xss/css file. E.g., "af|" or "tr|"
+   */
   private static String[] _getNamespacePrefixes(
     StyleContext       context,
     StyleSheetDocument document)
@@ -1035,8 +1041,10 @@
     return namespacePrefixesSet.toArray(_EMPTY_STRING_ARRAY);
   }
 
-  // Create the map of full style classes to short style classes
-  // Do not shorten styleclasses that start with SkinSelectors.STATE_PREFIX
+  /**
+   * Create the map of full style classes to short style classes
+   * Do not shorten styleclasses that start with SkinSelectors.STATE_PREFIX
+   */
   private static Map<String, String> _getShortStyleClassMap(
     StyleContext       context,
     StyleSheetDocument document,
@@ -1146,12 +1154,14 @@
     return Collections.unmodifiableMap(map);
   }
   
-  // Method to put styleclasses in the shortened map.
-  // We don't put 'state' styleclasses in the shortened map. Those are styleclasses
-  // that start with SkinSelectors.STATE_PREFIX. The reason is that those
-  // are likely to be added and removed on the client as the state changes, and
-  // we don't want to require the shortened map on the client.
-  private static void _putStyleClassInShortMap(String styleClass, Map<String, String> map)
+  /**
+   * Method to put styleclasses in the shortened map.
+   * We don't put 'state' styleclasses in the shortened map. Those are styleclasses
+   * that start with SkinSelectors.STATE_PREFIX. The reason is that those
+   * are likely to be added and removed on the client as the state changes, and
+   * we don't want to require the shortened map on the client.
+   */
+  private static void _putStyleClassInShortMap(String styleClass, Map map)
   {
     if (styleClass != null &&
         !styleClass.startsWith(SkinSelectors.STATE_PREFIX) &&
@@ -1161,9 +1171,11 @@
     }
   }
 
-  // Helper method used by _getShortStyleClassMap().  Returns a new
-  // short style class selector.  The count is the number of style
-  // classes seen so far.
+  /**
+   * Helper method used by _getShortStyleClassMap().  Returns a new
+   * short style class selector.  The count is the number of style
+   * classes seen so far.
+   */
   private static String _getShortStyleClass(int count)
   {
     // At the moment the short style class is just based on the nubmer
@@ -1171,7 +1183,10 @@
     return _SHORT_CLASS_PREFIX + Integer.toString(count, Character.MAX_RADIX);
   }
   
-  // Key class used for hashing style sheet URIs
+
+  /**
+   * Key class used for hashing style sheet URIs
+   */
   private static class Key
   {
     public Key(StyleContext context)
@@ -1265,31 +1280,34 @@
     private AccessibilityProfile _accProfile;
   }
 
-  // Cache entry class
+  /**
+   * Cache entry class
+   */
   private static class Entry
   {
-    public final List<String> uriList;
+    public final List<String> uris;
     public final StyleMap map;
     public final ConcurrentMap<String, Icon> icons;
     public final ConcurrentMap<Object, Object> skinProperties;
 
     public Entry(
-      List<String> uriList,
+      List<String> uris,
       StyleMap map,
       ConcurrentMap<String, Icon> icons,
       ConcurrentMap<Object, Object> skinProperties)
     {
-      this.uriList = uriList;
+      this.uris = uris;
       this.map = map;
       this.icons = icons;
       this.skinProperties = skinProperties;
     }
   }
 
-  // A key object which is used to hash Entrys in the
-  // entry cache.  The key for the entry cache is the
-  // style sheet derivation list - that is a list of
-  // StyleSheetNodes, sorted by specficity.
+  /**
+   * A key object which is used to hash Entrys in the entry cache.  The key for the entry
+   * cache is the style sheet derivation list - that is a list of StyleSheetNodes, sorted
+   * by specficity.
+   */
   private static class DerivationKey
   {
     public DerivationKey(StyleContext context, StyleSheetNode[] styleSheets)
@@ -1344,7 +1362,9 @@
     private boolean          _short;   // Do we use short style classes?
   }
 
-  // A StyleMap implemenation which creates Style objects as needed
+  /**
+   * A StyleMap implemenation which creates Style objects as needed
+   */
   private class StyleMapImpl implements StyleMap
   {
     // Implementation of StyleMap.getStyleBySelector()
@@ -1453,27 +1473,76 @@
     private Hashtable<String, Style> _nameMap;
   }
 
+  private class StyleWriterFactoryImpl
+    implements StyleWriterFactory
+  {
+    private String _outputDirectory;
+    private String _baseFilename;
+    private PrintWriter _out;
+    private List<File> _files = new LinkedList<File>();
+
+    StyleWriterFactoryImpl(String outputDirectory, String baseName)
+    {
+      _outputDirectory = outputDirectory;
+      _baseFilename = baseName;
+    }
+
+    List<File> getFiles()
+    {
+      return _files;
+    }
+
+    public PrintWriter createWriter()
+    {
+      if (_out != null)
+      {
+        _out.close();
+      }
+
+      File outputFile = _getOutputFile(_baseFilename, _files.size() + 1);
+      // We never want to do anything other then read it or delete it:
+      outputFile.setReadOnly();
+
+      _files.add(outputFile);
+      _out = _getWriter(outputFile);
+
+      return _out;
+    }
+
+    void close()
+    {
+      if (_out != null)
+      {
+        _out.close();
+        _out = null;
+      }
+    }
+  }
+
   private File   _sourceFile; // The source XSS file
   private String _targetPath; // The location of the cache
   private String _baseName;   // The base file name for generated CSS files
 
-  // The NameResolver and InputStreamProvider we use to
-  // resolve/load all files.  We also use the InputStreamProvider
-  // to check for modifications to any dependent files.
+  /**
+   * The NameResolver and InputStreamProvider we use to
+   * resolve/load all files.  We also use the InputStreamProvider
+   * to check for modifications to any dependent files.
+   */
   private NameResolver        _resolver;
 
-  // The parsed StyleSheetDocument
+  /** The parsed StyleSheetDocument */
   private StyleSheetDocument _document;
 
-  // The cache of style sheet URIs
+  /** The cache of style sheet URIs */
   private Hashtable<Key, Entry> _cache;
 
-  // We cache Entry objects, hashed by DerivationKey (ie.
-  // hashed based on the StyleSheetNode derivation list).
+  /**
+   * We cache Entry objects, hashed by DerivationKey (ie.
+   * hashed based on the StyleSheetNode derivation list).
+   */
   private Hashtable<Object, Entry> _entryCache;
 
-  // Map which maps from full style class names to
-  // our compressed names.
+  /** Map which maps from full style class names to our compressed names. */
   private Map<String, String> _shortStyleClassMap;
   private String[]            _namespacePrefixes;
 
@@ -1483,33 +1552,37 @@
   private static final char _NAME_SEPARATOR = '-';
   private static final String _COMPRESSED = "cmp";
 
-  // Extension for CSS files
+  /** Extension for CSS files */
   private static final String _CSS_EXTENSION = ".css";
 
-  // Java name for UTF8 encoding
+  /** Java name for UTF8 encoding */
   private static String _UTF8_ENCODING = "UTF8";
 
-  // Stub StyleSheetDocument instance
+  /** Stub StyleSheetDocument instance */
   private static final StyleSheetDocument _EMPTY_DOCUMENT =
     new StyleSheetDocument(null, null, StyleSheetDocument.UNKNOWN_TIMESTAMP);
 
-  // Style used to represent misses in the StyleMap.
-  // Package private to allow access from nested StyleMapImpl class
+  /**
+   * Style used to represent misses in the StyleMap.
+   * Package private to allow access from nested StyleMapImpl class
+   */
           static final Style _MISS = new CSSStyle();
 
-  // Prefix to use for short style classes
+  /** Prefix to use for short style classes */
   private static final String _SHORT_CLASS_PREFIX = "x";
 
-  private static final int _MSIE_SELECTOR_LIMIT = 4095;
   private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(FileSystemStyleCache.class);
 
 
-  // use this map to map from the public style selector names to
-  // our internal style selector names. The public style selector
-  // names do not contain html, whereas our internal style selector
-  // names may. We write out the shortened version of the mapped
-  // selector names to the css file.
-  // jmw. @todo Need to find a better spot for this, like the skin?
+  /**
+   * use this map to map from the public style selector names to
+   * our internal style selector names. The public style selector
+   * names do not contain html, whereas our internal style selector
+   * names may. We write out the shortened version of the mapped
+   * selector names to the css file.
+   * jmw.
+   * @todo Need to find a better spot for this, like the skin?
+   */
   private static final Map<String, String> _STYLE_KEY_MAP;
 
   static

Modified: myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/util/CSSGenerationUtils.java
URL: http://svn.apache.org/viewvc/myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/util/CSSGenerationUtils.java?rev=703009&r1=703008&r2=703009&view=diff
==============================================================================
--- myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/util/CSSGenerationUtils.java (original)
+++ myfaces/trinidad/trunk/trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/util/CSSGenerationUtils.java Wed Oct  8 15:23:39 2008
@@ -19,6 +19,7 @@
 package org.apache.myfaces.trinidadinternal.style.util;
 
 import java.io.PrintWriter;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Comparator;
@@ -30,17 +31,16 @@
 import java.util.Map;
 import java.util.Set;
 import java.util.Vector;
-
 import java.util.regex.Pattern;
 
 import org.apache.myfaces.trinidad.logging.TrinidadLogger;
 import org.apache.myfaces.trinidadinternal.agent.TrinidadAgent;
-import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.OutputUtils;
 import org.apache.myfaces.trinidadinternal.renderkit.core.xhtml.SkinSelectors;
 import org.apache.myfaces.trinidadinternal.style.StyleContext;
 import org.apache.myfaces.trinidadinternal.style.xml.parse.PropertyNode;
 import org.apache.myfaces.trinidadinternal.style.xml.parse.StyleNode;
 
+
 /**
  * CSS-generation related utilities used when we write out our css-2 stylesheet
  * document based on the skin's css-3 stylesheet document.
@@ -50,17 +50,15 @@
 
 public class CSSGenerationUtils
 {
-
-
   /**
-    * Converts the specified set of StyleNodes to CSS. We output either full styleclass names or
-    * compressed styleclass names.
+   * Converts the specified set of StyleNodes to CSS. We output either full styleclass names or
+   * compressed styleclass names.
    *
    * @param context The current StyleContext
    * @param styleSheetName The stylesheet name that is registered with the skin.
    *     e.g. skins/purple/purpleSkin.css
    * @param styles The style nodes to convert
-   * @param out The PrintWriter to write to
+   * @param writerFactory The factory to obtain {@link PrintWriter} instances
    * @param compressStyles This tells us whether or not we want to output the short names.
    * @param shortStyleClassMap A Map which maps style
    *   class names to short names.
@@ -69,17 +67,23 @@
    * @param afSelectorMap A Map which maps the namespaced component selectors
    *   to their base names (e.g., 'af|menuPath::step' maps to 'af|menuPath A')
    */
-  public static void writeCSS(StyleContext        context,
-                              String              styleSheetName,
-                              StyleNode[]         styles,
-                              PrintWriter         out,
-                              boolean             compressStyles,
-                              Map<String, String> shortStyleClassMap,
-                              String[]            namespacePrefixArray,
-                              Map<String, String> afSelectorMap,
-                              int 				        startIndex,
-                              int					        count)
+  public static void writeCSS(
+    StyleContext        context,
+    String              styleSheetName,
+    StyleNode[]         styles,
+    StyleWriterFactory  writerFactory,
+    boolean             compressStyles,
+    Map<String, String> shortStyleClassMap,
+    String[]            namespacePrefixArray,
+    Map<String, String> afSelectorMap
+    )
   {
+    PrintWriter out = writerFactory.createWriter();
+    if (out == null)
+    {
+      return;
+    }
+
     // writeCSS() attempts to produce a minimal set of style rules
     // by combining selectors with identical properties into a
     // single rule.  For example, we convert the following two
@@ -103,31 +107,17 @@
     // During the second pass over the styles, we write out all matching
     // selectors for each style followed by the shared set of properties.
 
-    if (startIndex < 0)
-    {
-    	throw new IllegalArgumentException("startIndex must be positive");
-    }
-    
-    if (count <= 0)
-    {
-    	throw new IllegalArgumentException("count must be strictly positive");
-    }
-	
     // We track styles with matching properties in the following HashMap
     // which maps property strings to StyleNode[]s.
-    HashMap<String, StyleNode[]> matchingStylesMap = new HashMap<String, StyleNode[]>(101);
+    HashMap<String, StyleNode[]> matchingStylesMap =
+      new HashMap<String, StyleNode[]>(101);
 
     // We also keep an array of the property strings that we generate
     // during this pass, since we need these strings during the second
     // pass to find matching StyleNodes.
-    String[] propertyStrings = new String[count];
-    
-    // Keep track of the number of selectors written out. The reason? IE has a 4095 limit,
-    // and we want to warn when we get to that limit.
-    int numberSelectorsWritten = 0;
-    int endIndex = startIndex + count;
-    
-    for (int i = startIndex; i < styles.length && i < endIndex; i++)
+    String[] propertyStrings = new String[styles.length];
+
+    for (int i = 0; i < styles.length; i++)
     {
       StyleNode style = styles[i];
 
@@ -144,7 +134,7 @@
         {
           // If we don't already have matching StyleNodes, add this
           // StyleNode to the map.
-          propertyStrings[i - startIndex] = propertyString;
+          propertyStrings[i] = propertyString;
           matchingStyles = new StyleNode[1];
           matchingStyles[0] = style;
         }
@@ -174,14 +164,18 @@
     Date date = new Date();
     out.println("/* This CSS file generated on " + date + " */");
 
+    // Keep track of the number of selectors written out. The reason? IE has a 4095 limit,
+    // and we want to warn when we get to that limit.
+    int numberSelectorsWritten = 0;
+
     // This is the second pass in which we write out the style rules
     // Get the baseURI up front so we don't have to recalculate it every time we find
     // a property value that contains url() and need to resolve the uri.
     String baseURI = CSSUtils.getBaseSkinStyleSheetURI(styleSheetName);
-    for (int i = startIndex; i < styles.length && i < endIndex; i++)
+    for (int i = 0; i < styles.length; i++)
     {
       StyleNode style = styles[i];
-      String propertyString = propertyStrings[i - startIndex];
+      String propertyString = propertyStrings[i];
 
       // We only write out styles for which we have a property string.
       // All other entries correspond to styles which don't have selectors -
@@ -194,29 +188,62 @@
         // Actually, we should always have at least one StyleNode here
         assert (matchingStyles != null);
 
-        // Write out all of the style selectors for this property string
+        // determine if the current CSS file can fit all of the CSS selectors, or if a new
+        // one will be needed.
+        // TODO: figure out why we write both the uncompressed & compressed styles for styles
+        // without a '|' character, shouldn't the uncompressed be enough on its own? This results
+        // in some ugly code here
+        int stylesToBeWritten = 0;
+        String[] selectors = new String[matchingStyles.length];
+        String[] mappedSelectors = new String[matchingStyles.length];
+
         for (int j = 0; j < matchingStyles.length; j++)
         {
-          StyleNode matchingStyle = matchingStyles[j];
-          String selector = matchingStyle.getSelector();
-          
+          selectors[j] = matchingStyles[j].getSelector();
+
           // We should always have a selector at this point
-          assert (selector != null);
+          assert (selectors[j] != null);
 
-          String mappedSelector = _getMappedSelector(afSelectorMap,
+          mappedSelectors[j] = _getMappedSelector(afSelectorMap,
                                                      namespacePrefixArray,
-                                                     selector);
+                                                     selectors[j]);
 
+          if (compressStyles && (mappedSelectors[j].indexOf('|') == -1))
+          {
+            stylesToBeWritten += 2;
+          }
+          else
+          {
+            stylesToBeWritten++;
+          }
+        }
+
+        if (numberSelectorsWritten + matchingStyles.length >= _MSIE_SELECTOR_LIMIT
+          && TrinidadAgent.APPLICATION_IEXPLORER == context.getAgent().getAgentApplication())
+        {
+          out.println("/* The number of CSS selectors in this file is " +
+                      numberSelectorsWritten + " */");
+          out = writerFactory.createWriter();
+          if (out == null)
+          {
+            return;
+          }
+          numberSelectorsWritten = 0;
+        }
+
+        // Write out all of the style selectors for this property string
+        for (int j = 0; j < matchingStyles.length; j++)
+        {
           String validFullNameSelector = null;
 
           // write out the full selector if we aren't compressing styles or
           // it doesn't have a '|' in the name which means it may be a user's public styleclass
           // and we don't want to compress those; we will also write out the compressed
           // version the public styleclasses in the next step.
-          if (!compressStyles || (mappedSelector.indexOf('|') == -1))
+          if (!compressStyles || (mappedSelectors[j].indexOf('|') == -1))
           {
             validFullNameSelector =
-              _getValidFullNameSelector(mappedSelector, namespacePrefixArray);
+              _getValidFullNameSelector(mappedSelectors[j], namespacePrefixArray);
 
             if (validFullNameSelector != null)
             {
@@ -237,11 +264,11 @@
           // e.g., .Foo:hover -> .x0:hover
           if (compressStyles)
           {
-            String shortSelector = _getShortSelector(mappedSelector,
+            String shortSelector = _getShortSelector(mappedSelectors[j],
                                                      shortStyleClassMap);
 
             if (shortSelector == null)
-              shortSelector = mappedSelector;
+              shortSelector = mappedSelectors[j];
 
             // run it through a shortener one more time to shorten any
             // of the af component selectors.
@@ -265,7 +292,7 @@
             {
               String validShortSelector =
                 _getValidFullNameSelector(shortSelector, namespacePrefixArray);
-              
+
               // if we wrote out a full style, check to see if we need to write out the short, too.
               // if it is something different, write out the short, too.
               if (validFullNameSelector != null)
@@ -334,18 +361,6 @@
       }
     }
     out.println("/* The number of CSS selectors in this file is " + numberSelectorsWritten + " */");
-    if (numberSelectorsWritten > 4095 &&
-      (TrinidadAgent.APPLICATION_IEXPLORER == context.getAgent().getAgentApplication()))
-    {
-
-      out.println("/* ERROR: The number of CSS selectors is more than IE's limit of 4095. " +
-      "The selectors after that will be ignored. */");
-      if (_LOG.isWarning())
-      {
-        _LOG.warning("CSS_FILE_HIT_IE_LIMIT_OF_CSS_SELECTOR", numberSelectorsWritten);
-      }
-    }
-
   }
 
   /**
@@ -461,7 +476,7 @@
     String              namespace,
     Map<String, String> afSelectorMap)
   {
-	if (selector == null)
+  if (selector == null)
       return null;
     int afIndex = selector.indexOf(namespace);
 
@@ -757,7 +772,7 @@
     {
       String[] selectorArray =
         _orderPseudoElementsAndClasses(selector);
-      
+
       // map selectors, if needed
       // any of the selectors that start with a namespace prefix will
       // be mapped.
@@ -778,14 +793,14 @@
       StringBuilder b = new StringBuilder();
       for(int i = 0; i < selector.length(); i++)
       {
-        char c = selector.charAt(i); 
+        char c = selector.charAt(i);
         if (c == ' ' )
         {
           if (start == i)
           {
             //group of spaces
-            start = i+1; //Skip space                       
-          } 
+            start = i+1; //Skip space
+          }
           else
           {
             String subSelector = selector.substring(start,i);
@@ -796,7 +811,7 @@
           }
         }
       } // end for loop
-      
+
       // We reached the end of the selector, now convert the last bit
       if (start == 0)
       {
@@ -1300,7 +1315,7 @@
     if (lastString.length() > 0)
       splitList.add(lastString);
 
-    return splitList.toArray(_EMPTY_STRING_ARRAY);      
+    return splitList.toArray(_EMPTY_STRING_ARRAY);
 
   }
 
@@ -1381,6 +1396,7 @@
   private static final Pattern _SPACE_PATTERN = Pattern.compile("\\s");
   private static final Pattern _DASH_PATTERN =  Pattern.compile("-");
   private static final String[] _EMPTY_STRING_ARRAY = new String[0];
+  private static final int _MSIE_SELECTOR_LIMIT = 4095;
 
   private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(CSSGenerationUtils.class);
 }