cocoon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From stef...@apache.org
Subject cvs commit: xml-cocoon2/src/scratchpad/src/org/apache/cocoon/transformation/pagination ItemGroup.java PageRules.java Pagesheet.java Paginator.java
Date Wed, 20 Feb 2002 20:56:19 GMT
stefano     02/02/20 12:56:19

  Added:       src/scratchpad/src/org/apache/cocoon/transformation/pagination
                        ItemGroup.java PageRules.java Pagesheet.java
                        Paginator.java
  Log:
  added a paginating transformer to the scratchpad
  
  Revision  Changes    Path
  1.1                  xml-cocoon2/src/scratchpad/src/org/apache/cocoon/transformation/pagination/ItemGroup.java
  
  Index: ItemGroup.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
   
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
   
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
   
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
   
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
   
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
   
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      apache@apache.org.
   
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
   
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache 
   Software Foundation, please see <http://www.apache.org/>.
   
  */
  
  package org.apache.cocoon.transformation.pagination;
  
  /**
   * Container class for the immutable pagination rules for each page.
   *
   * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
   * @version CVS $Revision: 1.1 $ $Date: 2002/02/20 20:56:19 $
   */
  public class ItemGroup {
      
      private String name;
      private String elementName;
      private String elementURI;
      
      public ItemGroup (String name, String elementURI, String elementName) {
          this.name = name;
          this.elementURI = elementURI;
          this.elementName = elementName;
      }
      
      public boolean match(String elementName, String elementURI) {
          return (this.elementName.equals(elementName) && this.elementURI.equals(elementURI));
      }
  
      public boolean match(String elementURI) {
          return this.elementURI.equals(elementURI);
      }
  
      public String getName() {
          return this.name;
      }
  
      public String getElementURI() {
          return this.elementURI;
      }
      
      public String getElementName() {
          return this.elementName;
      }
  }
  
  
  1.1                  xml-cocoon2/src/scratchpad/src/org/apache/cocoon/transformation/pagination/PageRules.java
  
  Index: PageRules.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
   
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
   
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
   
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
   
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
   
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
   
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      apache@apache.org.
   
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
   
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache 
   Software Foundation, please see <http://www.apache.org/>.
   
  */
  
  package org.apache.cocoon.transformation.pagination;
  
  /**
   * Container class for the immutable pagination rules for each page.
   *
   * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
   * @version CVS $Revision: 1.1 $ $Date: 2002/02/20 20:56:19 $
   */
  public class PageRules {
  
      public String elementName = "";
      public String elementURI = "";
      public int elementCount = 1;
      public int charCount = 0;
      public int unitLinks = 0;
      public int rangeLink = 0;
      public boolean store = false;
  
      public boolean match(String element, String namespace) {
          return (this.elementName.equals(element) && this.elementURI.equals(namespace));
      }
  
      public boolean match(String namespace) {
          return this.elementURI.equals(namespace);
      }
  }
  
  
  
  1.1                  xml-cocoon2/src/scratchpad/src/org/apache/cocoon/transformation/pagination/Pagesheet.java
  
  Index: Pagesheet.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
   
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
   
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
   
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
   
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
   
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
   
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      apache@apache.org.
   
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
   
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache 
   Software Foundation, please see <http://www.apache.org/>.
   
  */
  
  package org.apache.cocoon.transformation.pagination;
  
  import java.util.Map;
  import java.util.HashMap;
  import java.util.List;
  import java.util.ArrayList;
  import java.util.Set;
  import java.util.Iterator;
  
  import org.xml.sax.Attributes;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.SAXException;
  import org.xml.sax.helpers.DefaultHandler;
  
  import org.apache.cocoon.Modifiable;
  import org.apache.cocoon.util.ResizableContainer;
  
  /**
   * Interprets the pagesheet rules to perform pagination.
   * 
   * FIXME (SM): this code sucks! It was done to show the concept of 
   *             rule driven pagination (which I find very nice) but
   *             it needs major refactoring in order to be sufficiently
   *             stable to allow any input to enter without breaking
   *             SAX well-formness. I currently don't have the time to make
   *             it any better (along with implementing the char-based rule
   *             that is mostly useful for text documents) but if you want
   *             to blast the code and rewrite it better, you'll make me happy :)
   *
   * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
   * @version CVS $Revision: 1.1 $ $Date: 2002/02/20 20:56:19 $
   */
   
  /* 
  
  This is an example pagesheet to show the power of this:
  
    <?xml version="1.0"?>
    <pagesheet xmlns="http://apache.org/cocoon/paginate/1.0">
     <items>
      <group name="pictures" element="file" namespace="http://apache.org/cocoon/directory/2.0"/>
     </items>
     <rules page="1">
      <count type="element" name="file" namespace="http://apache.org/cocoon/directory/2.0" num="16" store="yes"/>
       <link type="unit" num="2"/>
       <link type="range" value="10"/>
     </rules>
     <rules>
      <count type="element" name="file" namespace="http://apache.org/cocoon/directory/2.0" num="16" store="yes"/>
       <link type="unit" num="5"/>
       <link type="range" value="20"/>
     </rules>
    </pagesheet>
  
  which indicates that:
  
   1) there is one item group called "picture" and each item is given by the 
      element "file" of the namespace "http://apache.org/cocoon/directory/2.0".
      
   2) for the first page, the pagination rules indicate that there are two unit
      links (two above and two below, so linking to page -2 -1 0 +1 +2) and 
      range links have value 10 (so they link to page -10 and +10).
   
   3) for the rest of the pages, there are three unit links (-3 -2 -1 0 +1 +2 +3)
      and range goes 20 (so +20 and -20).
      
  */
  
  public class Pagesheet extends DefaultHandler implements Cloneable, Modifiable {
  
      private int level = 0;
      private int pg = 0;
      private long lastModified;
      private Pagesheet pagesheet;
      private PageRules rules;
  
      ResizableContainer pageRules;
      ResizableContainer pages;
  
      Map itemGroupsPerName;
      Map itemGroupsPerElement;
      Map itemListsPerName;
      Map itemListsPerElement;
  
      private int currentPage = 1;
      private int currentPageElementStart = 1;
      private int currentPageElementEnd = 1;
      private int counter = 0;
      private int descendant = 0;
  
      class Page {
          public int elementStart;
          public int elementEnd;
  
          public Page(int start, int end) {
              this.elementStart = start;
              this.elementEnd = end;
          }
  
          public boolean validInPage(int counter) {
              return (this.elementStart <= counter) && (counter <= this.elementEnd);
          }
      }
  
      class ItemList extends ArrayList {
  
          public ItemList(int capacity) {
              super(capacity);
          }
  
          public void addItem(int page) {
              this.add(new Integer(page));
          }
  
          public int getPageForItem(int item) {
              Integer i = (Integer) this.get(item-1);
              return (i == null) ? 0 : i.intValue();
          }
  
          public boolean valid(int item) {
              return (item == this.size());
          }
      }
  
      public Pagesheet() {
          this.pages = new ResizableContainer(2);
      }
  
      private Pagesheet(ResizableContainer rules, Map itemGroupsPerName, Map itemGroupsPerElement) {
          this.pageRules = rules;
          this.itemGroupsPerName = itemGroupsPerName;
          this.itemGroupsPerElement = itemGroupsPerElement;
  
          this.pages = new ResizableContainer(5);
          
          if ((this.itemGroupsPerName != null) && (this.itemGroupsPerElement != null)) {
              this.itemListsPerName = new HashMap(itemGroupsPerName.size());
              this.itemListsPerElement = new HashMap(itemGroupsPerName.size());
      
              Iterator iter = itemGroupsPerName.values().iterator();
              for (int i = 0; iter.hasNext(); i++) {
                  ItemGroup group = (ItemGroup) iter.next();
                  ItemList list = new ItemList(10);
                  this.itemListsPerName.put(group.getName(),list);
                  this.itemListsPerElement.put(group.getElementURI()+group.getElementName(),list);
              }
          }
      }
  
      // --------------- interprets the pagesheet document ----------------
  
      public void startPrefixMapping(String prefix, String uri) throws SAXException {
          if (!uri.equals(Paginator.PAGINATE_URI)) {
              throw new SAXException("The pagesheet's namespace is not supported.");
          }
      }
  
      public void startElement(String uri, String loc, String raw, Attributes a) throws SAXException {
          level++;
          switch (level) {
              case 1:
                  if (loc.equals("pagesheet")) {
                      pagesheet = new Pagesheet();
                      return;
                  }
              case 2:
                  if (loc.equals("rules")) {
                      if (this.pageRules == null) this.pageRules = new ResizableContainer(2);
                      String key = a.getValue("page");
                      if (key != null) {
                          try {
                              pg = Integer.parseInt(key);
                          } catch (NumberFormatException e) {
                              throw new SAXException("Syntax error: the attribute 'rules/@page' must contain a number");
                          }
                      } else {
                          pg = 0;
                      }
                      rules = new PageRules();
                      return;
                  } else if (loc.equals("items")) {
                      if (this.itemGroupsPerName == null) this.itemGroupsPerName = new HashMap(2);
                      if (this.itemGroupsPerElement == null) this.itemGroupsPerElement = new HashMap(2);
                  }
              case 3:
                  if (loc.equals("count")) {
                      if (a.getValue("type").equals("element")) {
                          rules.elementName = a.getValue("name");
                          rules.elementURI = a.getValue("namespace");
                          rules.store = (a.getValue("store") != null);
                          try {
                              rules.elementCount = Integer.parseInt(a.getValue("num"));
                          } catch (NumberFormatException e) {
                              throw new SAXException("Syntax error: the attribute 'count/@num' must contain a number");
                          }
                      } else if (a.getValue("type").equals("chars")) {
                          try {
                              rules.charCount = Integer.parseInt(a.getValue("num"));
                          } catch (NumberFormatException e) {
                              throw new SAXException("Syntax error: the attribute 'count/@num' must contain a number.");
                          }
                      } else {
                          throw new SAXException("Syntax error: count type not supported.");
                      }
                  } else if (loc.equals("link")) {
                      if (a.getValue("type").equals("unit")) {
                          try {
                              rules.unitLinks = Integer.parseInt(a.getValue("num"));
                          } catch (NumberFormatException e) {
                              throw new SAXException("Syntax error: the attribute 'link/@num' must contain a number.");
                          }
                      } else if (a.getValue("type").equals("range")) {
                          try {
                              rules.rangeLink = Integer.parseInt(a.getValue("value"));
                          } catch (NumberFormatException e) {
                              throw new SAXException("Syntax error: the attribute 'link/@value' must contain a number.");
                          }
                      } else {
                          throw new SAXException("Syntax error: link type not supported.");
                      }
                  } else if (loc.equals("group")) {
                      String name = a.getValue("name");
                      String elementName = a.getValue("element");
                      String elementURI = a.getValue("namespace");
                      if (name == null) throw new SAXException("Syntax error: the attribute 'group/@name' must be present.");
                      if (elementName == null) throw new SAXException("Syntax error: the attribute 'group/@element' must be present.");
                      ItemGroup group = new ItemGroup(name, elementURI, elementName);
                      this.itemGroupsPerName.put(name, group);
                      this.itemGroupsPerElement.put(elementURI+elementName, group);
                  }
                  return;
          }
          throw new SAXException("Syntax error: element " + raw + " is not recognized or is misplaced.");
      }
  
      public void endElement(String uri, String loc, String raw) throws SAXException {
          level--;
          if (loc.equals("rules")) {
              pageRules.set(pg, rules);
          }
      }
  
      public void endDocument() throws SAXException {
          if (pageRules.size() == 0) throw new SAXException("Pagesheet must contain at least a set of pagination rules.");
          if (pageRules.get(0) == null) throw new SAXException("Pagesheet must contain the global pagination rules.");
      }
  
      // --------------- process the received element events ----------------
  
      public void processStartElement(String uri, String name) {
          PageRules rules = getPageRules(currentPage);
  
          if (rules.match(name,uri)) {
              counter++;
              descendant++;
              if (counter == currentPageElementStart) {
                  currentPageElementEnd = currentPageElementStart + rules.elementCount - 1;
                  pages.set(currentPage, new Page(currentPageElementStart, currentPageElementEnd));
              }
              if (counter == currentPageElementEnd) {
                  currentPage++;
                  currentPageElementStart = currentPageElementEnd + 1;
              }
          }
  
          if (itemGroupsPerElement != null) {
              String qname = uri + name;
              ItemGroup group = (ItemGroup) this.itemGroupsPerElement.get(qname);
              if ((group != null) && (group.match(uri))) {
                  ItemList list = (ItemList) this.itemListsPerElement.get(qname);
                  if (list != null) list.addItem(currentPage);
              }
          }
      }
  
      public void processEndElement(String uri, String name) {
          PageRules rules = getPageRules(currentPage);
          if (rules.match(name,uri)) {
              descendant--;
          }
      }
  
      public void processCharacters(char[] ch, int index, int len) {
          PageRules rules = getPageRules(currentPage);
          // FIXME (SM): do nothing for now but this is the place where
          // we should process the character to do char-based pagination
          // instead of element-based pagination which is much more
          // useful for text-based documents.
      }
  
      // --------------- return the pagination information ----------------
  
      public boolean isInPage(int page, int item, String itemGroup) {
          return ((descendant == 0) || valid(page, item, itemGroup));
      }
  
      public int getTotalPages() {
          return currentPage;
      }
  
      public int getTotalItems(String itemGroup) {
          ItemList list = (ItemList) this.itemListsPerName.get(itemGroup);
          return (list == null) ? 0 : list.size();
      }
  
      public int getPageForItem(int item, String itemGroup) {
          ItemList list = (ItemList) this.itemListsPerName.get(itemGroup);
          return (list == null) ? 0 : list.getPageForItem(item);
      }
  
      public boolean store(String elementURI, String elementName) {
          PageRules rules = getPageRules(currentPage);
          return rules.store;        
      }
  
      public int itemCount(String elementURI, String elementName) {
          ItemList list = (ItemList) this.itemListsPerElement.get(elementURI+elementName);
          return (list == null) ? 0 : list.size();
      }
  
      public String getItemGroupName(String elementURI, String elementName) {
          return ((ItemGroup) this.itemGroupsPerElement.get(elementURI+elementName)).getName();
      }
  
      // ---------------- miscellaneous methods ----------------------------
  
      private boolean valid(int page, int item, String itemGroup) {
          if (item == 0) {
              Page p = (Page) pages.get(page);
              return (p != null) && (p.validInPage(counter));
          } else {
              ItemList list = (ItemList) this.itemListsPerName.get(itemGroup);
              return (list != null) && (list.valid(item));
          }
      }
  
      public PageRules getPageRules(int page) {
          PageRules p = (PageRules) pageRules.get(page);
          return (p != null) ? p : (PageRules) pageRules.get(0);
      }
  
      public void setLastModified(long lastModified) {
          this.lastModified = lastModified;
      }
  
      public boolean modifiedSince(long date) {
          return (date != this.lastModified);
      }
  
      public Object clone() {
          return new Pagesheet(pageRules, itemGroupsPerName, itemGroupsPerElement);
      }
  }
  
  
  
  1.1                  xml-cocoon2/src/scratchpad/src/org/apache/cocoon/transformation/pagination/Paginator.java
  
  Index: Paginator.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
   
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
   
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
   
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
   
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
   
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
   
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      apache@apache.org.
   
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
   
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache 
   Software Foundation, please see <http://www.apache.org/>.
   
  */
  
  package org.apache.cocoon.transformation.pagination;
  
  import java.io.IOException;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.Map;
  
  import org.apache.avalon.framework.activity.Disposable;
  import org.apache.avalon.framework.component.Component;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.avalon.framework.component.Composable;
  import org.apache.avalon.framework.parameters.Parameters;
  import org.apache.avalon.excalibur.pool.Poolable;
  
  import org.apache.cocoon.Constants;
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.Roles;
  import org.apache.cocoon.caching.CacheValidity;
  import org.apache.cocoon.caching.Cacheable;
  import org.apache.cocoon.caching.CompositeCacheValidity;
  import org.apache.cocoon.caching.ParametersCacheValidity;
  import org.apache.cocoon.caching.TimeStampCacheValidity;
  import org.apache.cocoon.components.parser.Parser;
  import org.apache.cocoon.components.store.Store;
  import org.apache.cocoon.components.pathmap.PathMap;
  import org.apache.cocoon.environment.Request;
  import org.apache.cocoon.environment.Source;
  import org.apache.cocoon.environment.SourceResolver;
  import org.apache.cocoon.util.HashUtil;
  import org.apache.cocoon.xml.ContentHandlerWrapper;
  import org.apache.cocoon.xml.XMLConsumer;
  import org.apache.cocoon.transformation.AbstractTransformer;
  
  import org.xml.sax.Attributes;
  import org.xml.sax.SAXException;
  import org.xml.sax.helpers.DefaultHandler;
  import org.xml.sax.helpers.AttributesImpl;
  
  /**
   * A paginating transformer.
   *
   * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
   * @version CVS $Revision: 1.1 $ $Date: 2002/02/20 20:56:19 $
   */
  public class Paginator extends AbstractTransformer
      implements Composable, Disposable, Cacheable {
  
      public static final String PAGINATE_URI = "http://apache.org/cocoon/paginate/1.0";
      public static final String PAGINATE_PREFIX = "page";
      public static final String PAGINATE_PREFIX_TOKEN = PAGINATE_PREFIX + ":";
  
      private ComponentManager manager;
      private Parser parser;
      private Store store;
      private PathMap pathMap;
      private Source inputSource;
      private Parameters par;
      private Map objectModel;
      private SourceResolver resolver;
      private int page;
      private int item;
      private String itemGroup;
      private String requestURI;
      private Request request;
      private Pagesheet pagesheet;
      private int level;
      private boolean prefixMapping;
  
      /**
       * Set the current <code>ComponentManager</code> instance used by this
       * <code>Composable</code>.
       */
      public void compose(ComponentManager manager) {
          try {
              this.manager = manager;
              getLogger().debug("Looking up " + Parser.ROLE);
              this.parser = (Parser) manager.lookup(Parser.ROLE);
              getLogger().debug("Looking up " + Store.ROLE);
              this.store = (Store) manager.lookup(Store.ROLE);
              getLogger().debug("Looking up " + PathMap.ROLE);
              this.pathMap = (PathMap) manager.lookup(PathMap.ROLE);
          } catch (Exception e) {
              getLogger().error("Could not find component", e);
          }
      }
  
      /**
       * Dispose this component.
       */
      public void dispose() {
          if (this.parser != null) {
              this.manager.release((Component) this.parser);
          } else {
              this.parser = null;
          }
          if (this.store != null) {
              this.manager.release((Component) this.store);
          } else {
              this.store = null;
          }
          if (this.pathMap != null) {
              this.manager.release((Component) this.pathMap);
          } else {
              this.pathMap = null;
          }
      }
  
      /**
       * Setup the transformer.
       */
      public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par)
              throws ProcessingException, SAXException, IOException {
  
          if (src == null) {
              throw new ProcessingException("I need the paginate instructions (pagesheet) to continue. Set the 'src' attribute.");
          }
  
          this.level = 0;
          this.prefixMapping = false;
          this.par = par;
          this.objectModel = objectModel;
          this.inputSource = resolver.resolve(src);
          this.resolver = resolver;
          getLogger().debug("Using pagesheet: '" + this.inputSource.getSystemId() + "' in " + this + ", last modified: " + this.inputSource.getLastModified());
          this.page = par.getParameterAsInteger("page", 1);
          this.item = par.getParameterAsInteger("item", 0);
          this.itemGroup = par.getParameter("item-group", "");
          getLogger().debug("Paginating with [page = " + this.page + ", item = " + this.item + ", item-group = " + this.itemGroup + "]");
  
          this.request = (Request) objectModel.get(Constants.REQUEST_OBJECT);
          this.requestURI = request.getRequestURI();
  
          // Get the pagesheet factory from the Store if available,
          // otherwise load it and put it into the store for further request
          if (store != null) {
              pagesheet = (Pagesheet) store.get(src);
          }
  
          // If not in the store or if pagesheet has changed, loads and stores it
          if (pagesheet == null || pagesheet.modifiedSince(inputSource.getLastModified())) {
              pagesheet = new Pagesheet();
              parser.setContentHandler(pagesheet);
              pagesheet.setLastModified(inputSource.getLastModified());
              parser.parse(inputSource.getInputSource());
              if (store != null) store.store(src,pagesheet);
          }
  
          // Clone it in order to avoid concurrency collisions since the
          // implementation is not reentrant.
          this.pagesheet = (Pagesheet) this.pagesheet.clone();
      }
  
      /**
       * Generate the unique key.
       * This key must be unique inside the space of this component.
       *
       * @return The generated key hashes the src
       */
      public long generateKey() {
          if (this.inputSource.getLastModified() != 0) {
              return HashUtil.hash(this.inputSource.getSystemId() + page);
          } else {
              return 0;
          }
      }
  
      /**
       * Generate the validity object.
       *
       * @return The generated validity object or <code>null</code> if the
       *         component is currently not cacheable.
       */
      public CacheValidity generateValidity() {
          if (this.inputSource.getLastModified() != 0) {
              return new CompositeCacheValidity(
                              new TimeStampCacheValidity(page),
                              new TimeStampCacheValidity(this.inputSource.getLastModified())
                         );
          } else {
              return null;
          }
      }
  
      /**
       * Receive notification of the beginning of an element.
       *
       * @param uri The Namespace URI, or the empty string if the element has no
       *            Namespace URI or if Namespace
       *            processing is not being performed.
       * @param loc The local name (without prefix), or the empty string if
       *            Namespace processing is not being performed.
       * @param raw The raw XML 1.0 name (with prefix), or the empty string if
       *            raw names are not available.
       * @param a The attributes attached to the element. If there are no
       *          attributes, it shall be an empty Attributes object.
       */
      public void startElement(String uri, String loc, String raw, Attributes a)
      throws SAXException {
          if (!prefixMapping) {
              super.startPrefixMapping(PAGINATE_PREFIX, PAGINATE_URI);
              this.prefixMapping = true;
          }
          level++;
          pagesheet.processStartElement(uri,loc);
          if (pagesheet.isInPage(page, item, itemGroup)) {
              int itemCount = pagesheet.itemCount(uri,loc);
              if (itemCount > 0) {
                  String itemGroup = pagesheet.getItemGroupName(uri,loc);
                  AttributesImpl atts = new AttributesImpl(a);
                  atts.addAttribute(PAGINATE_URI,"item",PAGINATE_PREFIX_TOKEN+"item","CDATA",String.valueOf(itemCount));
                  atts.addAttribute(PAGINATE_URI,"item-group",PAGINATE_PREFIX_TOKEN+"item-group","CDATA",itemGroup);
                  super.startElement(uri,loc,raw,atts);
              } else {
                  super.startElement(uri,loc,raw,a);
              }
              if (pagesheet.store(uri,loc)) {
                  String src = this.request.getSitemapURI();
                  String dest = a.getValue("http://www.w3.org/1999/xlink","href");
                  int index = src.lastIndexOf('/');
                  if (index > 0) {
                      if (dest != null) {
                          dest = src.substring(0, index + 1) + dest;
                      } else {
                          dest = src.substring(0, index + 1);
                      }
                  }
                  this.pathMap.put(dest, src);
              }
          }
      }
  
      /**
       * Receive notification of the end of an element.
       *
       * @param uri The Namespace URI, or the empty string if the element has no
       *            Namespace URI or if Namespace
       *            processing is not being performed.
       * @param loc The local name (without prefix), or the empty string if
       *            Namespace processing is not being performed.
       * @param raw The raw XML 1.0 name (with prefix), or the empty string if
       *            raw names are not available.
       */
      public void endElement(String uri, String loc, String raw)
      throws SAXException {
          level--;
          if (pagesheet.isInPage(page, item, itemGroup)) {
              if (level == 0) {
                  if (item == 0) {
                      int totalPages = pagesheet.getTotalPages();
                      PageRules rules = pagesheet.getPageRules(page);
                      AttributesImpl atts = new AttributesImpl();
                      atts.addAttribute(null,"current","current","CDATA",String.valueOf(page));
                      atts.addAttribute(null,"total","total","CDATA",String.valueOf(totalPages));
                      atts.addAttribute(null,"current-uri","current-uri","CDATA",requestURI);
                      atts.addAttribute(null,"clean-uri","clean-uri","CDATA",cleanURI(requestURI,page));
                      super.startElement(PAGINATE_URI, "page", PAGINATE_PREFIX_TOKEN + "page", atts);
                      if ((rules.rangeLink > 0) && (page - rules.rangeLink >= 1)) {
                          atts.clear();
                          atts.addAttribute(null,"type","type","CDATA","prev");
                          atts.addAttribute(null,"uri","uri","CDATA",encodeURI(requestURI,page,page - rules.rangeLink));
                          atts.addAttribute(null,"page","page","CDATA",String.valueOf(page - rules.rangeLink));
                          super.startElement(PAGINATE_URI, "range-link", PAGINATE_PREFIX_TOKEN + "range-link", atts);
                          super.endElement(PAGINATE_URI, "range-link", PAGINATE_PREFIX_TOKEN + "range-link");
                      }
                      for (int i = page - rules.unitLinks; i < page; i++) {
                          if (i > 0) {
                              atts.clear();
                              atts.addAttribute(null,"type","type","CDATA","prev");
                              atts.addAttribute(null,"uri","uri","CDATA",encodeURI(requestURI,page,i));
                              atts.addAttribute(null,"page","page","CDATA",String.valueOf(i));
                              super.startElement(PAGINATE_URI, "link", PAGINATE_PREFIX_TOKEN + "link", atts);
                              super.endElement(PAGINATE_URI, "link", PAGINATE_PREFIX_TOKEN + "link");
                          }
                      }
                      for (int i = page + 1; i <= page + rules.unitLinks; i++) {
                          if (i <= totalPages) {
                              atts.clear();
                              atts.addAttribute(null,"type","type","CDATA","next");
                              atts.addAttribute(null,"uri","uri","CDATA",encodeURI(requestURI,page,i));
                              atts.addAttribute(null,"page","page","CDATA",String.valueOf(i));
                              super.startElement(PAGINATE_URI, "link", PAGINATE_PREFIX_TOKEN + "link", atts);
                              super.endElement(PAGINATE_URI, "link", PAGINATE_PREFIX_TOKEN + "link");
                          }
                      }
                      if ((rules.rangeLink > 0) && (page + rules.rangeLink <= totalPages)) {
                          atts.clear();
                          atts.addAttribute(null,"type","type","CDATA","next");
                          atts.addAttribute(null,"uri","uri","CDATA",encodeURI(requestURI,page,page + rules.rangeLink));
                          atts.addAttribute(null,"page","page","CDATA",String.valueOf(page + rules.rangeLink));
                          super.startElement(PAGINATE_URI, "range-link", PAGINATE_PREFIX_TOKEN + "range-link", atts);
                          super.endElement(PAGINATE_URI, "range-link", PAGINATE_PREFIX_TOKEN + "range-link");
                      }
                      super.endElement(PAGINATE_URI, "page", PAGINATE_PREFIX_TOKEN + "page");
                      super.endPrefixMapping(PAGINATE_PREFIX);
                  } else {
                      int totalItems = pagesheet.getTotalItems(itemGroup);
                      AttributesImpl atts = new AttributesImpl();
                      atts.addAttribute(null,"current","current","CDATA",String.valueOf(item));
                      atts.addAttribute(null,"total","total","CDATA",String.valueOf(totalItems));
                      atts.addAttribute(null,"current-uri","current-uri","CDATA",requestURI);
                      atts.addAttribute(null,"clean-uri","clean-uri","CDATA",cleanURI(requestURI,item));
                      atts.addAttribute(null,"page","page","CDATA",String.valueOf(pagesheet.getPageForItem(item,itemGroup)));
                      super.startElement(PAGINATE_URI, "item", PAGINATE_PREFIX_TOKEN + "item", atts);
                      if (item > 1) {
                          atts.clear();
                          atts.addAttribute(null,"type","type","CDATA","prev");
                          atts.addAttribute(null,"uri","uri","CDATA",encodeURI(requestURI,item,item-1));
                          super.startElement(PAGINATE_URI, "link", PAGINATE_PREFIX_TOKEN + "link", atts);
                          super.endElement(PAGINATE_URI, "link", PAGINATE_PREFIX_TOKEN + "link");
                      }
                      if (item <= totalItems) {
                          atts.clear();
                          atts.addAttribute(null,"type","type","CDATA","next");
                          atts.addAttribute(null,"uri","uri","CDATA",encodeURI(requestURI,item,item+1));
                          super.startElement(PAGINATE_URI, "link", PAGINATE_PREFIX_TOKEN + "link", atts);
                          super.endElement(PAGINATE_URI, "link", PAGINATE_PREFIX_TOKEN + "link");
                      }
                      super.endElement(PAGINATE_URI, "item", PAGINATE_PREFIX_TOKEN + "item");
                      super.endPrefixMapping(PAGINATE_PREFIX);
                  }
              }
              super.endElement(uri, loc, raw);
          }
          pagesheet.processEndElement(uri,loc);
      }
  
      /**
       * Receive notification of character data.
       *
       * @param c The characters from the XML document.
       * @param start The start position in the array.
       * @param len The number of characters to read from the array.
       */
      public void characters(char c[], int start, int len)
      throws SAXException {
          pagesheet.processCharacters(c, start, len);
          if (pagesheet.isInPage(page, item, itemGroup)) super.characters(c,start,len);
      }
  
      /**
       * Receive notification of ignorable whitespace in element content.
       *
       * @param c The characters from the XML document.
       * @param start The start position in the array.
       * @param len The number of characters to read from the array.
       */
      public void ignorableWhitespace(char c[], int start, int len)
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) super.ignorableWhitespace(c,start,len);
      }
  
      /**
       * Receive notification of a processing instruction.
       *
       * @param target The processing instruction target.
       * @param data The processing instruction data, or null if none was
       *             supplied.
       */
      public void processingInstruction(String target, String data)
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) super.processingInstruction(target,data);
      }
  
      /**
       * Receive notification of a skipped entity.
       *
       * @param name The name of the skipped entity.  If it is a  parameter
       *             entity, the name will begin with '%'.
       */
      public void skippedEntity(String name)
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) super.skippedEntity(name);
      }
  
      /**
       * Report the start of DTD declarations, if any.
       *
       * @param name The document type name.
       * @param publicId The declared public identifier for the external DTD
       *                 subset, or null if none was declared.
       * @param systemId The declared system identifier for the external DTD
       *                 subset, or null if none was declared.
       */
      public void startDTD(String name, String publicId, String systemId)
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) {
              super.startDTD(name,publicId,systemId);
          } else {
              throw new SAXException(
                  "Recieved startDTD not in page."
              );
          }
      }
  
      /**
       * Report the end of DTD declarations.
       */
      public void endDTD()
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) {
              super.endDTD();
          } else {
              throw new SAXException(
                  "Recieved endDTD not in page."
              );
          }
      }
  
      /**
       * Report the beginning of an entity.
       *
       * @param name The name of the entity. If it is a parameter entity, the
       *             name will begin with '%'.
       */
      public void startEntity(String name)
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) super.startEntity(name);
      }
  
      /**
       * Report the end of an entity.
       *
       * @param name The name of the entity that is ending.
       */
      public void endEntity(String name)
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) super.endEntity(name);
      }
  
      /**
       * Report the start of a CDATA section.
       */
      public void startCDATA()
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) super.startCDATA();
      }
  
      /**
       * Report the end of a CDATA section.
       */
      public void endCDATA()
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) super.endCDATA();
      }
  
      /**
       * Report an XML comment anywhere in the document.
       *
       * @param ch An array holding the characters in the comment.
       * @param start The starting position in the array.
       * @param len The number of characters to use from the array.
       */
      public void comment(char ch[], int start, int len)
      throws SAXException {
          if (pagesheet.isInPage(page, item, itemGroup)) super.comment(ch,start,len);
      }
  
      /**
       * Removes the pagination encoding from the URI by removing the page
       * number and the previous and next character.
       */
       private String cleanURI(String uri, int current) {
          String currentS = String.valueOf(current);
          int index = uri.lastIndexOf(currentS);
          if (index == -1) {
              return uri;
          } else {
              return uri.substring(0, index - 1) + uri.substring(index + currentS.length() + 1);
          }
      }
  
      /**
       * Encode the next page in the given URI. First tries to use the
       * existing encoding by replacing the current page number, but if
       * the current encoding is not found it appends "(xx)" to the
       * filename (before the file extention, if any) where "xx" is the
       * next page value.
       */
       private String encodeURI(String uri, int current, int next) {
          String currentS = String.valueOf(current);
          String nextS = String.valueOf(next);
          int index = uri.lastIndexOf(currentS);
          if (index == -1) {
              index = uri.lastIndexOf('.');
              if (index == -1) {
                  return uri + "(" + nextS + ")";
              } else {
                  return uri.substring(0, index) + "(" + nextS + ")." + uri.substring(index + 1);
              }
          } else {
              return uri.substring(0, index) + nextS + uri.substring(index + currentS.length());
          }
      }
  }
  
  
  

----------------------------------------------------------------------
In case of troubles, e-mail:     webmaster@xml.apache.org
To unsubscribe, e-mail:          cocoon-cvs-unsubscribe@xml.apache.org
For additional commands, e-mail: cocoon-cvs-help@xml.apache.org


Mime
View raw message