cocoon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From step...@apache.org
Subject cvs commit: xml-cocoon2/src/java/org/apache/cocoon/transformation TextFragmentParserTransformer.java chaperon.xmap
Date Tue, 17 Sep 2002 12:07:44 GMT
stephan     2002/09/17 05:07:44

  Modified:    .        changes.xml module.xml properties.xml
  Added:       src/blocks/chaperon/conf chaperon.generator.xmap
                        chaperon.transformator.xmap
               src/blocks/chaperon/java/org/apache/cocoon/generation
                        TextParserGenerator.java
               src/blocks/chaperon/java/org/apache/cocoon/transformation
                        TextFragmentParserTransformer.java
  Removed:     src/java/org/apache/cocoon/generation
                        TextParserGenerator.java chaperon.xmap
               src/java/org/apache/cocoon/transformation
                        TextFragmentParserTransformer.java chaperon.xmap
  Log:
  Enabled the chaperon text parser as block.
  
  Revision  Changes    Path
  1.250     +4 -1      xml-cocoon2/changes.xml
  
  Index: changes.xml
  ===================================================================
  RCS file: /home/cvs/xml-cocoon2/changes.xml,v
  retrieving revision 1.249
  retrieving revision 1.250
  diff -u -r1.249 -r1.250
  --- changes.xml	16 Sep 2002 15:35:33 -0000	1.249
  +++ changes.xml	17 Sep 2002 12:07:44 -0000	1.250
  @@ -40,6 +40,9 @@
    </devs>
   
    <release version="@version@" date="@date@">
  +  <action dev="SMS" type="update">
  +   Enabled the chaperon text parser as block.
  +  </action>
     <action dev="NKB" type="add">
      Added initial support for compilation of Cocoon blocks, and migrated
      Fop and Batik classes and configuration to the src/blocks dir.
  
  
  
  1.4       +21 -0     xml-cocoon2/module.xml
  
  Index: module.xml
  ===================================================================
  RCS file: /home/cvs/xml-cocoon2/module.xml,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- module.xml	16 Sep 2002 15:35:21 -0000	1.3
  +++ module.xml	17 Sep 2002 12:07:44 -0000	1.4
  @@ -56,6 +56,7 @@
       <!-- <option project="jakarta-poi"/> -->
       <option project="commons-logging" version="supplied"/>
       <option project="jakarta-slide" ids="kernel" version="supplied"/>
  +    <option project="chaperon" version="supplied"/>
   
       <work nested="build/cocoon/classes"/>
       <work nested="tools/anttasks"/>
  @@ -109,6 +110,26 @@
       <home nested="build/cocoon"/>
       
       <jar name="batik-block.jar"/>
  +
  +    <nag from="Nicola Ken Barozzi &lt;nicolaken@apache.org&gt;"
  +         to="cocoon-dev@xml.apache.org"/>
  +         
  +  </project>
  +
  +  <project name="chaperon-block">
  +    <package>org.apache.cocoon</package>
  +    
  +    <ant target="block">
  +      <property name="block-name" value="chaperon"/>
  +    </ant>
  +    
  +    <depend project="xml-cocoon2"/>
  +    <depend project="chaperon" version="supplied"/>
  +    
  +    <work nested="tools/anttasks"/>
  +    <home nested="build/cocoon"/>
  +    
  +    <jar name="chaperon-block.jar"/>
   
       <nag from="Nicola Ken Barozzi &lt;nicolaken@apache.org&gt;"
            to="cocoon-dev@xml.apache.org"/>
  
  
  
  1.4       +1 -0      xml-cocoon2/properties.xml
  
  Index: properties.xml
  ===================================================================
  RCS file: /home/cvs/xml-cocoon2/properties.xml,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- properties.xml	16 Sep 2002 15:35:14 -0000	1.3
  +++ properties.xml	17 Sep 2002 12:07:44 -0000	1.4
  @@ -103,6 +103,7 @@
         <blocks>
           <fop include="true"/>
           <batik include="true"/>
  +        <chaperon include="true"/>
         </blocks>
   
      </cocoon>
  
  
  
  1.1                  xml-cocoon2/src/blocks/chaperon/conf/chaperon.generator.xmap
  
  Index: chaperon.generator.xmap
  ===================================================================
  <?xml version="1.0"?>
  <xmap xpath="/sitemap/components/generators" unless="generator[@name='textparser']">
      <map:generator label="content,data" logger="sitemap.generator.textparser" name="textparser"
src="org.apache.cocoon.generation.TextParserGenerator"/>
  </xmap>
  
  
  
  1.1                  xml-cocoon2/src/blocks/chaperon/conf/chaperon.transformator.xmap
  
  Index: chaperon.transformator.xmap
  ===================================================================
  <?xml version="1.0"?>
  <xmap xpath="/sitemap/components/transformers" unless="transformer[@name='textparser']">
      <map:transformer logger="sitemap.transformer.textparser" name="textparser" src="org.apache.cocoon.transformation.TextFragmentParserTransformer"/>
  </xmap>
  
  
  
  1.1                  xml-cocoon2/src/blocks/chaperon/java/org/apache/cocoon/generation/TextParserGenerator.java
  
  Index: TextParserGenerator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, 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 (INCLUDING, 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.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  package org.apache.cocoon.generation;
  
  import org.apache.avalon.excalibur.pool.Recyclable;
  
  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.configuration.Configurable;
  import org.apache.avalon.framework.configuration.Configuration;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  import org.apache.avalon.framework.parameters.ParameterException;
  import org.apache.avalon.framework.parameters.Parameters;
  
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.components.source.SourceUtil;
  import org.apache.cocoon.caching.CacheableProcessingComponent;
  import org.apache.cocoon.environment.Request;
  import org.apache.cocoon.environment.SourceResolver;
  import org.apache.cocoon.generation.ComposerGenerator;
  import org.apache.cocoon.util.HashUtil;
  import org.apache.cocoon.xml.EmbeddedXMLPipe;
  
  import org.apache.excalibur.source.Source;
  import org.apache.excalibur.source.SourceException;
  import org.apache.excalibur.source.SourceValidity;
  import org.apache.excalibur.source.impl.validity.AggregatedValidity;
  import org.apache.excalibur.store.Store;
  
  import org.xml.sax.Attributes;
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  import org.xml.sax.helpers.AttributesImpl;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.helpers.AttributesImpl;
  
  import java.io.ByteArrayInputStream;
  import java.io.IOException;
  import java.io.Serializable;
  import java.util.Map;
  
  import net.sourceforge.chaperon.grammar.Grammar;
  import net.sourceforge.chaperon.grammar.SyntaxErrorException;
  import net.sourceforge.chaperon.grammar.generator.SAXGrammarGenerator;
  import net.sourceforge.chaperon.parser.ParserException;
  import net.sourceforge.chaperon.parser.Parser;
  import net.sourceforge.chaperon.parser.ParserTable;
  import net.sourceforge.chaperon.parser.generator.ParserTableGenerator;
  import net.sourceforge.chaperon.parser.output.EventQueue;
  import net.sourceforge.chaperon.parser.output.SAXEventAdapter;
  
  /**
   * A generator that parse text via a LR Paser.
   * The generator owns two parameter 'includeignorabletokens', which 
   * decides if the ignorable tokens should be included, and 'grammar',
   * which specified the grammar.
   *
   * @author <a href="mailto:stephan@apache.org">Stephan Michels</a>
   * @version CVS $Id: TextParserGenerator.java,v 1.1 2002/09/17 12:07:44 stephan Exp $
   */
  public class TextParserGenerator extends ComposerGenerator
         implements CacheableProcessingComponent {
  
      /** The URI of the parser exception */
      public final static String URI = "http://chaperon.sourceforge.net/schema/parser-exception/1.0";
  
      /** Element name */
      public final static String ELEMENT = "parser-exception";
  
      /** Attribute name of the message property */
      public final static String MESSAGE_ATTRIBUTE = "message";
  
      /** Attribute name of the message property */
      public final static String LINENUMBER_ATTRIBUTE = "linenr";
  
      /** Attribute name of the message property */
      public final static String COLUMNNUMBER_ATTRIBUTE = "columnnr";
  
      /** Element name for acceptedsymbols */
      public final static String ACCEPTEDSYMBOL_ELEMENT = "parser-exception-accept";
  
      /** The input source */
      private Source      inputSource = null;
      private Source      grammarSource = null;
  
      private String      grammar = null;
      private boolean     includeIgnorableTokens = false;
  
      private ParserTable parsertable = null;
  
      private Parser      parser = null;
  
      /**
       * Recycle this component.
       * All instance variables are set to <code>null</code>.
       */
    	public void recycle()	{
  
          if (this.inputSource!=null)
              super.resolver.release(this.inputSource);
          this.inputSource = null;
          if (this.grammarSource!=null)
              super.resolver.release(this.grammarSource);
          this.grammarSource = null;
  
          inputSource = null;
          grammarSource = null;
          grammar = null;
          includeIgnorableTokens = false;
          parsertable = null;
          parser = null;
  
          super.recycle();
    	}
  
      /**
       * Set the SourceResolver, objectModel Map, the source and sitemap 
       * Parameters used to process the request.
       *
       * @param resolver Source resolver
       * @param objectmodel Object model
       * @param src Source
       * @param parameters Parameters
       *
       * @throws IOException
       * @throws ProcessingException
       * @throws SAXException
       */
      public void setup(SourceResolver resolver, Map objectmodel, String src,
                        Parameters parameters)
                        throws ProcessingException, SAXException, IOException {
          super.setup(resolver, objectmodel, src, parameters);
          Store store = null;
          try {
              this.includeIgnorableTokens = parameters.getParameterAsBoolean("includeignorabletokens",
false);
              this.grammar = parameters.getParameter("grammar");
  
              this.grammarSource = resolver.resolveURI(this.grammar);
  
              // Retrieve the parser table from the transient store 
              store = (Store)this.manager.lookup(Store.TRANSIENT_STORE);
              ParserTableEntry entry = (ParserTableEntry)store.get(this.grammarSource.getSystemId());
  
              // If the parser table has changed, rebuild the parser table
              if ((entry==null) ||
                  (entry.getValidity()==null) ||
                  (!entry.getValidity().isValid(this.grammarSource.getValidity()))) {
                  getLogger().debug("(Re)building the parsertable from '"+this.grammarSource.getSystemId()+"'");
  
                  SAXGrammarGenerator grammargenerator = new SAXGrammarGenerator();
                  SourceUtil.toSAX(this.grammarSource, grammargenerator, this.manager);
  
                  Grammar grammar = grammargenerator.getGrammar();
                  SyntaxErrorException see = grammar.validate();
                  if (see!=null) {
                      getLogger().error("Grammar is not correct", see);
                      throw new ProcessingException("Grammar is not correct", see);
                  }
  
                  ParserTableGenerator parsertablegenerator = new ParserTableGenerator(grammar);
                  this.parsertable = parsertablegenerator.getParserTable();
  
                  store.store(this.grammarSource.getSystemId(), new ParserTableEntry(this.parsertable,
                                                                    this.grammarSource.getValidity()));
              } else {
                  getLogger().debug("Getting parsertable from store for '"+this.grammarSource.getSystemId()+"'");
                  this.parsertable = entry.getParserTable();
              }
  
              this.inputSource = resolver.resolveURI(src);
  
          } catch (ParameterException pe) {
              getLogger().error("Error during retrieving a parameter", pe);
              throw new ProcessingException("Error during retrieving a parameter", pe);
          } catch (SourceException se) {
              getLogger().error("Error during resolving of '" + src + "'.", se);
              throw new ProcessingException("Error during resolving of '" + src + "'.", se);
          } catch (ComponentException ce) {
              getLogger().error("Could not lookup for component", ce);
              throw new ProcessingException("Could not lookup for component", ce);
          } catch (SyntaxErrorException see) {
              getLogger().error("Grammar is not correct", see);
              throw new ProcessingException("Grammar is not correct", see);
          } finally {
              if (store!=null)
              this.manager.release(store);
          }
      }
  
      /**
       * Generate the unique key.
       * This key must be unique inside the space of this component.
       * This method must be invoked before the generateValidity() method.
       *
       * @return The generated key or <code>null</code> if the component
       *              is currently not cacheable.
       */
      public Serializable generateKey() {
          return "TPG("+this.inputSource.getSystemId()+";"+this.grammarSource.getSystemId()+")";
      }
  
      /**
       * Generate the validity object.
       * Before this method can be invoked the generateKey() method
       * must be invoked.
       *
       * @return The generated validity object or <code>null</code> if the
       *         component is currently not cacheable.
       */
      public SourceValidity generateValidity() {
          SourceValidity inputsourcevalidity  = this.inputSource.getValidity();
          SourceValidity grammarsourcevalidity = this.grammarSource.getValidity();
  
          if ((inputsourcevalidity==null) && (grammarsourcevalidity==null))
              return null;
  
          AggregatedValidity validity = new AggregatedValidity();
          if (inputsourcevalidity!=null)
              validity.add(inputsourcevalidity);
          if (grammarsourcevalidity!=null)
              validity.add(grammarsourcevalidity);
          return validity;
      }
  
      /**
       * Generate XML data.
       */
      public void generate() throws IOException, SAXException, ProcessingException {
          try {
              if (parser==null) {
                  parser = new Parser();
                  parser.enableLogging(getLogger());
              }
  
              EventQueue queue = parser.parse(this.parsertable, this.inputSource.getInputStream());
  
              SAXEventAdapter adapter = new SAXEventAdapter(super.contentHandler, 
                                                          this.includeIgnorableTokens, false);
              queue.fireEvents(adapter);
          } catch (ParserException pe) {
              getLogger().error("Document ist not valid", pe);
              toSAX(super.contentHandler, pe);
          } catch (SourceException se) {
              getLogger().error("Could not get inputstream from source", se);
              throw new ProcessingException("Could not get inputstream from source", se);
          }
      }
  
      /** 
       * Serialize the exception to a SAX stream
       *
       * @param handler The content handler, which receives the SAX events
       *
       * @throws SAXException
       */
      public void toSAX(ContentHandler handler, ParserException pe) throws SAXException {

          handler.startDocument();
  
          handler.startPrefixMapping("", URI);
      
          AttributesImpl attributes = new AttributesImpl();
      
          attributes.addAttribute(URI, MESSAGE_ATTRIBUTE, MESSAGE_ATTRIBUTE,
                                  "CDATA", pe.getMessage());
          attributes.addAttribute(URI, LINENUMBER_ATTRIBUTE, LINENUMBER_ATTRIBUTE,
                                  "CDATA", String.valueOf(pe.getLineNumber()));
          attributes.addAttribute(URI, COLUMNNUMBER_ATTRIBUTE, COLUMNNUMBER_ATTRIBUTE,
                                  "CDATA", String.valueOf(pe.getColumnNumber()));
        
          handler.startElement(URI, ELEMENT, ELEMENT, attributes);
    
          for(int i=0; i<pe.getAcceptedSymbols().length; i++) { 
              handler.startElement(URI, ACCEPTEDSYMBOL_ELEMENT, ACCEPTEDSYMBOL_ELEMENT, new
AttributesImpl());
              handler.characters(pe.getAcceptedSymbols()[i].toCharArray(), 0, 
                                 pe.getAcceptedSymbols()[i].length());
              handler.endElement(URI, ACCEPTEDSYMBOL_ELEMENT, ACCEPTEDSYMBOL_ELEMENT);
          } 
  
          handler.endElement(URI, ELEMENT, ELEMENT);
  
          handler.endPrefixMapping("");
    
          handler.endDocument();
      }
  
      /**
       * This class represent a entry in a store to cache the parsertable.
       */
      public class ParserTableEntry implements Serializable {
          private SourceValidity validity    = null;
          private ParserTable    parsertable = null;
  
          public ParserTableEntry(ParserTable parsertable, SourceValidity validity) {
              this.parsertable = parsertable;
              this.validity = validity;
          }
  
          public SourceValidity getValidity() {
              return this.validity;
          }
  
          public ParserTable getParserTable() {
              return this.parsertable;
          }
      }
  }
  
  
  
  1.1                  xml-cocoon2/src/blocks/chaperon/java/org/apache/cocoon/transformation/TextFragmentParserTransformer.java
  
  Index: TextFragmentParserTransformer.java
  ===================================================================
  /*
   *  Copyright (C) Chaperon. All rights reserved.
   *  -------------------------------------------------------------------------
   *  This software is published under the terms of the Apache Software License
   *  version 1.1, a copy of which has been included  with this distribution in
   *  the LICENSE file.
   */
  
  package org.apache.cocoon.transformation;
  
  import org.apache.avalon.excalibur.pool.Recyclable;
  
  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.configuration.Configurable;
  import org.apache.avalon.framework.configuration.Configuration;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  import org.apache.avalon.framework.logger.LogEnabled;
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.avalon.framework.parameters.ParameterException;
  import org.apache.avalon.framework.parameters.Parameters;
  
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.caching.CacheableProcessingComponent;
  import org.apache.cocoon.components.source.SourceUtil;
  import org.apache.cocoon.environment.SourceResolver;
  import org.apache.cocoon.transformation.AbstractTransformer;
  import org.apache.cocoon.util.HashUtil;
  import org.apache.cocoon.xml.EmbeddedXMLPipe;
  
  import org.apache.excalibur.source.Source;
  import org.apache.excalibur.source.SourceException;
  import org.apache.excalibur.source.SourceValidity;
  import org.apache.excalibur.store.Store;
  
  import org.xml.sax.Attributes;
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.helpers.AttributesImpl;
  
  import java.io.ByteArrayInputStream;
  import java.io.IOException;
  import java.io.Serializable;
  import java.util.Map;
  
  import net.sourceforge.chaperon.grammar.Grammar;
  import net.sourceforge.chaperon.grammar.SyntaxErrorException;
  import net.sourceforge.chaperon.grammar.generator.SAXGrammarGenerator;
  import net.sourceforge.chaperon.parser.ParserException;
  import net.sourceforge.chaperon.parser.Parser;
  import net.sourceforge.chaperon.parser.ParserTable;
  import net.sourceforge.chaperon.parser.generator.ParserTableGenerator;
  import net.sourceforge.chaperon.parser.output.EventQueue;
  import net.sourceforge.chaperon.parser.output.SAXEventAdapter;
  
  /**
   * The FragmentTextParser parse text in a XML document
   *
   * @author Stephan Michels
   * @version CVS $Id: TextFragmentParserTransformer.java,v 1.1 2002/09/17 12:07:44 stephan
Exp $
   */
  public class TextFragmentParserTransformer extends AbstractTransformer
          implements Composable, Recyclable, Disposable, CacheableProcessingComponent {
      private static String EXTRACT_URI = "http://chaperon.sourceforge.net/schema/textfragment/1.0";
      private static String EXTRACT_ELEMENT = "textfragment";
  
      /** The URI of the parser exception DTD */
      public final static String URI = "http://chaperon.sourceforge.net/schema/parser-exception/1.0";
  
      /** Element name */
      public final static String ELEMENT = "parser-exception";
  
      /** Attribute name of the message property */
      public final static String MESSAGE_ATTRIBUTE = "message";
  
      /** Attribute name of the message property */
      public final static String LINENUMBER_ATTRIBUTE = "linenr";
  
      /** Attribute name of the message property */
      public final static String COLUMNNUMBER_ATTRIBUTE = "columnnr";
  
      /** Element name for acceptedsymbols */
      public final static String ACCEPTEDSYMBOL_ELEMENT = "parser-exception-accept";
  
      private int              extractLevel = 0;
  
      private StringBuffer     text = null;
  
      private Source           grammarSource = null;
    
      private ComponentManager manager = null;
      private SourceResolver   resolver = null;
    
      private String           grammar = null;
      private boolean          includeIgnorableTokens = false;
    
      private ParserTable      parsertable = null;
  
      private Parser           parser = null;
  
      /**
       * Pass the ComponentManager to the composer. The Composable 
       * implementation should use the specified ComponentManager
       * to acquire the components it needs for execution.
       *
       * @param manager The ComponentManager which this Composable uses.
       */
      public void compose(ComponentManager manager) {
          this.manager = manager;
      }
  
      /**
       * Recycle this component.
       * All instance variables are set to <code>null</code>.
       */
      public void recycle() {
          if ((this.resolver!=null) && (this.grammarSource!=null)) {
              this.resolver.release(this.grammarSource);
              this.grammarSource = null;
          }
  
          this.parsertable = null;
      }
  
      /**
       * The dispose operation is called at the end of a 
       * components lifecycle.
       */
      public void dispose() {
          if ((this.resolver!=null) && (this.grammarSource!=null)) {
              this.resolver.release(this.grammarSource);
              this.grammarSource = null;
          }
  
          this.manager = null;
      }
  
      /**
       * Set the SourceResolver, objectModel Map, the source and sitemap 
       * Parameters used to process the request.
       *
       * @param resolver Source resolver
       * @param objectmodel Object model
       * @param src Source
       * @param parameters Parameters
       */
      public void setup(SourceResolver resolver, Map objectmodel, String src,
                        Parameters parameters)
              throws ProcessingException, SAXException, IOException {
          this.resolver = resolver;
          Store store = null;
          try {
              this.includeIgnorableTokens = parameters.getParameterAsBoolean("includeignorabletokens",
false);
              this.grammar = parameters.getParameter("grammar");
  
              this.grammarSource = resolver.resolveURI(this.grammar);
  
              // Retrieve the parser table from the transient store 
              store = (Store)this.manager.lookup(Store.TRANSIENT_STORE);
              ParserTableEntry entry = (ParserTableEntry)store.get(this.grammarSource.getSystemId());
  
              // If the parser table has changed, rebuild the parser table
              if ((entry==null) ||
                  (entry.getValidity()==null) ||
                  (!entry.getValidity().isValid(this.grammarSource.getValidity()))) {
                  getLogger().debug("(Re)building the parsertable from '"+this.grammarSource.getSystemId()+"'");
  
                  SAXGrammarGenerator grammargenerator = new SAXGrammarGenerator();
                  SourceUtil.toSAX(this.grammarSource, grammargenerator, this.manager);
  
                  Grammar grammar = grammargenerator.getGrammar();
                  SyntaxErrorException see = grammar.validate();
                  if (see!=null) { 
                      getLogger().error("Grammar is not correct", see);
                      throw new ProcessingException("Grammar is not correct", see);
                  }
  
                  ParserTableGenerator parsertablegenerator = new ParserTableGenerator(grammar);
                  this.parsertable = parsertablegenerator.getParserTable();
  
                  store.store(this.grammarSource.getSystemId(), new ParserTableEntry(this.parsertable,
                                                                    this.grammarSource.getValidity()));
              } else {
                  getLogger().debug("Getting parsertable from store for '"+this.grammarSource.getSystemId()+"'");
                  this.parsertable = entry.getParserTable();
              }
  
          } catch (ParameterException pe) {
              getLogger().error("Error during retrieving a parameter", pe);
              throw new ProcessingException("Error during retrieving a parameter", pe);
          } catch (SourceException se) {
              getLogger().error("Error during resolving of '" + src + "'.", se);
              throw new ProcessingException("Error during resolving of '" + src + "'.", se);
          } catch (ComponentException ce) {
              getLogger().error("Could not lookup for component", ce);
              throw new ProcessingException("Could not lookup for component", ce);
          } catch (SyntaxErrorException see) {
              getLogger().error("Grammar is not correct", see);
              throw new ProcessingException("Grammar is not correct", see);
          } finally {
              if (store!=null)
                  this.manager.release(store);
          }
      }
  
      /**
       * Generate the unique key.
       * This key must be unique inside the space of this component.
       *
       * @return The generated key hashes the src
       */
      public Serializable generateKey() {
          return this.grammarSource.getSystemId();
      }
  
      /**
       * Generate the validity object.
       *
       * @return The generated validity object or <code>null</code> if the
       *         component is currently not cacheable.
       */
      public SourceValidity generateValidity() {
          return this.grammarSource.getValidity();
      }
  
      /**
       * 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 (this.EXTRACT_URI.equals(uri) && this.EXTRACT_ELEMENT.equals(loc)
              && (this.grammar != null)) {
  
              this.extractLevel++;
              this.text = new StringBuffer();
          } else
              super.startElement(uri, loc, raw, a);
      }
  
      /**
       * 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 {
          if (this.EXTRACT_URI.equals(uri) && this.EXTRACT_ELEMENT.equals(loc)
              && (this.grammar != null)) {
  
              this.extractLevel--;
    
              try {
                  if (parser==null) {
                      parser = new Parser();
                      parser.enableLogging(getLogger());
                  }
             
                  EventQueue queue = parser.parse(this.parsertable, 
                      new ByteArrayInputStream(this.text.toString().getBytes()));
  
                  SAXEventAdapter adapter = new SAXEventAdapter(super.contentHandler, 
                                                                this.includeIgnorableTokens,
true);
                  //adapter.enableLogging(getLogger());
                  queue.fireEvents(adapter);
              } catch (ParserException pe) {
                  getLogger().error("Document ist not valid", pe);
                  EmbeddedXMLPipe pipe = new EmbeddedXMLPipe(super.contentHandler);
                  toSAX(pipe, pe);
              }  
  
              this.text = null;
          } else
              super.endElement(uri, loc, raw);
      }
  
      /**
       * 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 {
          if (this.extractLevel > 0)
              this.text.append(c, start, len);
          else
              super.characters(c, start, len);
      }
  
      /** 
       * Serialize the exception to a SAX stream
       *
       * @param handler The content handler, which receives the SAX events
       *
       * @throws SAXException
       */
      public void toSAX(ContentHandler handler, ParserException pe) throws SAXException {
          handler.startDocument();
  
          handler.startPrefixMapping("", URI);
  
          AttributesImpl attributes = new AttributesImpl();
  
          attributes.addAttribute(URI, MESSAGE_ATTRIBUTE, MESSAGE_ATTRIBUTE,
                                  "CDATA", pe.getMessage());
          attributes.addAttribute(URI, LINENUMBER_ATTRIBUTE, LINENUMBER_ATTRIBUTE,
                                  "CDATA", String.valueOf(pe.getLineNumber()));
          attributes.addAttribute(URI, COLUMNNUMBER_ATTRIBUTE, COLUMNNUMBER_ATTRIBUTE,
                                  "CDATA", String.valueOf(pe.getColumnNumber()));
  
          handler.startElement(URI, ELEMENT, ELEMENT, attributes);
  
          for(int i=0; i<pe.getAcceptedSymbols().length; i++) {
              handler.startElement(URI, ACCEPTEDSYMBOL_ELEMENT, ACCEPTEDSYMBOL_ELEMENT, new
AttributesImpl());
              handler.characters(pe.getAcceptedSymbols()[i].toCharArray(), 0, 
                                 pe.getAcceptedSymbols()[i].length());
              handler.endElement(URI, ACCEPTEDSYMBOL_ELEMENT, ACCEPTEDSYMBOL_ELEMENT);
          }
  
          handler.endElement(URI, ELEMENT, ELEMENT);
  
          handler.endPrefixMapping("");
  
          handler.endDocument();
      }
  
      /**
       * This class represent a entry in a store to cache the parsertable.
       */
      public class ParserTableEntry implements Serializable {
          private SourceValidity validity    = null;
          private ParserTable    parsertable = null;
  
          public ParserTableEntry(ParserTable parsertable, SourceValidity validity) {
              this.parsertable = parsertable;
              this.validity = validity;
          }
  
          public SourceValidity getValidity() {
              return this.validity;
          }
  
          public ParserTable getParserTable() {
              return this.parsertable;
          }
      }
  }
  
  
  

----------------------------------------------------------------------
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