sboag       00/06/19 09:53:55

  Added:       java     Makefile make.include make.include2
               java/bin bsf.jar bsfengines.jar
               java/src makexpath4j makexslt4j
               java/src/org/apache/xalan/client XSLTProcessorApplet.java
               java/src/org/apache/xalan/dtm ChunkedIntArray.java DTM.java
                        DTMException.java DTMLiaison.java
                        DTMNodeLocator.java DTMNodeVector.java
                        DTMProxy.java DTMProxyMap.java IntMap.java
                        IntToObjectMap.java
               java/src/org/apache/xalan/extensions
                        ExtensionFunctionHandler.java
                        ExtensionNSHandler.java ExtensionsTable.java
                        XSLProcessorContext.java XSLTJavaClassEngine.java
                        extensions.dfPackage
               java/src/org/apache/xalan/lib Redirect.java
               java/src/org/apache/xalan/processor
                        ProcessorAttributeSet.java ProcessorCharacters.java
                        ProcessorDecimalFormat.java
                        ProcessorGlobalParamDecl.java
                        ProcessorGlobalVariableDecl.java
                        ProcessorImport.java ProcessorInclude.java
                        ProcessorKey.java ProcessorLRE.java
                        ProcessorNamespaceAlias.java
                        ProcessorOutputElem.java
                        ProcessorPreserveSpace.java
                        ProcessorStripSpace.java
                        ProcessorStylesheetDoc.java
                        ProcessorStylesheetElement.java
                        ProcessorTemplate.java ProcessorTemplateElem.java
                        ProcessorText.java StylesheetHandler.java
                        StylesheetProcessor.java
                        TemplateElementFactory.java
                        XSLProcessorVersion.java XSLTAttributeDef.java
                        XSLTElementDef.java XSLTElementProcessor.java
                        XSLTSchema.java
               java/src/org/apache/xalan/res XSLMessages.java
                        XSLResourceBundle.java XSLTErrorResources.java
                        XSLTErrorResources_en.java XSLTInfo.properties
                        XSLTResourceBundle.java XSLTResources_cy.java
                        XSLTResources_el.java XSLTResources_en.java
                        XSLTResources_he.java XSLTResources_hy.java
                        XSLTResources_ja_JP_A.java
                        XSLTResources_ja_JP_HA.java
                        XSLTResources_ja_JP_HI.java
                        XSLTResources_ja_JP_I.java XSLTResources_ka.java
                        XSLTResources_zh_CN.java XSLTResources_zh_TW.java
               java/src/org/apache/xalan/stree AttrImpl.java
                        AttrImplNS.java CDATASectionImpl.java Child.java
                        CommentImpl.java DOMImplementationImpl.java
                        DocumentFragmentImpl.java DocumentImpl.java
                        DocumentTypeImpl.java ElementImpl.java
                        ElementImplWithNS.java IndexedDocImpl.java
                        IndexedElem.java IndexedElemImpl.java
                        IndexedElemWithNS.java IndexedLocPathIterator.java
                        IndexedUnionPathIterator.java
                        LevelIndexIterator.java LevelIndexer.java
                        NotationImpl.java Parent.java
                        ProcessingInstructionImpl.java
                        SourceTreeHandler.java StreeDOMHelper.java
                        StreeLocator.java TextImpl.java WhiteSpace.java
               java/src/org/apache/xalan/templates AVT.java AVTPart.java
                        AVTPartSimple.java AVTPartXPath.java Constants.java
                        DecimalFormatProperties.java ElemApplyImport.java
                        ElemApplyTemplates.java ElemAttribute.java
                        ElemAttributeSet.java ElemCallTemplate.java
                        ElemChoose.java ElemComment.java ElemCopy.java
                        ElemCopyOf.java ElemElement.java ElemEmpty.java
                        ElemExtensionCall.java ElemFallback.java
                        ElemForEach.java ElemIf.java ElemLiteralResult.java
                        ElemMessage.java ElemNumber.java ElemOtherwise.java
                        ElemPI.java ElemParam.java ElemSort.java
                        ElemTemplate.java ElemTemplateElement.java
                        ElemText.java ElemTextLiteral.java ElemUse.java
                        ElemValueOf.java ElemVariable.java ElemWhen.java
                        ElemWithParam.java FuncDocument.java
                        FuncFormatNumb.java FuncKey.java
                        KeyDeclaration.java NamespaceAlias.java
                        OutputFormatExtended.java Stylesheet.java
                        StylesheetComposed.java StylesheetRoot.java
                        TemplateList.java WhiteSpaceInfo.java
                        XMLNSDecl.java
               java/src/org/apache/xalan/trace GenerateEvent.java
                        PrintTraceListener.java SelectionEvent.java
                        TraceListener.java TraceManager.java
                        TracerEvent.java
               java/src/org/apache/xalan/transformer Counter.java
                        CountersTable.java DecimalToRoman.java
                        KeyIterator.java KeyManager.java KeyTable.java
                        KeyWalker.java MsgMgr.java NodeSortKey.java
                        NodeSorter.java NumeratorFormatter.java
                        ResultNameSpace.java ResultTreeFrag.java
                        ResultTreeHandler.java StackGuard.java
                        TransformerImpl.java TreeWalker2Result.java
                        XSLInfiniteLoopException.java
               java/src/org/apache/xalan/utils AttList.java BoolStack.java
                        DOMBuilder.java DefaultErrorHandler.java
                        ElemDesc.java Heap.java HeapObject.java
                        IntStack.java IntVector.java
                        MutableAttrListImpl.java NSInfo.java NameSpace.java
                        NodeVector.java ObjectPool.java PrefixResolver.java
                        PrefixResolverDefault.java QName.java
                        RawCharacterHandler.java StringKey.java
                        StringToIntTable.java StringToStringTable.java
                        StringToStringTableVector.java StringVector.java
                        SystemIDResolver.java TreeWalker.java Trie.java
                        UnImplNode.java WrongParserException.java
               java/src/org/apache/xalan/xpath Arg.java DOM2Helper.java
                        DOMHelper.java FoundIndex.java FunctionTable.java
                        Keywords.java Lexer.java LocPathIterator.java
                        NodeSet.java OpCodes.java OpMap.java Process.java
                        PsuedoNames.java SimpleNodeLocator.java
                        SourceTree.java SourceTreeManager.java
                        UnionPathIterator.java VariableStack.java
                        XBoolean.java XBooleanStatic.java XLocator.java
                        XNodeSet.java XNull.java XNumber.java XObject.java
                        XPath.java XPathAPI.java XPathContext.java
                        XPathDumper.java XPathException.java
                        XPathFactory.java XPathParser.java
                        XPathProcessorException.java XRTreeFrag.java
                        XString.java
               java/src/org/apache/xalan/xpath/axes
                        AncestorOrSelfWalker.java AncestorWalker.java
                        AttributeWalker.java AxesWalker.java
                        ChildWalker.java DescendantOrSelfWalker.java
                        DescendantWalker.java FilterExprWalker.java
                        FollowingSiblingWalker.java FollowingWalker.java
                        NamespaceWalker.java ParentWalker.java
                        PrecedingSiblingWalker.java PrecedingWalker.java
                        ReverseAxesWalker.java RootWalker.java
                        SelfWalker.java
               java/src/org/apache/xalan/xpath/functions FuncBoolean.java
                        FuncCeiling.java FuncConcat.java FuncContains.java
                        FuncCount.java FuncCurrent.java FuncDoc.java
                        FuncDoclocation.java FuncExtElementAvailable.java
                        FuncExtFunctionAvailable.java FuncFalse.java
                        FuncFloor.java FuncFormatNumber.java
                        FuncGenerateId.java FuncId.java FuncLang.java
                        FuncLast.java FuncLoader.java FuncLocalPart.java
                        FuncNamespace.java FuncNormalize.java
                        FuncNormalizeSpace.java FuncNot.java
                        FuncNumber.java FuncPosition.java FuncQname.java
                        FuncRound.java FuncStartsWith.java FuncString.java
                        FuncStringLength.java FuncSubstring.java
                        FuncSubstringAfter.java FuncSubstringBefore.java
                        FuncSum.java FuncSystemProperty.java
                        FuncTranslate.java FuncTrue.java
                        FuncUnparsedEntityURI.java Function.java
               java/src/org/apache/xalan/xpath/res
                        XPATHErrorResourceBundle.java
                        XPATHErrorResources.java
                        XPATHErrorResources_en.java
               java/src/org/apache/xalan/xslt Process.java
                        StylesheetSpec.java
  Log:
  Xalan 2.0.0d1
  
  Revision  Changes    Path
  1.1                  xml-xalan/java/Makefile
  
  Index: Makefile
  ===================================================================
  ###########################################################
  # Makefile for xml-xalan, an XSLT Processor
  #
  # Please note the following assumptions!
  #  - See make.include for system tools definitions. We assume
  #    that each of these tools are on the path and properly setup.
  #  
  #  - Use GNU make or an equivalent.  On Win32, you can see
  #    http://sourceware.cygnus.com/cygwin for a port. 
  #  
  #  - With JDK 1.1.7B or earlier, a 'make all' may fail the first
  #    time. Try running it again twice, and everything should work.
  #    Note that when using JDK 1.2.x, it all works fine. We'll work on it.
  #  
  #  - Note the several attempts to determine if we're on WinXX or Unix:
  #    ifeq (,$(findstring usr,$(PATH)))
  #    Feel free to modify to work for your machine, and suggest a better
  #    way to create a platform-independent makefile.
  #  
  #  - The docs directory currently requires javadoc from the JDK 1.2.x
  #    You may need to edit make.include 'JAVADOC12' for your system.
  #
  #  - Yes, we plan to move to an 'Ant' based make system soon
  #    (Ant is from jakarta.apache.org and is a Java-based make)
  ###########################################################
  
  include make.include
  
  SUBDIRS = src
  
  ###########################################################
  # Main targets definitions
  #
  # Note that make.include also defines common targets
  ###########################################################
  all: makesubdirs jars makesamples makedocs
  
  build: makesubdirs jars
  # To change debug/release options, see make.include for JAVADEBUG flag
  
  # Create a distribution module
  dist: makedist
  
  docs: makedocs
  
  samples: makesamples
  
  jars: makesubdirs $(JARNAME)
  
  PROPPATH = org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res
  $(JARNAME)::
        $(CP) src/$(PROPPATH)/*.properties src/$(CLASS_DIR)/$(PROPPATH)/.; \
        echo -n "Jarring ../bin/$@ .. "; \
        cd src/$(CLASS_DIR); $(JAR) $(JARFLAGS) ../../bin/$@ org trax; \
        echo "done"
  
  # Note: When making dist, copy the built docs up one level
  # Note: Create both a super-jar and a tar.gz archive
  DISTDIR  = $(PRODUCT_NAME)$(VERSION)
  .PHONY: makedist
  makedist:
        echo Prepare creating $(DIST_NAME)
        -mkdir $(DISTDIR)
        $(CP) * $(DISTDIR);\
        $(CPR) xdocs $(DISTDIR);\
        $(CPR) samples $(DISTDIR);\
        $(CPR) src $(DISTDIR);\
        $(CPR) build/docs $(DISTDIR);\
        echo Create $(JARDISTNAME);\
        $(JAR) -cf $(JARDISTNAME) $(DISTDIR);\
        echo Create $(TARDISTNAME);\
        $(TARGZ) $(TARDISTNAME) $(DISTDIR);\
        echo Create $(ZIPDISTNAME);\
        $(JAR) -cMf $(ZIPDISTNAME) $(DISTDIR);\
        echo Done creating $(JARDISTNAME) etc., you should sign this with PGP 
before posting
  
  # Subsidiary targets are defined in make.include
  clean:: cleansubdirs cleandocs cleansamples
  
  
  
  
  1.1                  xml-xalan/java/make.include
  
  Index: make.include
  ===================================================================
  ###########################################################
  # Common variables and targets for XPath and xslt4j
  #
  # See Makefile for important environment notes
  #
  ###########################################################
  
  ###########################################################
  # Project-specific variables and rules
  #
  # You should not need to edit these
  ###########################################################
  JAVAX = .java
  CLASSX = .class
  JARX  = .jar
  TARX  = .tar.gz
  ZIPX  = .zip
  OBJS  = $(SRCS:%.java=%.class)
  
  # A simple marker file created to show last compile time
  # Note subdirectories may reset the name!
  SINCE_FILE       = since.last
  
  # Relative directory (usually from ./src/.) where class files are to go
  CLASS_DIR        = classes
  
  CURRENT_DIR      = .
  
  ###########################################################
  # Build-specific tools and flags definitions
  ###########################################################
  PRODUCT_NAME := xalan
  VERSION      = _1_1_D01
  JARNAME      = $(PRODUCT_NAME)$(JARX)
  JARDISTNAME  = $(PRODUCT_NAME)-j$(VERSION)$(JARX)
  TARDISTNAME  = $(PRODUCT_NAME)-j$(VERSION)$(TARX)
  ZIPDISTNAME  = $(PRODUCT_NAME)-j$(VERSION)$(ZIPX)
  
  ###########################################################
  # Environment-specific tools and flags definitions
  #
  # You may need to edit these if you're not using
  # a standard JDK or the tools aren't on the path.
  ###########################################################
  # References to default tools
  JAVA       = java
  JAVAC      = javac
  JAVADOC    = javadoc
  JAR        = jar
  # References to JDK 1.2-only tools; required for xdocs build
  # While the code compiles under 1.1.8 or 1.2.2, the docs require 1.2.2
  # Thus, you can install both JDK's, set 1.1.8 up as default,
  # then call us like 'make -f Makefile JAVAC12=c:/jdk122/bin/javac.exe ...'
  #    This should compile the sources with 1.1.8, but the doc with 1.2.2
  JAVA12     = java
  JAVAC12    = javac
  JAVADOC12  = javadoc
  
  # Setting flags for various tools
  # You can override these on the make command line as well
  #    Call us like 'make -f Makefile JAVADEBUG=-g:none ...'
  JAVADEBUG   = -g
  JAVADESTDIR = -d $(CLASS_DIR)
  JAVACFLAGS  = $(JAVADEBUG) $(JAVADESTDIR)
  JARFLAGS    = cf0
  
  # References to other tools
  RM         = rm -f
  RM-RF      = rm -rf
  CP         = cp -f
  CPR        = cp -Rvf
  UPDIR      := ..
  
  # References to standard UNIX or Cygwin tar utility, filtering through gzip
  TARGZ      = tar cvzf
  UNTARGZ      = tar xvzf 
  
  # Decide if we're on unix or DOS
  ifeq (,$(findstring usr,$(PATH)))
  # DOS
  PATHSEP := \\
  CLPATHSEP := ;
  else 
  # UNIX
  PATHSEP := /
  CLPATHSEP := :
  endif
  
  ###########################################################
  # Main targets definitions
  ###########################################################
  .PHONY: makeall
  makeall: all
  
  .PHONY: clean
  clean::
        $(RM) *.class $(JARNAME) *~ *.bak *.o *.obj *.dll $(SINCE_FILE)
  
  .PHONY: makesubdirs
  makesubdirs:
        @for i in $(SUBDIRS) ; \
        do \
        (cd $$i; echo making xpath engine in "$(CURRENT_DIR)/$$i..."; \
        $(MAKE) CURRENT_DIR=$(CURRENT_DIR)/$$i $(MFLAGS) -f makexpath4j 
JAVACFLAGS="$(JAVACFLAGS)" all); \
        (cd $$i; echo making xslt engine in "$(CURRENT_DIR)/$$i..."; \
        $(MAKE) CURRENT_DIR=$(CURRENT_DIR)/$$i $(MFLAGS) -f makexslt4j 
JAVACFLAGS="$(JAVACFLAGS)" all); \
        done
  
  .PHONY: makedocs
  makedocs:
        @for i in xdocs ; \
        do \
        (cd $$i; echo making x-docs in "$(CURRENT_DIR)/$$i..."; \
        $(MAKE) CURRENT_DIR=$(CURRENT_DIR)/$$i $(MFLAGS) -f Makefile all); \
        done
  
  .PHONY: makesamples
  makesamples:
        @for i in samples ; \
        do \
        (cd $$i; echo making samples in "$(CURRENT_DIR)/$$i..."; \
        $(MAKE) CURRENT_DIR=$(CURRENT_DIR)/$$i $(MFLAGS) -f Makefile all); \
        done
  
  .PHONY: cleansubdirs 
  cleansubdirs:
        [EMAIL PROTECTED] i in $(SUBDIRS) ; \
        do \
        (cd $$i; echo cleaning in "$(CURRENT_DIR)/$$i..."; \
        $(MAKE) CURRENT_DIR=$(CURRENT_DIR)/$$i -f makexpath4j $(MFLAGS) clean); 
\
        (cd $$i; echo cleaning in "$(CURRENT_DIR)/$$i..."; \
        $(MAKE) CURRENT_DIR=$(CURRENT_DIR)/$$i -f makexslt4j $(MFLAGS) clean); \
        done
  
  .PHONY: cleandocs
  cleandocs:
        @for i in xdocs ; \
        do \
        (cd $$i; echo cleaning up x-docs "$(CURRENT_DIR)/$$i..."; \
        $(MAKE) CURRENT_DIR=$(CURRENT_DIR)/$$i $(MFLAGS) -f Makefile clean); \
        done
  
  .PHONY: cleansamples
  cleansamples:
        @for i in samples ; \
        do \
        (cd $$i; echo cleaning up samples "$(CURRENT_DIR)/$$i..."; \
        $(MAKE) CURRENT_DIR=$(CURRENT_DIR)/$$i $(MFLAGS) -f Makefile clean); \
        done
  
  # End of file
  
  
  1.1                  xml-xalan/java/make.include2
  
  Index: make.include2
  ===================================================================
  ###########################################################
  # Common definitions and main 'compile' rule for xpath and xslt.
  #
  # See Makefile for important environment notes
  # 
  ###########################################################
  
  # Note this is separate from the variable in make.include
  CLASSESDIR = classes
  
  # Add other required dirs to the classpath
  XML4J_CLASSPATH := 
..$(PATHSEP)..$(PATHSEP)..$(PATHSEP)xml-xerces$(PATHSEP)java$(PATHSEP)bin$(PATHSEP)xerces.jar
  BSF_CLASSPATH := ..$(PATHSEP)bin$(PATHSEP)bsf.jar
  # Add . (current dir) to end of classpath to help 1.1.x compilers find all 
the source files, thanks to Sean Timm
  EXTRA_CLASSPATH := 
$(XML4J_CLASSPATH)$(CLPATHSEP)$(BSF_CLASSPATH)$(CLPATHSEP)$(CLASSESDIR)$(CLPATHSEP)$(CLASSPATH)$(CLPATHSEP).
  
  sincelast: $(SINCE_FILE)
  $(SINCE_FILE): $(SRCS)
        -mkdir $(CLASSESDIR)
        $(JAVAC) $(JAVACFLAGS) -classpath "$(EXTRA_CLASSPATH)" $?
        touch $(SINCE_FILE)
  
  
  
  
  
  1.1                  xml-xalan/java/bin/bsf.jar
  
        <<Binary file>>
  
  
  1.1                  xml-xalan/java/bin/bsfengines.jar
  
        <<Binary file>>
  
  
  1.1                  xml-xalan/java/src/makexpath4j
  
  Index: makexpath4j
  ===================================================================
  ###########################################################
  # Makefile for the XPath engine.
  #
  # See ../Makefile for important environment notes
  #
  ###########################################################
  
  # Include common targets and variables
  include ../make.include
  
  SINCE_FILE       = sincexpath.last
  
  # Define our directory structure
  PROJDIR = org$(PATHSEP)apache$(PATHSEP)xalan
  XPATHDIR = $(PROJDIR)$(PATHSEP)xpath
  UTILSDIR = $(PROJDIR)$(PATHSEP)utils
  XSLT4JDIR = $(PROJDIR)$(PATHSEP)xslt
  CLIENTDIR = $(PROJDIR)$(PATHSEP)xslt$(PATHSEP)client
  EXTENSIONSDIR = $(PROJDIR)$(PATHSEP)xslt$(PATHSEP)extensions
  TRACEDIR = $(PROJDIR)$(PATHSEP)xslt$(PATHSEP)trace
  RESDIR = $(PROJDIR)$(PATHSEP)xpath$(PATHSEP)res
  DTMDIR = $(PROJDIR)$(PATHSEP)dtm
  FUNCDIR = $(PROJDIR)$(PATHSEP)xpath$(PATHSEP)functions
  SUBDIRS = 
  
  # List of all files to compile for this module
  SRCS = \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)Arg.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)DOMHelper.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)DOM2Helper.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)FoundIndex.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)FunctionTable.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)Keywords.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)Lexer.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)NodeSet.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)OpCodes.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)OpMap.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)Process.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)PsuedoNames.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)SimpleNodeLocator.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)SourceTree.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)SourceTreeManager.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)VariableStack.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XBoolean.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XBooleanStatic.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XLocator.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XNodeSet.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XNull.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XNumber.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XObject.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XPath.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XPathAPI.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XPathContext.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XPathDumper.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XPathException.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XPathFactory.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XPathParser.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XPathProcessorException.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XRTreeFrag.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)XString.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)LocPathIterator.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)UnionPathIterator.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)ChunkedIntArray.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)DTM.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)DTMException.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)DTMLiaison.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)DTMNodeLocator.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)DTMNodeVector.java 
\
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)DTMProxy.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)DTMProxyMap.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)IntMap.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)dtm$(PATHSEP)IntToObjectMap.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)res$(PATHSEP)XPATHErrorResourceBundle.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)res$(PATHSEP)XPATHErrorResources.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)res$(PATHSEP)XPATHErrorResources_en.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)AncestorWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)AncestorOrSelfWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)AttributeWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)AxesWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)ChildWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)DescendantWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)DescendantOrSelfWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)FilterExprWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)FollowingWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)FollowingSiblingWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)NamespaceWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)ParentWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)PrecedingWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)PrecedingSiblingWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)RootWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)SelfWalker.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)axes$(PATHSEP)ReverseAxesWalker.java
        
  SRCS2 = \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncBoolean.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncCeiling.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncConcat.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncContains.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncCount.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncCurrent.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncDoc.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncDoclocation.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncExtElementAvailable.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncExtFunctionAvailable.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncFalse.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncFloor.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncFormatNumber.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncGenerateId.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncId.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncLang.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncLast.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncLoader.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncLocalPart.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncNamespace.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncNormalize.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncNormalizeSpace.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncNot.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncNumber.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncPosition.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncQname.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncRound.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncStartsWith.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncString.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncStringLength.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncSubstring.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncSubstringAfter.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncSubstringBefore.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncSum.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncSystemProperty.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)Function.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncTranslate.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncTrue.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xpath$(PATHSEP)functions$(PATHSEP)FuncUnparsedEntityURI.java
  
  OBJS = $(SRCS:%.java=classes/%.class)
  
  all: sincelast sincelast2 makesubdirs
  
  # Note double-colon targets are treated specially
  clean::
        $(RM) $(CLASS_DIR)/$(XPATHDIR)/*.class \
        $(CLASS_DIR)/$(XPATHDIR)/xml4j2dom/*.class \
        $(CLASS_DIR)/$(UTILSDIR)/*.class \
        $(CLASS_DIR)/$(RESDIR)/*.class \
        $(SINCE_FILE) sincexpath2.last
  
  include ../make.include2
  
  sincelast2: sincexpath2.last
  sincexpath2.last: $(SRCS2)
        -mkdir $(CLASSESDIR)
        $(JAVAC) $(JAVACFLAGS) -classpath "$(EXTRA_CLASSPATH)" $?
        touch sincexpath2.last
  
  
  1.1                  xml-xalan/java/src/makexslt4j
  
  Index: makexslt4j
  ===================================================================
  ###########################################################
  # Makefile for the XSLT engine.
  #
  # See ../Makefile for important environment notes
  #
  ###########################################################
  
  # Include common targets and variables
  include ../make.include
  
  SINCE_FILE       = sincexslt.last
  
  # Define our directory structure
  PROJDIR = org$(PATHSEP)apache$(PATHSEP)xalan
  XPATHDIR = $(PROJDIR)$(PATHSEP)xpath
  XMLLIAISONDIR = $(PROJDIR)$(PATHSEP)xpath$(PATHSEP)xml
  XSLT4JDIR = $(PROJDIR)$(PATHSEP)xslt
  TRANSFORMERDIR = $(PROJDIR)$(PATHSEP)transformer
  PROCESSORDIR = $(PROJDIR)$(PATHSEP)processor
  TEMPLATESDIR = $(PROJDIR)$(PATHSEP)templates
  EXTENSIONSDIR = $(PROJDIR)$(PATHSEP)extensions
  CLIENTDIR = $(PROJDIR)$(PATHSEP)client
  LIBDIR = $(PROJDIR)$(PATHSEP)lib
  TRACEDIR = $(PROJDIR)$(PATHSEP)trace
  RESDIR = $(PROJDIR)$(PATHSEP)res
  STREEDIR = $(PROJDIR)$(PATHSEP)stree
  TRAXDIR = trax
  SUBDIRS = 
  
  SRCS = \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)client$(PATHSEP)XSLTProcessorApplet.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)extensions$(PATHSEP)ExtensionFunctionHandler.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)extensions$(PATHSEP)ExtensionNSHandler.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)extensions$(PATHSEP)ExtensionsTable.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)extensions$(PATHSEP)XSLProcessorContext.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)extensions$(PATHSEP)XSLTJavaClassEngine.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)lib$(PATHSEP)Redirect.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorAttributeSet.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorCharacters.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorDecimalFormat.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorGlobalParamDecl.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorGlobalVariableDecl.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorImport.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorInclude.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorKey.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorLRE.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorNamespaceAlias.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorOutputElem.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorPreserveSpace.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorStripSpace.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorStylesheetDoc.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorStylesheetElement.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorTemplate.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorTemplateElem.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)ProcessorText.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)StylesheetHandler.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)StylesheetProcessor.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)TemplateElementFactory.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)XSLProcessorVersion.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)XSLTAttributeDef.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)XSLTElementDef.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)XSLTElementProcessor.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)processor$(PATHSEP)XSLTSchema.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLMessages.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLResourceBundle.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTErrorResources.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTErrorResources_en.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResourceBundle.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_cy.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_el.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_en.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_he.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_hy.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_ja_JP_A.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_ja_JP_HA.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_ja_JP_HI.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_ja_JP_I.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_ka.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_zh_CN.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)res$(PATHSEP)XSLTResources_zh_TW.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)AttrImpl.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)AttrImplNS.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)CDATASectionImpl.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)Child.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)CommentImpl.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)DocumentFragmentImpl.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)DocumentImpl.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)DocumentTypeImpl.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)DOMImplementationImpl.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)ElementImpl.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)ElementImplWithNS.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)IndexedDocImpl.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)IndexedElem.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)IndexedElemImpl.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)IndexedElemWithNS.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)IndexedLocPathIterator.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)IndexedUnionPathIterator.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)LevelIndexer.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)LevelIndexIterator.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)NotationImpl.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)Parent.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)ProcessingInstructionImpl.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)SourceTreeHandler.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)StreeDOMHelper.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)StreeLocator.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)TextImpl.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)stree$(PATHSEP)WhiteSpace.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)AVT.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)AVTPart.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)AVTPartSimple.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)AVTPartXPath.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)Constants.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)DecimalFormatProperties.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemApplyImport.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemApplyTemplates.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemAttribute.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemAttributeSet.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemCallTemplate.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemChoose.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemComment.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemCopy.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemCopyOf.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemElement.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemEmpty.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemExtensionCall.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemFallback.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemForEach.java 
\
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemIf.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemLiteralResult.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemMessage.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemNumber.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemOtherwise.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemParam.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemPI.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemSort.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemTemplate.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemTemplateElement.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemText.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemTextLiteral.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemUse.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemValueOf.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemVariable.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemWhen.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)ElemWithParam.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)FuncDocument.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)FuncFormatNumb.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)FuncKey.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)KeyDeclaration.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)NamespaceAlias.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)OutputFormatExtended.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)Stylesheet.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)StylesheetComposed.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)StylesheetRoot.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)TemplateList.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)WhiteSpaceInfo.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)templates$(PATHSEP)XMLNSDecl.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)trace$(PATHSEP)GenerateEvent.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)trace$(PATHSEP)PrintTraceListener.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)trace$(PATHSEP)SelectionEvent.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)trace$(PATHSEP)TraceListener.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)trace$(PATHSEP)TraceManager.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)trace$(PATHSEP)TracerEvent.java 
\
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)Counter.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)CountersTable.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)DecimalToRoman.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)KeyManager.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)KeyTable.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)MsgMgr.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)NodeSorter.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)NodeSortKey.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)NumeratorFormatter.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)ResultNameSpace.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)ResultTreeFrag.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)ResultTreeHandler.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)StackGuard.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)TransformerImpl.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)TreeWalker2Result.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)XSLInfiniteLoopException.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)transformer$(PATHSEP)KeyIterator.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)AttList.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)BoolStack.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)DefaultErrorHandler.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)DOMBuilder.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)ElemDesc.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)IntStack.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)IntVector.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)MutableAttrListImpl.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)NameSpace.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)NodeVector.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)NSInfo.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)PrefixResolver.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)PrefixResolverDefault.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)QName.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)RawCharacterHandler.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)StringKey.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)StringToIntTable.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)StringToStringTable.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)StringToStringTableVector.java
 \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)StringVector.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)SystemIDResolver.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)TreeWalker.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)Trie.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)UnImplNode.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)WrongParserException.java
 \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)HeapObject.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)Heap.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)utils$(PATHSEP)ObjectPool.java \
    org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xslt$(PATHSEP)Process.java \
    
org$(PATHSEP)apache$(PATHSEP)xalan$(PATHSEP)xslt$(PATHSEP)StylesheetSpec.java \
    trax$(PATHSEP)Examples.java \
    trax$(PATHSEP)Processor.java \
    trax$(PATHSEP)ProcessorException.java \
    trax$(PATHSEP)ProcessorFactoryException.java \
    trax$(PATHSEP)Result.java \
    trax$(PATHSEP)Templates.java \
    trax$(PATHSEP)TemplatesBuilder.java \
    trax$(PATHSEP)Transformer.java \
    trax$(PATHSEP)TransformException.java \
    trax$(PATHSEP)URIResolver.java
      
  OBJS = $($(subst /,\\,$(SRCS)):%.java=classes/%.class)
  
  all: sincelast makesubdirs
  
  clean::
        $(RM) $(CLASS_DIR)/$(XSLT4JDIR)/*.class \
        $(CLASS_DIR)/$(TRACEDIR)/*.class \
        $(CLASS_DIR)/$(CLIENTDIR)/*.class \
        $(CLASS_DIR)/$(LIBDIR)/*.class \
        $(CLASS_DIR)/$(RESDIR)/*.class \
        $(SINCE_FILE)
  
  include ../make.include2
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/client/XSLTProcessorApplet.java
  
  Index: XSLTProcessorApplet.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.client;
  
  import java.applet.Applet;
  
  import java.awt.Graphics;
  
  import java.net.URL;
  import java.net.MalformedURLException;
  
  import java.io.PrintWriter;
  import java.io.StringWriter;
  import java.io.StringReader;
  import java.io.IOException;
  import java.io.InputStream;
  
  // Needed Xalan classes
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.res.XSLTErrorResources;
  
  // Needed Xerces classes
  import org.apache.xerces.parsers.DOMParser;
  
  // Needed TRaX classes
  import trax.Result;
  import trax.Processor;
  import trax.Transformer;
  import trax.Templates;
  
  // Needed SAX classes
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  import org.xml.sax.XMLReader;
  import org.xml.sax.helpers.ParserAdapter;
  import org.xml.sax.helpers.XMLReaderFactory;
  
  // Needed DOM classes
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  
  // Needed Serializer classes
  import org.apache.xml.serialize.OutputFormat;
  import org.apache.xml.serialize.Serializer;
  import org.apache.xml.serialize.SerializerFactory;
  
  /**
   * <meta name="usage" content="general"/>
   * Provides applet host for the XSLT processor. To perform transformations on 
an HTML client:
   * <ol>
   * <li>Use an &lt;applet&gt; tag to embed this applet in the HTML client.</li>
   * <li>Use the DocumentURL and StyleURL PARAM tags or the [EMAIL PROTECTED] 
#setDocumentURL} and
   * [EMAIL PROTECTED] #setStyleURL} methods to specify the XML source document 
and XSL stylesheet.</li>
   * <li>Call the [EMAIL PROTECTED] #transformToHTML} method to perform the 
transformation and return
   * the result as a String.</li>
   * </ol>
   */
  public class XSLTProcessorApplet extends Applet
  {
  
    /**
     * The XML Parser Liaison.
     */
    Processor m_processor = null;
  
    /**
     * @serial
     */
    private String m_styleURL;
  
    /**
     * @serial
     */
    private String m_documentURL;
  
    // Parameter names.  To change a name of a parameter, you need only make
    // a single change.  Simply modify the value of the parameter string below.
    //--------------------------------------------------------------------------
    /**
     * @serial
     */
    private final String PARAM_styleURL = "styleURL";
  
    /**
     * @serial
     */
    private final String PARAM_documentURL = "documentURL";
  
    /**
     * @serial
     */
    private final String PARAM_parser = "parser";
  
    /**
     * @serial
     */
    private String whichParser = null;
  
    // We'll keep the DOM trees around, so tell which trees
    // are cached.
    /**
     * @serial
     */
    private String m_styleURLOfCached = null;
  
    /**
     * @serial
     */
    private String m_documentURLOfCached = null;
  
    /**
     * I save this for use on the worker thread, but i don't think I
     * need to do this.
     * @serial
     */
    private URL m_codeBase = null;
    private URL m_documentBase = null;
  
    private Templates m_styleTree = null;
  
    /**
     * Thread stuff for the trusted worker thread.
     */
    transient private Thread m_callThread = null;
  
    /**
     */
    transient private TrustedAgent m_trustedAgent = null;
  
    /**
     */
    transient private Thread m_trustedWorker = null;
  
    /**
     * Where the worker thread puts the HTML text.
     */
    transient private String m_htmlText = null;
  
    /**
     * Stylesheet attribute name and value that the caller can set.
     */
    transient private String m_nameOfIDAttrOfElemToModify = null;
  
    /**
     */
    transient private String m_elemIdToModify = null;
  
    /**
     */
    transient private String m_attrNameToSet = null;
  
    /**
     */
    transient private String m_attrValueToSet = null;
  
    /**
     * The XSLTProcessorApplet constructor takes no arguments.
     */
    public XSLTProcessorApplet()
    {
    }
  
    /**
     * Get basic information about the applet
     * @return A String with the applet name and author.
     */
    public String getAppletInfo()
    {
      return "Name: XSLTProcessorApplet\r\n" +
        "Author: Scott Boag";
    }
  
    /**
     * Get descriptions of the applet parameters.
     * @return A two-dimensional array of Strings with Name, Type, and 
Description
     * for each parameter.
     */
    public String[][] getParameterInfo()
    {
      String[][] info =
      {
        { PARAM_styleURL, "String", "URL to a XSL style sheet" },
        { PARAM_documentURL, "String", "URL to a XML document" },
        { PARAM_parser, "String", "Which parser to use: XML4J or ANY" },
      };
      return info;
    }
  
    /**
     * Standard applet initialization.
     */
    public void init()
    {
      // PARAMETER SUPPORT
      //                The following code retrieves the value of each parameter
      // specified with the <PARAM> tag and stores it in a member
      // variable.
      //----------------------------------------------------------------------
      String param;
      param = getParameter(PARAM_parser);
      whichParser = (param != null) ? param : "ANY";
  
      // styleURL: Parameter description
      //----------------------------------------------------------------------
      param = getParameter(PARAM_styleURL);
      if (param != null)
        setStyleURL(param);
      // documentURL: Parameter description
      //----------------------------------------------------------------------
      param = getParameter(PARAM_documentURL);
      if (param != null)
        setDocumentURL(param);
      m_codeBase = this.getCodeBase();
      m_documentBase = this.getDocumentBase();
  
      // If you use a ResourceWizard-generated "control creator" class to
      // arrange controls in your applet, you may want to call its
      // CreateControls() method from within this method. Remove the following
      // call to resize() before adding the call to CreateControls();
      // CreateControls() does its own resizing.
      //----------------------------------------------------------------------
      resize(320, 240);
  
      initLiaison();
  
    }
  
    /**
     * Try to init the XML liaison object: currently not implemented.
     */
    protected void initLiaison()
    {
      try
      {
        m_processor = Processor.newInstance("xslt");
      }
      catch(org.xml.sax.SAXException se)
      {
        se.printStackTrace();
        throw new RuntimeException(se.getMessage());
      }
  
    }
  
    /**
     * Cleanup; called when applet is terminated and unloaded.
     */
    public void destroy()
    {
      if(null != m_trustedWorker)
      {
        m_trustedWorker.stop();
        // m_trustedWorker.destroy();
        m_trustedWorker = null;
      }
      m_styleURLOfCached = null;
      m_documentURLOfCached = null;
    }
  
    /**
     * Do not call; this applet contains no UI or visual components.
     */
  
    public void paint(Graphics g)
    {
    }
   
    /**
     *  Automatically called when the HTML client containing the applet loads.
     *  This method starts execution of the applet thread.
     */
    public void start()
    {
      m_trustedAgent = new TrustedAgent();
      Thread currentThread = Thread.currentThread();
      m_trustedWorker = new Thread(currentThread.getThreadGroup(), 
m_trustedAgent);
      m_trustedWorker.start();
      try
      {
        this.showStatus("Causing Xalan and XML4J to Load and JIT...");
        // Prime the pump so that subsequent transforms don't look so slow.
        StringReader xmlbuf = new StringReader("<?xml version='1.0'?><foo/>");
        StringReader xslbuf = new StringReader("<?xml 
version='1.0'?><xsl:stylesheet 
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:template 
match='foo'><out/></xsl:template></xsl:stylesheet>");
        PrintWriter pw = new PrintWriter(new StringWriter());
        synchronized(m_processor)
        {
          Templates templates = m_processor.process(new InputSource(xslbuf));
          Transformer transformer = templates.newTransformer();
          transformer.transform(new InputSource(xmlbuf), new Result(pw));
          this.showStatus("PRIMED the pump!");
        }
        // System.out.println("Primed the pump!");
        this.showStatus("Ready to click!");
      }
      catch(Exception e)
      {
        this.showStatus("Could not prime the pump!");
        System.out.println("Could not prime the pump!");
        e.printStackTrace();
      }
    }
  
    /**
     * Automatically called when the HTML page containing the applet is no 
longer
     * on the screen. Stops execution of the applet thread.
     */
    public void stop()
    {
      if(null != m_trustedWorker)
      {
        m_trustedWorker.stop();
        // m_trustedWorker.destroy();
        m_trustedWorker = null;
      }
      m_styleURLOfCached = null;
      m_documentURLOfCached = null;
    }
  
    /**
     * Set the URL to the XSL stylesheet that will be used
     * to transform the input XML.  No processing is done yet.
     * @param valid URL string.
     */
    public void setStyleURL(String urlString)
    {
      m_styleURL =urlString;
    }
  
    /**
     * Set the URL to the XML document that will be transformed
     * with the XSL stylesheet.  No processing is done yet.
     * @param valid URL string.
     */
    public void setDocumentURL(String urlString)
    {
      m_documentURL = urlString;
    }
  
    /**
     * The processor keeps a cache of the source and
     * style trees, so call this method if they have changed
     * or you want to do garbage collection.
     */
    public void freeCache()
    {
      m_styleURLOfCached = null;
      m_documentURLOfCached = null;
    }
  
    /**
     * Set an attribute in the stylesheet, which gives the ability
     * to have some dynamic selection control.
     * @param nameOfIDAttrOfElemToModify The name of an attribute to search for 
a unique id.
     * @param elemId The unique ID to look for.
     * @param attrName Once the element is found, the name of the attribute to 
set.
     * @param value The value to set the attribute to.
     */
    public void setStyleSheetAttribute(String nameOfIDAttrOfElemToModify,
                                       String elemId,
                                       String attrName,
                                       String value)
    {
      m_nameOfIDAttrOfElemToModify = nameOfIDAttrOfElemToModify;
      m_elemIdToModify = elemId;
      m_attrNameToSet = attrName;
      m_attrValueToSet = value;
    }
  
    transient String m_key;
    transient String m_expression;
  
    /**
     * Submit a stylesheet parameter.
     * @param expr The parameter expression to be submitted.
     * @see org.apache.xalan.xslt.Processor#setStylesheetParam(String, String)
     */
    public void setStylesheetParam(String key, String expr)
    {
      m_key = key;
      m_expression = expr;
    }
  
    /**
     * Given a String containing markup, escape the markup so it
     * can be displayed in the browser.
     */
    public String escapeString(String s)
    {
      StringBuffer sb = new StringBuffer();
      int length = s.length();
  
      for (int i = 0;  i < length;  i ++)
      {
        char ch = s.charAt(i);
        if ('<' == ch)
        {
          sb.append("&lt;");
        }
        else if ('>' == ch)
        {
          sb.append("&gt;");
        }
        else if ('&' == ch)
        {
          sb.append("&amp;");
        }
        else if (0xd800 <= ch && ch < 0xdc00)
        {
          // UTF-16 surrogate
          int next;
          if (i+1 >= length)
          {
            throw new 
RuntimeException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_UTF16_SURROGATE,
 new Object[]{Integer.toHexString(ch)}));//"Invalid UTF-16 surrogate detected: "
              //+Integer.toHexString(ch)+ " ?");
          }
          else
          {
            next = s.charAt(++i);
            if (!(0xdc00 <= next && next < 0xe000))
              throw new 
RuntimeException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_UTF16_SURROGATE,
 new Object[]{Integer.toHexString(ch)+" 
"+Integer.toHexString(next)}));//"Invalid UTF-16 surrogate detected: "
                //+Integer.toHexString(ch)+" "+Integer.toHexString(next));
            next = ((ch-0xd800)<<10)+next-0xdc00+0x00010000;
          }
          sb.append("&#x");
          sb.append(Integer.toHexString(next));
          sb.append(";");
        }
        else
        {
          sb.append(ch);
        }
      }
      return sb.toString();
    }
  
  
    /**
     * Assuming the stylesheet URL and the input XML URL have been set,
     * perform the transformation and return the result as a String.
     */
    public String getHtmlText()
    {
      m_trustedAgent.m_getData = true;
      m_callThread = Thread.currentThread();
      try
      {
        synchronized(m_callThread)
        {
          m_callThread.wait();
        }
      }
      catch(InterruptedException ie)
      {
        System.out.println(ie.getMessage());
      }
      return m_htmlText;
    }
  
    /**
     * Get a DOM tree as escaped text, suitable for display
     * in the browser.
     */
    public String getTreeAsText(String treeURL)
      throws IOException
    {
      String text = "";
      byte[] buffer = new byte[50000];
  
      try
                {
        URL docURL = new URL(m_documentBase, treeURL);
        InputStream in = docURL.openStream();
  
                        int nun_chars;
                        while ( ( nun_chars = in.read( buffer, 0, buffer.length 
) ) != -1 )
                        {
                                text = text + new String( buffer, 0, nun_chars 
);
                        }
                        in.close();
                }
                catch ( Exception any_error )
      {any_error.printStackTrace();}
      return text;
    }
  
    /**
     * Get the XML source Tree as a text string suitable
     * for display in a browser.  Note that this is for display of the
     * XML itself, not for rendering of HTML by the browser.
     * @exception Exception thrown if tree can not be converted.
     */
    public String getSourceTreeAsText()
      throws Exception
    {
      return getTreeAsText(m_documentURL);
    }
  
    /**
     * Get the XSL style Tree as a text string suitable
     * for display in a browser.  Note that this is for display of the
     * XML itself, not for rendering of HTML by the browser.
     * @exception Exception thrown if tree can not be converted.
     */
    public String getStyleTreeAsText()
      throws Exception
    {
      return getTreeAsText(m_styleURL);
    }
  
    /**
     * Get the HTML result Tree as a text string suitable
     * for display in a browser.  Note that this is for display of the
     * XML itself, not for rendering of HTML by the browser.
     * @exception Exception thrown if tree can not be converted.
     */
    public String getResultTreeAsText()
      throws Exception
    {
      return escapeString(getHtmlText());
    }
  
    /**
     * Process a document and a stylesheet and return
     * the transformation result.  If one of these is null, the
     * existing value (of a previous transformation) is not affected.
     */
    public String transformToHtml(String doc, String style)
    {
      if(null != doc)
      {
        m_documentURL = doc;
      }
      if(null != style)
      {
        m_styleURL = style;
      }
      return getHtmlText();
    }
  
    /**
     * Process a document and a stylesheet and return
     * the transformation result. Use the xsl:stylesheet PI to find the
     * document, if one exists.
     */
    public String transformToHtml(String doc)
    {
      if(null != doc)
      {
        m_documentURL = doc;
      }
      m_styleURL = null;
      return getHtmlText();
    }
  
    /**
     * Do the real transformation after the right XML processor
     * liason has been found.
     */
    private String doTransformation(Processor processor)
      throws SAXException
    {
      URL documentURL = null;
      URL styleURL = null;
      StringWriter osw = new StringWriter();
      PrintWriter pw = new PrintWriter(osw, false);
  
      // xmlProcessorLiaison.SaveXMLToFile(m_resultTree, pw);
  
      this.showStatus("Begin Transformation...");
      try
      {
        documentURL = new URL(m_codeBase, m_documentURL);
        InputSource xmlSource = new InputSource(documentURL.toString());
  
        styleURL = new URL(m_codeBase, m_styleURL);
        InputSource xslSource = new InputSource(styleURL.toString());
        
        m_styleTree =  m_processor.process(xslSource);
  
        Transformer transformer = m_styleTree.newTransformer();
        if(null != m_key)
          transformer.setParameter(m_key, null, m_expression);
  
        transformer.transform(xmlSource, new Result(pw));
      }
      catch(MalformedURLException e)
      {
        e.printStackTrace();
        System.exit(-1);
      }
      catch(IOException e)
      {
        e.printStackTrace();
        System.exit(-1);
      }
      this.showStatus("Transformation Done!");
  
      String htmlData = osw.toString();
  
      return htmlData;
    }
  
    /**
     * Process the transformation.
     */
    private String processTransformation()
      throws SAXException
  {
    String htmlData = null;
    try
      {
        if(whichParser.trim().equals("XML4J") || 
whichParser.trim().equals("ANY"))
        {
          this.showStatus("Waiting for Xalan and XML4J to finish loading and 
JITing...");
          synchronized(m_processor)
          {
            // TransformerImpl processor = new XSLProcessor(m_liaison);
            htmlData = doTransformation(m_processor);
          }
        }
        else
        {
            System.out.println("XSLTProcessorApplet only works with XML4J at 
the moment!");
        }
      }
      catch(NoClassDefFoundError e)
      {
        System.out.println("Can not find "+whichParser+" XML Processor!!");
      }
      return htmlData;
    }
  
    /**
     * This class maintains a worker thread that that is
     * trusted and can do things like access data.  You need
     * this because the thread that is called by the browser
     * is not trusted and can't access data from the URLs.
     */
    class TrustedAgent implements Runnable
    {
      public boolean m_getData = false;
      public void run()
      {
        while(true)
        {
          m_trustedWorker.yield();
          if(m_getData)
          {
            try
            {
              m_getData = false;
              m_htmlText = null;
              m_htmlText = processTransformation();
            }
            catch(Exception e)
            {
              e.printStackTrace();
            }
            finally
            {
              synchronized(m_callThread)
              {
                m_callThread.notify();
              }
  
            }
          }
          else
          {
            try
            {
              m_trustedWorker.sleep(50);
            }
            catch (InterruptedException ie)
            {
              ie.printStackTrace();
            }
          }
        }
      }
    }
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/dtm/ChunkedIntArray.java
  
  Index: ChunkedIntArray.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
   
  import org.w3c.dom.*;
  
  import org.xml.sax.HandlerBase;
  import org.xml.sax.AttributeList;
  
  /**
   * <code>ChunkedIntArray</code> is an extensible array of blocks of integers.
   * (I'd consider Vector, but it's unable to handle integers except by
   * turning them into Objects.)
   * <P>
   * Making this a separate class means some call-and-return overhead. But
   * doing it all inline tends to be fragile and expensive in coder time,
   * not to mention driving up code size. If you want to inline it, feel free.
   * The Java text suggest that private and Final methods may be inlined, 
   * and one can argue that this beast need not be made subclassable...
   */
  final class ChunkedIntArray
    extends org.xml.sax.HandlerBase
  {
    final int slotsize=4; // Locked, MUST be power of two in current code
    // Debugging tip: Cranking lowbits down to 4 or so is a good
    // way to pound on the array addressing code.
    static final int lowbits=10; // How many bits address within chunks
    static final int chunkalloc=1<<lowbits;
    static final int lowmask=chunkalloc-1;
    
    ChunksVector chunks=new ChunksVector();
    final int fastArray[] = new int[chunkalloc];
    int lastUsed=0;
  
    /**
     * Create a new CIA with specified record size. Currently record size MUST
     * be a power of two... and in fact is hardcoded to 4.
     */
    ChunkedIntArray(int slotsize)
    {
      if(this.slotsize<slotsize)
        throw new ArrayIndexOutOfBoundsException("ChunkedIntArray("+slotsize+") 
not currently supported");
      else if (this.slotsize>slotsize)
        System.out.println("*****WARNING: ChunkedIntArray("+slotsize+") wasting 
"+(this.slotsize-slotsize)+" words per slot");
      chunks.addElement(fastArray);
    }
    /**
     * Append a 4-integer record to the CIA, starting with record 1. (Since
     * arrays are initialized to all-0, 0 has been reserved as the "unknown"
     * value in DTM.)
     * @return the index at which this record was inserted.
     */
    int appendSlot(int w0, int w1, int w2, int w3)
    {
      /*
      try
      {
        int newoffset = (lastUsed+1)*slotsize;
        fastArray[newoffset] = w0;
        fastArray[newoffset+1] = w1;
        fastArray[newoffset+2] = w2;
        fastArray[newoffset+3] = w3;
        return ++lastUsed;
      }
      catch(ArrayIndexOutOfBoundsException aioobe)
      */
      {
        final int slotsize=4;
        int newoffset = (lastUsed+1)*slotsize;
        int chunkpos = newoffset >> lowbits;
        int slotpos = (newoffset & lowmask);
  
        // Grow if needed
        if (chunkpos > chunks.size() - 1)
          chunks.addElement(new int[chunkalloc]);
        int[] chunk = chunks.elementAt(chunkpos);
        chunk[slotpos] = w0;
        chunk[slotpos+1] = w1;
        chunk[slotpos+2] = w2;
        chunk[slotpos+3] = w3;
  
        return ++lastUsed;
      }
    }
    /**
     * Retrieve an integer from the CIA by record number and column within
     * the record, both 0-based (though position 0 is reserved for special
     * purposes).
     * @param position int Record number
     * @param slotpos int Column number
     */
    int readEntry(int position, int offset) throws 
ArrayIndexOutOfBoundsException
    {
      /*
      try
      {
        return fastArray[(position*slotsize)+offset];
      }
      catch(ArrayIndexOutOfBoundsException aioobe)
      */
      {
        // System.out.println("Using slow read (1)");
        if (offset>=slotsize)
          throw new ArrayIndexOutOfBoundsException("Offset bigger than slot");
        position*=slotsize;
        int chunkpos = position >> lowbits;
        int slotpos = position & lowmask;
        int[] chunk = chunks.elementAt(chunkpos);
        return chunk[slotpos + offset];
      }
    }
    
    int specialFind(int startPos, int position)
    {
          // We have to look all the way up the ancestor chain
          // to make sure we don't have an ancestor.
          int ancestor = startPos;
          while(ancestor > 0)
          {
                ancestor*=slotsize;
                int chunkpos = ancestor >> lowbits;
                int slotpos = ancestor & lowmask;
                int[] chunk = chunks.elementAt(chunkpos);
                                                        
                ancestor = chunk[slotpos + 1];
                  
                if(ancestor == position)
                         break;
          }
  
          if (ancestor <= 0) 
          {
                  return position;
          }
          return -1;
    }
    
    /**
     * @return int index of highest-numbered record currently in use
     */
    int slotsUsed()
    {
      return lastUsed;
    }
  
    /** Disard the highest-numbered record. This is used in the string-buffer
     CIA; when only a single characters() chunk has been recieved, its index
     is moved into the Text node rather than being referenced by indirection
     into the text accumulator.
     */
    void discardLast()
    {
      --lastUsed;
    }
  
    /**
     * Overwrite the integer found at a specific record and column.
     * Used to back-patch existing records, most often changing their
     * "next sibling" reference from 0 (unknown) to something meaningful
     * @param position int Record number
     * @param offset int Column number
     * @param value int New contents
     */
    void writeEntry(int position, int offset, int value) throws 
ArrayIndexOutOfBoundsException
    {
      /*
      try
      {
        fastArray[( position*slotsize)+offset] = value;
      }
      catch(ArrayIndexOutOfBoundsException aioobe)
      */
      {
        if (offset >= slotsize)
          throw new ArrayIndexOutOfBoundsException("Offset bigger than slot");
        position*=slotsize;
        int chunkpos = position >> lowbits;
        int slotpos = position & lowmask;
        int[] chunk = chunks.elementAt(chunkpos);
        chunk[slotpos + offset] = value; // ATOMIC!
      }
    }
  
    /**
     * Overwrite an entire (4-integer) record at the specified index.
     * Mostly used to create record 0, the Document node.
     * @param position integer Record number
     * @param w0 int 
     * @param w1 int
     * @param w2 int
     * @param w3 int
     */
    void writeSlot(int position, int w0, int w1, int w2, int w3)
    {
      int chunkpos = position >> lowbits;
      int slotpos = (position & lowmask) * slotsize;
  
      // Grow if needed
      if (chunkpos > chunks.size() - 1)
        chunks.addElement(new int[chunkalloc]);
      int[] chunk = chunks.elementAt(chunkpos);
      chunk[slotpos] = w0;
      chunk[slotpos + 1] = w1;
      chunk[slotpos + 2] = w2;
      chunk[slotpos + 3] = w3;
    }
  
    /**
     * Retrieve the contents of a record into a user-supplied buffer array.
     * Used to reduce addressing overhead when code will access several
     * columns of the record.
     * @param position int Record number
     * @param buffer int[] Integer array provided by user, must be large enough
     * to hold a complete record.
     */
    void readSlot(int position, int[] buffer)
    {
      /*
      try
      {
        System.arraycopy(fastArray, position*slotsize, buffer, 0, slotsize);
      }
      catch(ArrayIndexOutOfBoundsException aioobe)
      */
      {
        // System.out.println("Using slow read (2): "+position);
        position *= slotsize;
        int chunkpos = position >> lowbits;
        int slotpos = (position & lowmask);
  
        // Grow if needed
        if (chunkpos > chunks.size() - 1)
          chunks.addElement(new int[chunkalloc]);
        int[] chunk = chunks.elementAt(chunkpos);
        System.arraycopy(chunk,slotpos,buffer,0,slotsize);
      }
    }
  
    class ChunksVector
    {
      final int BLOCKSIZE = 64;
      int[] m_map[] = new int[BLOCKSIZE][];
      int m_mapSize = BLOCKSIZE;
      int pos = 0;
      
      ChunksVector()
      {
      }
      
      final int size()
      {
        return pos;
      }
      
      void addElement(int[] value)
      {
        if(pos >= m_mapSize)
        {
          int orgMapSize = m_mapSize;
          while(pos >= m_mapSize)
            m_mapSize+=BLOCKSIZE;
          int[] newMap[] = new int[m_mapSize][];
          System.arraycopy(m_map, 0, newMap, 0, orgMapSize);
          m_map = newMap;
        }
        // For now, just do a simple append.  A sorted insert only 
        // makes sense if we're doing an binary search or some such.
        m_map[pos] = value;
        pos++;
      }
      
      final int[] elementAt(int pos)
      {
        return m_map[pos];
      }
    }
  }
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/dtm/DTM.java
  
  Index: DTM.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
   
  import org.w3c.dom.*;
  import java.util.Vector;
  import java.util.Hashtable;
  import org.xml.sax.HandlerBase;
  import org.xml.sax.AttributeList;
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  import org.xml.sax.SAXParseException;
  import org.xml.sax.SAXNotRecognizedException;
  import org.xml.sax.SAXNotSupportedException;
  import java.io.IOException;
  
  import org.apache.xalan.utils.StringToStringTable;
  import org.apache.xalan.utils.StringVector;
  import org.apache.xalan.utils.StringToStringTableVector;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  import org.apache.xerces.readers.XMLEntityHandler;
  import org.apache.xerces.dom.DocumentTypeImpl;
  import org.apache.xerces.dom.ElementDefinitionImpl;
  import org.apache.xerces.dom.EntityImpl;
  import org.apache.xerces.framework.XMLDocumentHandler;
  import org.apache.xerces.framework.XMLContentSpec;
  import org.apache.xerces.utils.QName;
  import org.apache.xerces.framework.XMLAttrList;
  
  /**
   * <meta name="usage" content="internal"/>
   * <code>DTM</code> is an XML document model expressed as a table rather than
   * an object tree. It attempts to be very compact, and to support very
   * specifically limited multitasking: users can start reading the document
   * while it's still being generated.  (A work in progress...)
   * <p>
   * (***** The SAX handler calls, and the string-based XMLContentHandler
   * methods, are known to be bad; they're included as hooks for the 
future.)</p>
   * <p>
   * DTM does _not_ directly support the W3C's Document Object Model. However,
   * it attempts to come close enough that a subset of DOM behavior can be
   * implemented as proxy objects referencing the DTM.</p>
   * @see DTMProxy
   */
  public class DTM 
    extends org.apache.xerces.framework.XMLParser implements Runnable,
    XMLDocumentHandler, XMLDocumentHandler.DTDHandler
  {
    // COMPILATION CONTROL: Debugging features
    final boolean DISABLE = false;
    final boolean DEBUG = false;
    final boolean DEBUG_WAITS = false;
    final boolean TRACE = false;
  
    private boolean fCreateEntityReferenceNodes = true;
    
    // DTM state information
    // org.xml.sax.Parser parser;
    // org.apache.xalan.dtm.HookedXMLParser ibmparser;
    // org.apache.xerces.utils.StringPool fStringPool;
    ChunkedIntArray nodes = new ChunkedIntArray(4);
    
    /**
     * Make the string public.
     */
    public org.apache.xerces.utils.StringPool getStringPool() { return 
fStringPool; }
  
    // Context for parse-and-append operations
    int currentParent = 0;
    int previousSibling = 0;
    private boolean XML4J=false;
    private boolean processingIgnorableWhitespace = false;
    private boolean processingCDATASection = false;
    private boolean previousSiblingWasParent = false;
    // Local cache for record-at-a-time fetch
    int gotslot[] = new int[4];
  
    // Unique-string-to-integer conversions, for use with SAX.
    // (The XMLContentHandler interface patches back into XML4J's
    // symbol tables instead */
    Hashtable symbolTable = new Hashtable();
    Vector symbolList=new Vector();
  
    // MANEFEST CONSTANTS
    // Status bits, ORed with node type (assumed to be <256, should be safe)
    final int TEXT_IGNORABLE = 2 << 8;
    final int TEXT_CDATA = 4 << 8;
    
    // Impossible prefix to look up the default namespace
    public static final String DEFAULT_PREFIX_STR = "#:::";
  
    // Handshaking for updates of simul read/write
    final int UPDATE_FREQUENCY=10;
    int update_counter=UPDATE_FREQUENCY;
    // endDocument recieved?
    private boolean done = false;
    
    DTMProxy document;
    
    boolean m_isError = false;
    
    protected int fAmpIndex;
    protected int fLtIndex;
    protected int fGtIndex;
    protected int fAposIndex;
    protected int fQuotIndex;
    
    ChunkedIntArray m_entityNodes = null;
    IntMap m_entities = new IntMap();
    
    IntToObjectMap m_elementDecls = new IntToObjectMap();
    
    IntMap m_idMap = new IntMap();
    
    /**
     * Namespace lookup. This is actually a stack of StringToStringTables
     */
    StringToStringTableVector namespaceTable = new 
StringToStringTableVector(64);
    
    /**
     * Default empty namespace
     */
    private StringToStringTable m_emptyNamespace = new StringToStringTable();
    
    // This needs to be set before calling run()
    private InputSource m_inputSource = null;
    
    public void setInputSource(InputSource inputSource)
    {
      m_inputSource = inputSource;
    }
    
    /**
     * Construct a DTM.
     * This is the only constructor currently working.
     * @param parser HookedXMLParser Input event-stream source.
     */
    public DTM()
    {
      super();
      
      initHandlers(false, this, this);
    }
  
    /** Returns the XML Schema validator. */
    /*
    protected org.apache.xerces.validators.schema.XSchemaValidator 
getSchemaValidator() 
    {
      if (fSchemaValidator == null)
        fSchemaValidator = new NullSchemaValidator(fStringPool, fErrorReporter, 
fEntityHandler);
      return fSchemaValidator;
    }
    */
    
    boolean m_throwNewError = true;
  
    
    /**
     * Run the parse thread.
     */
    public void run()
    {
      try
      {
        m_throwNewError = true;
        parse(m_inputSource);
      }
      catch(Exception e)
      {
        ; // should have already been reported via the error handler?
      }
    }
    
    
    // For now, just have an array of references.  This can 
    // later be changed to some sort of pool... maybe.
    DTMNodeVector m_proxies = new DTMNodeVector();
    
    /**
     * Return a Node object that represents the index.
     */
    public final DTMProxy getNode(int pos)
    {
      if(true)
      {
        // Create a new node every time...
        if(0 == pos)
        {
          if(null == document)
            document = new DTMProxy(this, pos, Node.DOCUMENT_NODE);
          return document;
        }
        return new DTMProxy(this, pos);
      }
      else
      {
        // cache the objects in an array...
        DTMProxy proxy = m_proxies.get(pos);
        if(null == proxy)
        {
          proxy = new DTMProxy(this, pos);
          m_proxies.put(pos, proxy);
        }
        
        // For now...
        return proxy;
      }
    }
  
    /**
     * Wrapper for ChunkedIntArray.append, to automatically update the
     * previous sibling's "next" reference (if necessary) and periodically
     * wake a reader who may have encountered incomplete data and entered
     * a wait state.
     * @param w0 int As in ChunkedIntArray.append
     * @param w1 int As in ChunkedIntArray.append
     * @param w2 int As in ChunkedIntArray.append
     * @param w3 int As in ChunkedIntArray.append
     * @return int As in ChunkedIntArray.append
     * @see ChunkedIntArray.append
     */
    private final int appendNode(int w0, int w1, int w2, int w3)
    {
      // A decent compiler will probably inline this.
      int slotnumber = nodes.appendSlot(w0, w1, w2, w3);
  
      if(DEBUG) System.out.println(slotnumber+": "+w0+" "+w1+" "+w2+" "+w3);
      
      if(previousSiblingWasParent)
        nodes.writeEntry(previousSibling,2,slotnumber);
  
      previousSiblingWasParent = false; // Set the default; endElement overrides
  
      if (--update_counter == 0)
        synchronized (this)
        {
          update_counter=UPDATE_FREQUENCY;
          notifyAll();
        }
      
      return slotnumber;
    }
    
    //==========================================================
    // SECTION: ContentHandler
    //==========================================================
    private final void ____ContentHandler____(){}
  
    /**
     * XMLContentHandler API: Start-of-document recieved.
     * Much like the SAX startDocument() and setDocumentLocator() calls,
     * but also has the side effect of switching DTM into its XML4J-aware
     * mode.
     */
    public final void startDocument() 
    {
      XML4J = true;
      // Initialize the doc -- no parent, no next-sib
      nodes.writeSlot(0,Node.DOCUMENT_NODE,-1,-1,0);
      document = getNode(0);
      // Make sure nobody is still waiting
      synchronized (this)
      {
        if(DEBUG_WAITS)
          System.out.println("startDocument(1): "+document);
        notify();
      }
    }
    
    /**
     ** SAX API: End of Document reached. 
     * Finalize the DTM: close out the sibling chain, mark the document as
     * no-more-nodes-expected, and wake up anyone who is waiting.
     * @exception org.xml.sax.SAXException Not used.
     */
    public final void endDocument() 
      throws org.xml.sax.SAXException
    {
      if(DISABLE)return;
  
      done=true;
      
      // Fix up "next" of last Element, if needed
      if(previousSiblingWasParent)
        nodes.writeEntry(previousSibling,2,-1);
  
      // Make sure nobody is still waiting
      synchronized (this)
      {
        // if(DEBUG_WAITS)
        //  System.out.println("endDocument");
        notifyAll();
      }
    }
  
    /**
     * XMLContentHandler API: Process element start-tag and its attributes.
     * This includes pushing a new namespace context (with any
     * namespaces declared on this element), creating the Element
     * node, making it the new parent, and creating child Attribute
     * nodes as needed. Namespace declarations _do_ appear as
     * attributes. Attributes are expressed as the leading children
     * of the Element, and are separated out later, which is different
     * from DOM's behavior.
     * <p>
     * The mapping from namespace prefixes to namespace URIs is also performed
     * at this time.
     * @param elementNameIndex int Index of element's qualified name in
     * symbol table.
     * @param attrListIndex int Starting index of this element's attributes
     * in the parser's attribute table, or -1 to indicate no attributes.
     */
    public final void startElement(QName qname,
                             XMLAttrList xmlAttrList, 
                             int attrListIndex) 
    {
      if(DISABLE)return;    
      // Need to retrive the attrList...
          
      String attrname, attrvalue;
  
      // Push a new namespace context
  
      StringToStringTable pushNS=m_emptyNamespace;
      
      // Process any new namespace declarations
      if(attrListIndex!=-1)
      {
        for (int index = xmlAttrList.getFirstAttr(attrListIndex);
             index != -1;
             index = xmlAttrList.getNextAttr(index))
        {
          attrname = fStringPool.toString(xmlAttrList.getAttrName(index));
          if (attrname.startsWith("xmlns:"))
          {
            // XML4J very politely offers to stringify this for us
            attrvalue = fStringPool.toString(xmlAttrList.getAttValue(index));
            String nsprefix = attrname.substring(6);
            if(m_emptyNamespace == pushNS)
              pushNS = new StringToStringTable();
            pushNS.put(nsprefix,attrvalue);
          }
          else if(attrname.equals("xmlns"))
          {
            attrvalue = fStringPool.toString(xmlAttrList.getAttValue(index));
            if(m_emptyNamespace == pushNS)
              pushNS = new StringToStringTable();
            pushNS.put(DEFAULT_PREFIX_STR,attrvalue);
          }
        }
      }
      namespaceTable.addElement(pushNS);
      
      // Scope some stuff...
      int ourslot;
      {
        // W0 Low: Node Type.
        // W0 High: Namespace
        int w0 = org.w3c.dom.Node.ELEMENT_NODE | (qname.uri << 16);
        // W1: Parent
        int w1 = currentParent;
        // W2: Next. Initialize as 0 (unresolved)
        int w2 = 0;
        // W3: Tagname
        int w3 = qname.rawname;
  
        // Add this element to the document
        ourslot = appendNode(w0, w1, w2, w3);
        
      }
      // Change append context
      currentParent = ourslot;
      
      previousSibling = 0;
      
      IntMap elemMap = (IntMap)m_elementDecls.get(qname.rawname);
  
      // Append the attributes
      if(attrListIndex!=-1)
      {
        for (int index = xmlAttrList.getFirstAttr(attrListIndex);
             index != -1;
             index = xmlAttrList.getNextAttr(index))
        {
          // W0 Low: Node Type.
          // W0 High: Namespace
          int attrNameIndex = xmlAttrList.getAttrName(index);
          attrname=fStringPool.toString(attrNameIndex);
          
          if(null != elemMap)
          {
            int attrDecl = elemMap.get(attrNameIndex);
            if((attrDecl >> 16) == fStringPool.addSymbol("ID"))
            {
              // Apparently, attribute lists have their own string pool.
              int attrValIndex = xmlAttrList.getAttValue(index);
              // But then, I don't understand why this works.
              String valStr=fStringPool.toString(attrValIndex);
              int valIndex = fStringPool.addSymbol(valStr);
              m_idMap.put(valIndex, ourslot);
            }
          }
  
          int w0;
          int colonpos = attrname.indexOf(':');
          if(colonpos > 0)
          {
            String prefix = attrname.substring(0, colonpos);
            w0 = org.w3c.dom.Node.ATTRIBUTE_NODE | 
(stringToInt(resolveNamespace(prefix)) << 16);
          }
          else
          {
            w0 = org.w3c.dom.Node.ATTRIBUTE_NODE;
          }
          // W1: Parent
          int w1 = currentParent;
          // W2: Next (not yet resolved)
          int w2 = 0;
          // W3: Tagname
          int w3 = xmlAttrList.getAttrName(index);
  
          // Add this element to the document
          ourslot = appendNode(w0, w1, w2, w3);
          previousSibling=ourslot;
          
          // Create attribute substructure. 
          // ***** Current XML4J will _only_ yield a single text,
          //   rather than attempting to retain EntityReference nodes
          //   within Attribute values.
          // ***** DTMProxy currently assumes this behavior!
          // W0 Low: Node Type, with flag if ignorable whitespace
          // W0 High: Buffer index (in SAX mode) or 0 (XML4J mode)
          w0=org.w3c.dom.Node.TEXT_NODE;
          // W1: Parent
          w1 = ourslot;
          // W2: Start position within buffer (SAX), or text index (XML4J)
          w2 = xmlAttrList.getAttValue(index);
          // W3: Length of this text (SAX), or 0 (XML4J)
          w3 = 0;
          
          // *************************************************
          // ***********FIX BUG SOMEWHERE IN HERE*************
          // *************************************************
          
          // Do a "weak push" to make this first child
          // of the Attr node rather than its next-sib.
          previousSibling=0;
          appendNode(w0,w1,w2,w3);
          // Restore attr as the sib
          previousSibling=ourslot;                  
          
          // Attrs are Parents
          previousSiblingWasParent=true;
        }
      }
    }
    
    /**
     * XMLDocumentHandler API: End-tag reached. Pop the parentage context, along
     * with any namespaces this element defined. Make sure that the sibling 
chain
     * has been properly terminated.
     * @param name int Index of element name in XML4J's symbol table
     */
    public final void endElement(QName name)
    {
      if(DISABLE)return;    
      int thisElement = currentParent;
      
      // If last node appended before we pop has a next-sib reference,
      // (true of nodes which function as parents)
      // we need to switch that from 0 (unknown) to -1 (null)
      if (previousSibling != 0 & previousSiblingWasParent)
        nodes.writeEntry(previousSibling,2, -1);
  
      // Pop parentage
      nodes.readSlot(currentParent, gotslot);
      currentParent = gotslot[1];
  
      // The element just being finished will be
      // the previous sibling for the next operation
      previousSibling = thisElement;
      previousSiblingWasParent = true;
  
      // Pop a level of namespace table
      namespaceTable.removeLastElem();
    }
  
  
    /**
     * SAX API: Accept a chunk of characters for normalization into a Text
     * node. Note that since SAX may reuse its input buffers, we may need to
     * either extract the string now or cache a copy of the buffer. It is 
unclear
     * which approach is preferable
     * @param ch char[] Input buffer in which string can be found.
     * @param start int Offset to start of string, 0-based.
     * @param length int Length of string
     * @exception org.xml.sax.SAXException Required by API, not thrown as far
     * as I know.
     */
    public final void characters(char ch[], int start, int length) 
      throws org.xml.sax.SAXException
    {
      throw new 
SAXException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_SAX_API_NOT_HANDLED,
 null)); //"SAX API characters(char ch[]... not handled by the DTM!");
    }
  
    /**
     * XMLContentHandler API: Accept a chunk of characters for normalization 
     * into a Text node. This is an "enhanced SAX" flavor of the call, adding 
the
     * flag for CDATA sections, and is not currently used.
     * <p>
     * Note that since XML4J may reuse its input buffers, we may need to
     * either extract the string now or cache a copy of the buffer. It is 
unclear
     * which approach is preferable
     * @param ch char[] Input buffer in which string can be found.
     * @param start int Offset to start of string, 0-based.
     * @param length int Length of string
     * @param cdataSection boolean True iff text was enclosed in <![CDATA[ ]]>
     * @exception org.xml.sax.SAXException Required by API, not thrown as far
     * as I know.
     */
    public final void characters(char ch[], int start, int length, boolean 
cdataSection) 
      throws org.xml.sax.SAXException
    {
      // XML4J, currently not used
      // ***** Currently not recording distinction between CDATA
      // and text. Probably should, for model consistancy...?
      characters(ch,start,length);
    }
  
    /**
     * XMLContentHandler API: Accept a chunk of characters for normalization 
     * into a Text node. This is the "late binding" version of the call, which
     * we currently rely upon.
     * @param dataIndex int Index of this string in XML4J's symbol tables
     * @param cdataSection boolean True iff text was enclosed in <![CDATA[ ]]>
     * @exception org.xml.sax.SAXException Required by API, not thrown as far
     * as I know.
     */
    public final void characters(int dataIndex) 
      throws org.xml.sax.SAXException
    {
      if(DISABLE)return;
      general_characters(dataIndex);
    }
    
    /** Start CDATA section. */
    public final void startCDATA() throws Exception 
    {
    }
  
    /** End CDATA section. */
    public final void endCDATA() throws Exception 
    {
    }
    
    /** Ignorable whitespace. */
    public final void ignorableWhitespace(int dataIndex) 
      throws Exception 
    {
      general_characters(dataIndex);
    }
    
    /**
     * SAX API: Accept a chunk of characters for normalization into an
     * ignorable-whitespace Text
     * node. Note that since SAX may reuse its input buffers, we may need to
     * either extract the string now or cache a copy of the buffer. It is 
unclear
     * which approach is preferable
     * @param ch char[] Input buffer in which string can be found.
     * @param start int Offset to start of string, 0-based.
     * @param length int Length of string
     * @exception org.xml.sax.SAXException Required by API, not thrown as far
     * as I know.
     */
    public final void ignorableWhitespace(char ch[], int start, int length) 
      throws org.xml.sax.SAXException
    {
      throw new 
SAXException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_IGNORABLE_WHITESPACE_NOT_HANDLED,
 null)); //"ignorableWhitespace(char ch[]... not handled by the DTM!");
    }
    
    /**
     * XMLContentHandler API: Accept a chunk of characters for normalization 
     * into an ignorable-whitespace Text node. 
     * This is an "enhanced SAX" flavor of the call, adding the
     * flag for CDATA sections, and is not currently used.
     * <p>
     * Note that since XML4J may reuse its input buffers, we may need to
     * either extract the string now or cache a copy of the buffer. It is 
unclear
     * which approach is preferable
     * @param ch char[] Input buffer in which string can be found.
     * @param start int Offset to start of string, 0-based.
     * @param length int Length of string
     * @param cdataSection boolean True iff text was enclosed in <![CDATA[ ]]>
     * @exception org.xml.sax.SAXException Required by API, not thrown as far
     * as I know.
     */
    public final void ignorableWhitespace(char ch[], int start, int length, 
boolean cdataSection) 
      throws org.xml.sax.SAXException
    {
      throw new 
SAXException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_IGNORABLE_WHITESPACE_NOT_HANDLED,
 null)); //"ignorableWhitespace(char ch[]... not handled by the DTM!");
    }
    
    /**
     * XMLContentHandler API: Accept a chunk of characters for normalization 
     * into an ignorable-whitespace Text node. 
     * This is the "late binding" version of the call, which
     * we currently rely upon.
     * @param dataIndex int Index of this string in XML4J's symbol tables
     * @param cdataSection boolean True iff text was enclosed in <![CDATA[ ]]>
     * @exception org.xml.sax.SAXException Required by API, not thrown as far
     * as I know.
     */
    public final void ignorableWhitespace(int dataIndex, boolean cdataSection) 
      throws org.xml.sax.SAXException
    {
      processingIgnorableWhitespace = true;
      general_characters(dataIndex);
    }
  
    /** Text-accumulator operation for the integer-index version of
     * characters(). Obviously far simpler, since we are assured that
     * (unlike the parse buffers) the XML4J symbol table will persist.
     * @param index int Index of this string in XML4J's symbol tables.
     *<p>
     * KNOWN LIMITATION: DOESN'T PRESERVE CDATA FLAG.
     */
    public final void general_characters(int index) 
    {
      // Add this element to the document
      int w0 = Node.TEXT_NODE;
      // W1: Parent
      int w1 = currentParent;
      // W2: Start position within buffer (SAX), or text index (XML4J)
      int w2 = index;
      // W3: Length of this text (SAX), or 0 (XML4J)
      int w3 = gotslot[2];
      int ourslot = appendNode(w0, w1, w2, w3);
      previousSibling = ourslot;
    }
  
    /**
     * XMLContentHandler API: Create a Comment node. Available only in the
     * late-binding form, and not supported in SAX 1.0 at all.
     * @param dataIndex int Index of comment's contents in XML4J's symbol table
     */
    public final void comment(int dataIndex) 
    {
      if(DISABLE)return;
      
      // Short Form, XML4J mode
      int w0, w1, w2, w3;
      
      // W0 Low: Node Type, with flags
      // W0 High: Not used
      w0 = Node.COMMENT_NODE;
      // W1: Parent
      w1 = currentParent;
      // W2: Text number
      w2 = dataIndex;
      // W3: Length of this text TBD
      w3 = -1;
  
      // Add this element to the document
      int ourslot = appendNode(w0, w1, w2, w3);
      previousSibling = ourslot;
    }
    
    /**
     * XMLContentHandler API: Create a PI node.
     * @param target int target processor name index
     * @param data int Index of PI parameters to be passed to that processor
     */
    public final void processingInstruction(int target, int data) 
    {
      if(DISABLE)return;
      
      // W0 Low: Node Type.
      int w0 = org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE;
      // W1: Parent
      int w1 = currentParent;
      // W2: data
      int w2 = data;
      // W3: Target
      int w3 = target;
  
      // Add this element to the document
      int ourslot = appendNode(w0, w1, w2, w3);
  
      previousSibling = ourslot;
    }
  
    
    /** Report the start of the scope of a namespace declaration. */
    public final void startNamespaceDeclScope(int prefix, int uri) throws 
Exception 
    {
    }
  
    /** Report the end of the scope of a namespace declaration. */
    public final void endNamespaceDeclScope(int prefix) throws Exception 
    {
    }
    
    /** Report when the internal subset is completely scanned. */
    public final void internalSubset(int internalSubset)
    {
    }
    
    /** Start entity reference. */
    public final void startEntityReference(int entityName, int entityType,
                                     int entityContext) throws Exception 
    {
      /*
      if(null == m_entityNodes)
        initDefaultEntities();
  
      // are we ignoring entity reference nodes?
      if ((entityName == fAmpIndex) ||
          (entityName == fGtIndex) ||
          (entityName == fLtIndex) ||
          (entityName == fAposIndex) ||
          (entityName == fQuotIndex)) 
        // if(entityName > 0)
      {
        String str = fStringPool.toString(entityName);
  
        int entRef = m_entities.get(entityName);
        if(entRef >= 0)
        {
          int val = m_entityNodes.readEntry(entRef, 3);
          general_characters(val);
        }
        return;
      }
      */
  
    } // startEntityReference(int,int,int)
  
    /** End entity reference. */
    public final void endEntityReference(int entityName, int entityType,
                                   int entityContext) throws Exception 
    {
    } // endEntityReference(int,int,int)
    
    /**
       * Set the state of any feature in a SAX2 parser.  The parser
       * might not recognize the feature, and if it does recognize
       * it, it might not be able to fulfill the request.
       *
       * @param featureId The unique identifier (URI) of the feature.
       * @param state The requested state of the feature (true or false).
       *
       * @exception org.xml.sax.SAXNotRecognizedException If the
       *            requested feature is not known.
       * @exception org.xml.sax.SAXNotSupportedException If the
       *            requested feature is known, but the requested
       *            state is not supported.
       * @exception org.xml.sax.SAXException If there is any other
       *            problem fulfilling the request.
       */
      public void setFeature(String featureId, boolean state)
          throws SAXNotRecognizedException, SAXNotSupportedException
  
      {
         if (featureId.startsWith(XERCES_FEATURES_PREFIX)) 
         {
           String feature = 
featureId.substring(XERCES_FEATURES_PREFIX.length());
              
           //
           // http://apache.org/xml/features/dom/create-entity-ref-nodes
           //   This feature determines whether entity references within
           //   the document are included in the document tree as
           //   EntityReference nodes.
           //   Note: The children of the entity reference are always
           //         added to the document. This feature only affects
           //         whether an EntityReference node is also included
           //         as the parent of the entity reference children.
           //
           if (feature.equals("dom/create-entity-ref-nodes")) {
               setCreateEntityReferenceNodes(state);
             return;
           }
         }
         //
         // Pass request off to XMLParser for the common cases.
         //
         super.setFeature(featureId, state);
      }  
  
    //==========================================================
    // SECTION: DTD Handling
    //==========================================================
    private final void ____DTDHandling____(){}
    
    private final void initDefaultEntities()
    {
      fAmpIndex = fStringPool.addSymbol("amp");
      fLtIndex = fStringPool.addSymbol("lt");
      fGtIndex = fStringPool.addSymbol("gt");
      fAposIndex = fStringPool.addSymbol("apos");
      fQuotIndex = fStringPool.addSymbol("quot");
      
      try
      {
        m_entityNodes = new ChunkedIntArray(4);
        declareEntity(fAmpIndex, fStringPool.addSymbol("&"));
        declareEntity(fLtIndex, fStringPool.addSymbol("<"));
        declareEntity(fGtIndex, fStringPool.addSymbol(">"));
        declareEntity(fAposIndex, fStringPool.addSymbol("'"));
        declareEntity(fQuotIndex, fStringPool.addSymbol("\""));
      }
      catch(Exception e)
      {
      }
    }
  
    //
    // DTDValidator.EventHandler methods
    //
  
    /**
     *  This function will be called when a &lt;!DOCTYPE...&gt; declaration is
     *  encountered.
     */
    public final void startDTD(int rootElementType, int publicId, int systemId)
      throws Exception 
    {
      // String qualifiedName = fStringPool.toString(rootElementType);
      // String publicID = fStringPool.toString(publicId);
      // String systemID = fStringPool.toString(systemId);
      
      // fDocumentType = new org.apache.xerces.dom.DocumentTypeImpl(null, 
qualifiedName, publicID, systemID);
  
    } // startDTD(int,int,int)
  
    /**
     *  This function will be called at the end of the DTD.
     */
    public final void endDTD() throws Exception {}
  
    /**
     * callback for an element declaration. 
     *
     * @param elementType element handle of the element being declared
     * @param contentSpec contentSpec for the element being declared
     * @see org.apache.xerces.framework.XMLContentSpec
     * @exception java.lang.Exception
     */
    public void elementDecl(QName elementDecl, XMLContentSpec contentSpec) 
throws Exception
    {
    }
  
    /**
     * callback for an attribute list declaration. 
     *
     * @param elementType element handle for the attribute's element
     * @param attrName string pool index of the attribute name
     * @param attType type of attribute
     * @param enumString String representing the values of the enumeration,
     *        if the attribute is of enumerated type, or null if it is not.
     * @param attDefaultType an integer value denoting the DefaultDecl value
     * @param attDefaultValue string pool index of this attribute's default 
value 
     *        or -1 if there is no defaultvalue 
     * @exception java.lang.Exception
     */
    public void attlistDecl(QName elementDecl, QName attributeDecl,
                            int attType, String enumString,
                            int attDefaultType,
                            int attDefaultValue) throws Exception
    {
    }
    
    /**
     * callback for the start of the DTD
     * This function will be called when a &lt;!DOCTYPE...&gt; declaration is
     * encountered.
     *
     * @param rootElementType element handle for the root element of the 
document
     * @param publicId string pool index of the DTD's public ID
     * @param systemId string pool index of the DTD's system ID
     * @exception java.lang.Exception
     */
    public void startDTD(QName rootElement, int publicId, int systemId) throws 
Exception
    {
    }
  
    /**
     * &lt;!ELEMENT Name contentspec&gt;
     */
    public void elementDecl(QName elementDecl, 
                            int contentSpecType, 
                            int contentSpecIndex,
                            XMLContentSpec.Provider contentSpecProvider) 
      throws Exception
    {
    }
    
    /**
     * &lt;!ATTLIST Name AttDef&gt;
     */
    public void attlistDecl(QName elementDecl, QName attributeDecl,
                            int attType, boolean attList,
                            String enumString,
                            int attDefaultType,
                            int attDefaultValue) throws Exception
    {
    } // attlistDecl(int,int,int,String,int,int)
    
    /**
     * Get the element identified by the ID.
     */
    public final Element getIdentifier(String id)
    {
      int strIndex = fStringPool.addSymbol(id);
      int elemNum = m_idMap.get(strIndex);
      if(elemNum <= 0)
      {
        // Then we have to keep trying until it has arrived, or the end of 
        // the document is found.
        while((elemNum <= 0) && !done && !m_isError)
        {
          synchronized (this)
          {
            try
            {
              if(DEBUG_WAITS)
                System.out.println("Waiting... getIdentifier");
              wait();
            }
            catch (InterruptedException e)
            {
              // That's OK, it's as good a time as any to check again
            }
            elemNum = m_idMap.get(strIndex);
          }
        }
      }
      return (elemNum > 0) ? getNode(elemNum) : null;
    }
  
    /**
     * &lt;!ENTITY % Name EntityValue&gt; (internal)
     */
    public final void internalPEDecl(int entityName, int entityValue) throws 
Exception {}
  
    /**
     * &lt;!ENTITY % Name ExternalID>                (external)
     */
    public final void externalPEDecl(int entityName, int publicId, int 
systemId) throws Exception {}
    
    /**
     * Declare an entity.
     */
    private final void declareEntity(int entityName, int entityValue)
    {
      //if (!fCreateEntityReferenceNodes)
      //  return;
      
      int w0=org.w3c.dom.Node.ENTITY_NODE;
      // W1: Parent
      int w1 = 0;
      // W2: name index
      int w2 =  entityName;
      // W3: Not used
      int w3 = entityValue;
  
      int slotnumber = m_entityNodes.appendSlot(w0, w1, w2, w3);
      
      m_entities.put(entityName, slotnumber);
  
      // if (fDocumentType == null) return; //revist: should never happen. 
Exception?
  
      //revist: how to check if entity was already declared.
      // XML spec says that 1st Entity decl is binding.
  
      // Entity entity = 
fDocumentImpl.createEntity(fStringPool.toString(entityName));
      // fDocumentType.getEntities().setNamedItem(entity);
  
    } // internalEntityDecl(int,int)
  
    /**
     * &lt;!ENTITY Name EntityValue&gt; (internal)
     */
    public final void internalEntityDecl(int entityName, int entityValue)
      throws Exception 
    {
      if(null == m_entityNodes)
        initDefaultEntities();
  
      declareEntity(entityName, entityValue);
  
    } // internalEntityDecl(int,int)
    
  
    /**
     * &lt;!ENTITY Name ExternalID>                (external)
     */
    public final void externalEntityDecl(int entityName, int publicId, int 
systemId)
      throws Exception 
    {
      if(null == m_entityNodes)
        initDefaultEntities();
  
      int w0=org.w3c.dom.Node.ENTITY_NODE;
      // W1: Parent
      int w1 = 0;
      // W2: public id
      int w2 =  publicId;
      // W3: system id
      int w3 = systemId;
  
      int slotnumber = m_entityNodes.appendSlot(w0, w1, w2, w3);
      
      m_entities.put(entityName, slotnumber);
  
      //revist: how to check if entity was already declared.
      // XML spec says that 1st Entity decl is binding.
  
      // EntityImpl entity = 
(EntityImpl)fDocumentImpl.createEntity(fStringPool.toString(entityName));
      // entity.setPublicId(fStringPool.toString(publicId));
      // entity.setSystemId(fStringPool.toString(systemId));
      // fDocumentType.getEntities().setNamedItem(entity);
  
    } // externalEntityDecl(int,int,int)
  
    /**
     * &lt;!ENTITY Name ExternalID NDataDecl>      (unparsed)
     */
    public final void unparsedEntityDecl(int entityName,
                                   int publicId, int systemId,
                                   int notationName) throws Exception 
    {
      if(null == m_entityNodes)
        initDefaultEntities();
  
      int w0=org.w3c.dom.Node.ENTITY_NODE;
      // W1: Parent
      int w1 = 0;
      // W2: name index
      int w2 =  publicId;
      // W3: Hope we have enough bits...
      int w3 = systemId | (notationName << 16);
  
      int slotnumber = m_entityNodes.appendSlot(w0, w1, w2, w3);
      
      m_entities.put(entityName, slotnumber);
  
      //revist: how to check if entity was already declared.
      // XML spec says that 1st Entity decl is binding.
  
      // EntityImpl entity = 
(EntityImpl)fDocumentImpl.createEntity(fStringPool.toString(entityName));
      // entity.setPublicId(fStringPool.toString(publicId));
      // entity.setSystemId(fStringPool.toString(systemId));
      // entity.setNotationName(fStringPool.toString(notationName));
      // fDocumentType.getEntities().setNamedItem(entity);
  
    } // unparsedEntityDecl(int,int,int,int)
  
    /**
     * &lt;!NOTATION Name ExternalId>
     */
    public final void notationDecl(int notationName, int publicId, int systemId)
      throws Exception 
    {
  
      //revist: how to check if entity was already declared.
      // XML spec says that 1st Entity decl is binding.
  
      // NotationImpl notation = 
(NotationImpl)fDocumentImpl.createNotation(fStringPool.toString(notationName));
      // notation.setPublicId(fStringPool.toString(publicId));
      // notation.setSystemId(fStringPool.toString(systemId));
  
      // fDocumentType.getNotations().setNamedItem(notation);
  
    } // notationDecl(int,int,int)
    
    //==========================================================
    // SECTION: DTM Read API
    //==========================================================
    private final void ____DTMReadAPI____(){}
  
    /**
     * Return the document proxy object.
     */
    public final Document getDocument()
    {
      if(TRACE)
        System.out.println("DTM: getDocument");
      
      if(null != document)
        return document;
      
      synchronized (this)
      {
        while(null == document)
        {
          try
          {
            if(m_isError)
              break;
            if(DEBUG_WAITS)
              System.out.println("Waiting... getDocument");
            wait();
            if(DEBUG_WAITS)
              System.out.println("Out of waiting... getDocument: "+document);
          }
          catch (InterruptedException e)
          {
            // That's OK, it's as good a time as any to check again
          }
        }
      }
      if(DEBUG_WAITS)
        System.out.println("getDocument returning: "+document);
      return document;
    }
  
    /**
     * DTM read API: Given a node index, get the index of the node's first 
child.
     * If not yet resolved, waits for more nodes to be added to the document and
     * tries again
     * @param postition int Index of this node's record.
     * @return int DTM node-number of first child, or -1 to indicate none 
exists.
     */
    public final int getFirstChild(int position)
    {
      if(TRACE)
        System.out.println("DTM: getFirstChild");
          
      // Examine the node in question   
      nodes.readSlot(position, gotslot);
  
      // If not an element or Attribute or EntRef, child is null
      int type = (gotslot[0] & 0xFFFF);
      if ((type != Node.ELEMENT_NODE) &&
          (type != Node.ENTITY_REFERENCE_NODE) &&
          (type != Node.DOCUMENT_NODE))
        return -1;
      
      // 0 is Document; first child is node 1.
      int parent = (position == 0) ? 1 : gotslot[1];
      
      // Advance to first non-Attr child
      // (First child of any kind is at position+1, thereafter walk sibs)
      int kid=position+1;
      while((kid > nodes.lastUsed) && !done)
      {
        synchronized (this)
        {
          try
          {
            if(m_isError)
              break;
            if(DEBUG_WAITS)
              System.out.println("Waiting... getFirstChild");
            wait();
          }
          catch (InterruptedException e)
          {
            // That's OK, it's as good a time as any to check again
          }
        }
      }
  
      // ***** MIGHT GET MORE SPEED BY INLINING THE NEXT-SIB CODE.
      while (kid != -1)
      {
        nodes.readSlot(kid,gotslot);
        boolean isAttr = ((gotslot[0]&0xff) == Node.ATTRIBUTE_NODE);
        if(isAttr)
        {
          // kid=getNextSibling(kid); // Since attrs have 2 nodes, advance by 2
          // if(kid == -1)
          //  break;
        }
        else if(gotslot[1] == position)
          return kid;
        else if(gotslot[1] == parent)
          break; // already to next sibling.
        
        // Else it's an Attr. Advance to next (Attrs have Next in DTM)
        // and try again.
        kid=getNextSibling(kid);
      }
      return -1;
    }
    
    /**
     * DTM read API: Given a node index, get the index of the node's first 
child.
     * If not yet resolved, waits for more nodes to be added to the document and
     * tries again
     * @param postition int Index of this node's record.
     * @return int DTM node-number of first child, or -1 to indicate none 
exists.
     */
    public final int getFirstAttribute(int position)
    {
      if(TRACE)
        System.out.println("DTM: getFirstAttribute");
          
      // Examine the node in question   
      nodes.readSlot(position, gotslot);
  
      // If not an element or Attribute or EntRef, child is null
      int type = (gotslot[0] & 0xFFFF);
      if (type != Node.ELEMENT_NODE)
        return -1;
      
      // 0 is Document; first child is node 1.
      // int parent = (position == 0) ? 1 : gotslot[1];
      
      // Advance to first non-Attr child
      // (First child of any kind is at position+1, thereafter walk sibs)
      int kid=position+1;
      while((kid > nodes.lastUsed) && !done)
      {
        synchronized (this)
        {
          try
          {
            if(m_isError)
              break;
            if(DEBUG_WAITS)
              System.out.println("Waiting... getFirstChild");
            wait();
          }
          catch (InterruptedException e)
          {
            // That's OK, it's as good a time as any to check again
          }
        }
      }
  
      nodes.readSlot(kid,gotslot);
      boolean isAttr = ((gotslot[0]&0xff) == Node.ATTRIBUTE_NODE);
      if(isAttr)
      {
        return kid;
      }
      return -1;
    }
  
  
    /**
     * DTM read API: Given a node index, advance to the next attribute. If an
     * element, we advance to its first attribute; if an attr, we advance to
     * the next attr on the same node.
     * If not yet resolved, waits for more nodes to be added to the document and
     * tries again.
     * @param postition int Index of this node's record.
     * @return int DTM node-number of the resolved attr, 
     * or -1 to indicate none exists.
     */
    public final int getNextAttribute(int position)
    {
      if(TRACE)
        System.out.println("DTM: getNextAttribute: "+position);
  
      while (!m_isError)
      {
        // Next after last in document is Null.
        if (done && position >= nodes.lastUsed)
          return -1;
  
        // Examine the node in question 
        nodes.readSlot(position, gotslot);
        
        // If not starting from element or attribute, 
        // this operation doesn't apply
        int type=gotslot[0] & 0xFFFF;
        if (type != Node.ATTRIBUTE_NODE && 
            type!= Node.ELEMENT_NODE)
          return -1;
  
        else
        {
          if (position < nodes.lastUsed) 
          {
            // If starting from an element,
            // First attr is following slot, or doesn't exist.
            if(type==Node.ELEMENT_NODE)
            {
              if((nodes.readEntry(position + 1, 0)& 0xFFFF) == 
                 Node.ATTRIBUTE_NODE)
                return position + 1;
              else
                return -1;
            }
            
            // If starting from an attribute,
            // next attr is via reference
            if(gotslot[2] != 0)
            {
              if((gotslot[2] != -1) &&
                 ((nodes.readEntry(gotslot[2], 0) & 0xFFFF) == 
                 Node.ATTRIBUTE_NODE))
                return gotslot[2];
              else
                return -1;
            }
          }
        }
        
        //Otherwise we need to wait for more nodes and try again
        synchronized (this)
        {
          try
          {
            if(DEBUG_WAITS)
              System.out.println("Waiting... getNextAttribute");
            wait();
          }
          catch (InterruptedException e)
          {
            // That's OK, it's as good a time as any to check again
          }
        }
      }
      throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_ERROR_OCCURED,
 null)); //"Error occured!");
    }
  
    /**
     * DTM read API: Given a node index, advance to its last child. 
     * If not yet resolved, waits for more nodes to be added to the document and
     * tries again.
     * WARNING: DTM is asymmetric; this operation is resolved by search, and is
     * relatively expensive.
     * @param postition int Index of this node's record.
     * @return int Node-number of last child,
     * or -1 to indicate none exists.
     */
    public final int getLastChild(int position)
    {
      if(TRACE)
        System.out.println("DTM: getLastChild");
  
      // NOT OPTIMIZED -- it's slow in this model anyway.
      int nt = getNodeType(position);
      if((nt != Node.ELEMENT_NODE) &&
         (nt != Node.DOCUMENT_NODE))
      {
        // System.out.println("early exit - Node type: "+nt);
        return -1;
      }
      
      int lastChild = -1;
  
      // Walk across the kids until all have been accounted for
      for (int nextkid = getFirstChild(position); 
           nextkid != -1; 
           nextkid = getNextSibling(nextkid))
      {
        lastChild = nextkid;
      }
      return lastChild;
    }
  
    /**
     * DTM read API: Given a node index, advance to its next sibling.
     * If not yet resolved, waits for more nodes to be added to the document and
     * tries again.
     * @param postition int Index of this node's record.
     * @return int Node-number of next sibling,
     * or -1 to indicate none exists.
     */
    public final int getNextSibling(int position)
    {
      if(TRACE)
        System.out.println("DTM: getNextSibling");
  
      // 0 is Document; no next-sib.
      if (position == 0)
        return -1;
      while (!m_isError)
      {
        // Next after last in document is Null.
        if (done && (position >= nodes.lastUsed))
          return -1;
  
        // If an element or attribute, next is as pointed to, IF resolved.
        // (Attributes don't have NextSib in the DOM, but it's a useful concept
        // here)
        int type = nodes.readEntry(position, 0) & 0xFF;
        if (type == Node.ELEMENT_NODE ||
            type == Node.ATTRIBUTE_NODE ||
            type == Node.ENTITY_REFERENCE_NODE)
        { 
          int nextSib = nodes.readEntry(position, 2);
          if(nextSib != 0)
            return nextSib;
        }
        // If not an element, next node is following, IF it
        // has the same parent as this one
        else
        {
          if (position < nodes.lastUsed) 
          {
            int thisParent = nodes.readEntry(position, 1);
            if(nodes.readEntry(position+1, 1) == thisParent)
              return position + 1;
            else
              return -1; // No next kid.
          }
        }
        
        //Otherwise we need to wait for more nodes and try again
        synchronized (this)
        {
          try
          {
            if(DEBUG_WAITS)
              System.out.println("Waiting... getNextSibling");
            wait();
          }
          catch (InterruptedException e)
          {
            // That's OK, it's as good a time as any to check again
          }
        }
      }
      
      ErrorHandler ehandler = this.getErrorHandler();
      
      try
      {
        if(null != ehandler)
          ehandler.fatalError(new 
SAXParseException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_PROBLEM_IN_DTM_NEXTSIBLING,
 null), null));
      }
      catch(SAXException se)
      {
        if(m_throwNewError)
          throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_ERROR_OCCURED,
 null)); //"Error occured!");
      }
      // 
m_problemListener.message(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_PROBLEM_IN_DTM_NEXTSIBLING,
 null)); //"Problem occured in DTM in getNextSibling... trying to recover");
  
      return -1;
    }
    
    
    /**
     * DTM read API: Given a node index, advance to its next descendant.
     * If not yet resolved, waits for more nodes to be added to the document and
     * tries again.
     * @param postition int Index of this node's record.
     * @return int Node-number of next descendant,
     * or -1 to indicate none exists.
     */
    public final int getNextDescendant(int parentPos, int position)
    {
      if(TRACE)
        System.out.println("DTM: getNextDescendant");
  
      // 0 is Document; no next-sib.
      if (position == 0)
        return -1;
      
      // System.out.println("nodes.lastUsed: "+nodes.lastUsed);
      // System.out.println("position: "+position);
          
      while (!m_isError)
      {
        // Next after last in document is Null.
        if (done && (position >= nodes.lastUsed))
          return -1;
        
        if (position > parentPos) 
        {
          nodes.readSlot(position+1, gotslot);
          
          // System.out.println("["+Integer.toHexString(gotslot[0])
          //                   +"]["+Integer.toHexString(gotslot[1])
          //                   +"]["+Integer.toHexString(gotslot[2])
          //                   +"]["+Integer.toHexString(gotslot[3])+"]");
          
          if(gotslot[2] != 0)
          {
            // Examine the node in question     
            int type = (gotslot[0] & 0xFFFF);
            if (type == Node.ATTRIBUTE_NODE)
            {
              position+=2; // skip this one and the text value
            }
            else 
            {
              int nextParentPos = gotslot[1];
              if(nextParentPos >= parentPos)
                return position+1;
              else
              {
                if(DEBUG_WAITS)
                  System.out.println("Not descendent...");
                return -1; // Not descendent.
              }
            }
          }
          else if(!done)
          {
            //Otherwise we need to wait for more nodes and try again
            synchronized (this)
            {
              try
              {
                if(DEBUG_WAITS)
                  System.out.println("Waiting... getNextDescendant");
                wait();
              }
              catch (InterruptedException e)
              {
                // That's OK, it's as good a time as any to check again
              }
            }
          }
          else
          {
            System.out.println("Strange case...");
  
            // No idea if this is right...
            return -1; // Not descendent.
          }
        }
        else
        {
          position++;
        }
      }
      throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_ERROR_OCCURED,
 null)); //"Error occured!");
    }
  
    /**
     * DTM read API: Given a node index, advance to its next sibling.
     * If not yet resolved, waits for more nodes to be added to the document and
     * tries again.
     * @param postition int Index of this node's record.
     * @return int Node-number of next sibling,
     * or -1 to indicate none exists.
     */
    public final int getNextNode(int parentPos, int position)
    {    
      if(TRACE && false)
        System.out.println("DTM: getNextNode");
  
      while (!m_isError)
      {
        // Next after last in document is Null.
        if (done && (position >= nodes.lastUsed))
          return -1;
        
        int nextOffset = ((nodes.readEntry(position, 1) & 0xFF) == 
Node.ATTRIBUTE_NODE)? 2 : 1;
        
        if (position >= parentPos) 
        {
          nodes.readSlot(position+nextOffset, gotslot);
          
          if(gotslot[2] != 0)
          {
            // Examine the node in question     
            int nextParentPos = gotslot[1];
            if(nextParentPos >= parentPos)
            {
              return position+nextOffset;
            }
            else
              return -1; // Not descendent.
          }
          else if(!done)
          {
            //Otherwise we need to wait for more nodes and try again
            synchronized (this)
            {
              try
              {
                if(DEBUG_WAITS)
                  System.out.println("Waiting... getNextNode");
                wait();
              }
              catch (InterruptedException e)
              {
                // That's OK, it's as good a time as any to check again
              }
            }
          }
          else
          {
            // ??
            return -1;
          }
        }
        else
        {
          position+=nextOffset;
        }
      }
      throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_ERROR_OCCURED,
 null)); //"Error occured!");
    }
    
    /**
     * DTM read API: Given a node index, find its parent node.
     * @param postition int Index of this node's record.
     * @return int Node-number of parent,
     * or -1 to indicate none exists.
     */
    public final int getParent(int position)
    {
      if(TRACE)
        System.out.println("DTM: getParent");
  
      // 0 is Document; no parent
      if (position == 0)
        return -1;
      // Off end of array is undefined.
      if (position > nodes.lastUsed)
        return 0;
      else
        return nodes.readEntry(position, 1);
    }
    
    /**
     * DTM read API: Given a node index, find its preceeding sibling.
     * WARNING: DTM is asymmetric; this operation is resolved by search, and is
     * relatively expensive.
     * @param postition int Index of this node's record.
     * @return int Node-number of the previous sib,
     * or -1 to indicate none exists.
     */
    public final int getPreviousSibling(int position)
    {
      if(TRACE)
        System.out.println("DTM: getPreviousSibling");
  
      // NOT OPTIMIZED -- it's slow in this model anyway.
  
      // 0 is Document, 1 is first child of doc
      if (position <= 1)
        return -1;
  
      int parent = nodes.readEntry(position, 1);
      int kid, nextkid;
      if (parent == 0)
        kid = 1;
      else
        kid = getFirstChild(parent);
      while ((nextkid = getNextSibling(kid)) != position)
      {
        kid = nextkid;
        if(kid == -1)
          break;
      }
      return kid;
    }
    
    /**
     * DTM read API: Given a node index, advance to the preceding node.  
     * The preceding axis contains all nodes in the same document as the 
     * context node that are before the context node in document order, 
     * excluding any ancestors and excluding attribute nodes and namespace 
nodes.
     * @param startPos  The position from where the axes is relative to.
     * @param postition int Index of this node's record.
     * @return int Node-number of preceding sibling,
     * or -1 to indicate none exists.
     */
    public final int getNextPreceding(int startPos, int position)
    {    
      if(TRACE)
        System.out.println("DTM: getNextPreceding");
  
      while (position > 1) // Preceding never returns the root
      {
        // Decrement position
        position--;
        
        int type = (nodes.readEntry(position, 0) & 0xFFFF);
        if (type == Node.ATTRIBUTE_NODE)
          continue;
          
          return nodes.specialFind(startPos, position);
  /*
        // We have to look all the way up the ancestor chain
        // to make sure we don't have an ancestor.
        int ancestor = startPos;
        while(ancestor > 0)
        {
          ancestor = nodes.readEntry(ancestor, 1);
          if(ancestor == position)
            break;
        }
  
        if (ancestor <= 0) 
        {
          return position;
        }
  */      
      }
      return -1;
    }
  
    /**
     * DTM read API: Given a node index, advance to the preceding node.  
     * The preceding axis contains all nodes in the same document as the 
     * context node that are before the context node in document order, 
     * excluding any ancestors and excluding attribute nodes and namespace 
nodes.
     * @param startPos  The position from where the axes is relative to.
     * @param postition int Index of this node's record.
     * @return int Node-number of preceding sibling,
     * or -1 to indicate none exists.
     */
    public final int getPrecedingOrAncestorOrSelf(int position)
    {    
      if(TRACE)
        System.out.println("DTM: getPrecedingOrAncestorOrSelf");
  
      // Decrement position
      position--;
      
      if(position > 1)
      {
        int type = (nodes.readEntry(position-1, 0) & 0xFFFF);
        if (type == Node.ATTRIBUTE_NODE)
          position--;
      }
      return position;
    }
    
    static final String[] fixednames=
    {
      null,null,              // nothing, Element
      null,"#text",           // Attr, Text
      "#cdata_section",null,  // CDATA, EntityReference
      null,null,              // Entity, PI
      "#comment","#document", // Comment, Document
      null,"#document-fragment", // Doctype, DocumentFragment
      null};                  // Notation
  
    /**
     * DTM read API: Given a node index, return its DOM-style node name.
     * @param postition int Index of this node's record.
     * @return String Name of this node.
     */
    public final String getNodeName(int position)
    {
      // int strIndex = nodes.readEntry(position, 3);
      // return fStringPool.toString( fStringPool.getFullNameForQName(strIndex) 
);
      if(position==0)
        return fixednames[Node.DOCUMENT_NODE];
  
      nodes.readSlot(position, gotslot);
      String name=fixednames[gotslot[0]&0xff];
      if(name==null)
        name=intToString(gotslot[3]);
      return name;
    }
    
    /**
     * DTM read API: Given a node index, return its DOM-style localname.
     * (As defined in Namespaces, this is the portion of the name after any
     * colon character)
     * @param postition int Index of this node's record.
     * @return String Local name of this node.
     */
    public final String getLocalName(int position)
    {
      // return  fStringPool.toString( 
fStringPool.getLocalPartForQName(nodes.readEntry(position, 3)) );
      String name=getNodeName(position);
      if(null != name)
      {
        int colonpos = name.indexOf(':');
        return (colonpos < 0) ? name : name.substring(colonpos+1);
      }
      else
      {
        return null;
      }
    }
    
    /**
     * DTM read API: Given a node index, return its DOM-style name prefix.
     * (As defined in Namespaces, this is the portion of the name before any
     * colon character)
     * @param postition int Index of this node's record.
     * @return String prefix of this node's name, or null if no explicit
     * namespace prefix was given.
     */
    public final String getPrefix(int position)
    {
      // return  fStringPool.toString( 
fStringPool.getFullNameForQName(nodes.readEntry(position, 3)) );
      String name=getNodeName(position);
      int colonpos = name.indexOf(':');
      return (colonpos <= 0) ? null : name.substring(0, colonpos);
    }
    
    /**
     * DTM read API: Given a node index, return its DOM-style namespace URI
     * (As defined in Namespaces, this is the declared URI which this node's
     * prefix -- or default in lieu thereof -- was mapped to.)
     * @param postition int Index of this node's record.
     * @return String URI value of this node's namespace, or null if no
     * namespace was resolved.
     */
    public final String getNamespaceURI(int position)
    {
      if(position==0)
        return null;
      int w0=nodes.readEntry(position, 0);
      int type = (w0&0xff);
      if((type != Node.ELEMENT_NODE) && (type != Node.ATTRIBUTE_NODE))
        return null;
      else 
        return intToString(w0>>16);
    }
  
    /**
     * DTM read API: Given a node index, return its node value. This is mostly
     * as defined by the DOM, but may ignore some conveniences.
     * <p>
     * @param postition int Index of this node's record.
     * @return String Value of this node, or null if not 
     * meaningful for this node type.
     */
    public final String getNodeValue(int position)
    {
      nodes.readSlot(position, gotslot);
      int nodetype=gotslot[0] & 0xFF;
      String value=null;
      
      switch(nodetype)
      {
      case Node.TEXT_NODE:
      case Node.CDATA_SECTION_NODE: // We handle as flagged Text...
        value=intToString(gotslot[2]);
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:
      case Node.COMMENT_NODE:
        value=intToString(gotslot[2]);
        break;
      case Node.ATTRIBUTE_NODE: // Value is in kid(s)
      case Node.ELEMENT_NODE:
      case Node.ENTITY_REFERENCE_NODE:
      default:
        break;
      }
      return value; // DO SOMETHING FOR SAX?
    }
  
    /**
     * DTM read API: Given a node index, return its DOM-style node type.
     * @param postition int Index of this node's record.
     * @return int Node type, as per the DOM's Node._NODE constants.
     */
    public final int getNodeType(int position)
    {
      return nodes.readEntry(position,0)&0xff;
    }
    
    /**
     * DTM read API: Given a node index, indicate whether the parser marked
     * it as an ignorable-whitespace text node.
     * @param postition int Index of this node's record.
     * @return boolean true iff the node was created via an ignorableWhitespace
     * event.
     */
    public final boolean isIgnorableText(int position)
    {
      return (position == 0) 
             ? false
               : ( (nodes.readEntry(position,0)&0xffff) ==
                   (Node.TEXT_NODE | TEXT_IGNORABLE) );
    }
  
    /**
     * DTM development API: Given a node index, write the node's contents
     * in extremely terse form onto Standard Output.
     * @param postition int Index of this node's record.
     */
    public final void display(int position)
    {
      if(position == 0)
        System.out.println("0:\tDocument (implicit first child = 1)");
      else
      {
        System.out.println(position+":\t"+getNodeName(position)+
                           ", parent="+getParent(position)+
                           ", nextsib="+getNextSibling(position) );
        String v=getNodeValue(position);
        if(v!=null)
          System.out.println("\tvalue="+v);
      }
    }
    /**
     * DTM development API: display() all the nodes in the DTM.
     * @see display
     *
     */
    public final void dump()
    {
      for(int i=0;i<=nodes.lastUsed;++i)
        display(i);
    }
  
    /**
     * Internal routine: Add a string to the symbol table. Attempts to work
     * in both SAX and XML4J-specific modes.
     * @param s String to be added
     * @return int Index number assigned to this string
     */
    private final int stringToInt(String s)
    {
      // Used only for SAX-based input
      // When recieving from XML4J, numbers were precalculated
      if(fStringPool==null)
      {
        Integer iobj=(Integer)symbolTable.get(s);
        if (iobj==null)
        {
          symbolList.addElement(s);
          iobj=new Integer(symbolList.size());
          symbolTable.put(s,iobj);
        }
        return iobj.intValue();
      }
      else
        return fStringPool.addSymbol(s);
    }
    /**
     * Internal routine: Retrieve a string from the symbol table. Attempts to 
work
     * in both SAX and XML4J-specific modes.
     * @param int Index number of desired string
     * @return String String represented by that number.
     */
    private final String intToString(int i)
    {
      if(fStringPool==null)
        return (String)symbolList.elementAt(i);
      else
        return fStringPool.toString(i);
    }
    
    /**
     * Internal routine: Look up a namespace in the current parent-element's
     * context, by consulting the stacked hashtables.
     * @param prefix String prefix to be resolved
     * @return String Namespace URI which that prefix currently points to.
     */
    private final String resolveNamespace(String prefix)
    {
      if(prefix==null || prefix.length() == 0)
        prefix=DEFAULT_PREFIX_STR;
      
      String nsuri = namespaceTable.get((prefix==null || prefix.length() == 0) 
? 
                                        DEFAULT_PREFIX_STR : prefix);
      return (null == nsuri) ? "" : nsuri;
    }
    
    /**
     * Internal routine: Look up a namespace in the current parent-element's
     * context, by consulting the stacked hashtables.
     * @param prefix String prefix to be resolved
     * @return String Namespace URI which that prefix currently points to.
     */
    private final boolean isDefaultNamespaceInEffect()
    {
      return namespaceTable.containsKey(DEFAULT_PREFIX_STR);
    }
  
    /**
     * Signal the XML declaration of a document
     *
     * @param version the handle in the string pool for the version number
     * @param encoding the handle in the string pool for the encoding
     * @param standalong the handle in the string pool for the standalone value
     * @exception java.lang.Exception
     */
    public void xmlDecl(int version, int encoding, int standalone) 
      throws Exception
    {
    }
    
    /**
     * Signal the Text declaration of an external entity.
     *
     * @exception java.lang.Exception
     */
    public void textDecl(int version, int encoding) throws Exception
    {
    }
  
    /**
     * This feature determines whether entity references within
     * the document are included in the document tree as
     * EntityReference nodes.
     * <p>
     * Note: The children of the entity reference are always
     * added to the document. This feature only affects
     * whether an EntityReference node is also included
     * as the parent of the entity reference children.
     *
     * @param create True to create entity reference nodes; false
     *               to only insert the entity reference children.
     *
     * @see #getCreateEntityReferenceNodes
     */
    protected void setCreateEntityReferenceNodes(boolean create) 
    {
      fCreateEntityReferenceNodes = create;
    }
  
    /**
     * @see #setCreateEntityReferenceNodes
     */
    public final boolean getCreateEntityReferenceNodes() 
    {
      return fCreateEntityReferenceNodes;
    }
    
    /*
    class NullSchemaValidator extends 
org.apache.xerces.validators.schema.XSchemaValidator
    {
      public NullSchemaValidator(org.apache.xerces.utils.StringPool stringPool, 
                                 org.apache.xerces.framework.XMLErrorReporter 
errorReporter, 
                                 XMLEntityHandler entityHandler) 
      {
        super(stringPool, errorReporter, entityHandler);
      }
      
      public final void loadSchema(String uri) {}
      public final void loadSchema(InputSource is) {}
    }
    */
  
    //==========================================================
    // SECTION: Diagnostics
    //==========================================================
    private final void ____Diagnostics____(){}
    
    public void dumpDTM()
    {
      try
      {
        // java.io.File file = new java.io.File("dtmdump.txt");
        java.io.FileOutputStream os = new 
java.io.FileOutputStream("dtmdump.txt");
        java.io.PrintWriter pw = new java.io.PrintWriter(os);
        for(int i = 0;i < nodes.lastUsed;i++)
        {
          nodes.readSlot(i, gotslot);
          pw.print(i+") ");
          pw.print("[type: "+gotslot[0]+" (");
          int type = (gotslot[0] & 0x00FF);
          switch(type)
          {
          case Node.ATTRIBUTE_NODE: pw.print("ATTRIBUTE_NODE"); break;
          case Node.CDATA_SECTION_NODE: pw.print("CDATA_SECTION_NODE"); break;
          case Node.COMMENT_NODE: pw.print("COMMENT_NODE"); break;
          case Node.DOCUMENT_FRAGMENT_NODE: pw.print("DOCUMENT_FRAGMENT_NODE"); 
break;
          case Node.DOCUMENT_NODE: pw.print("DOCUMENT_NODE"); break;
          case Node.DOCUMENT_TYPE_NODE: pw.print("DOCUMENT_TYPE_NODE"); break;
          case Node.ELEMENT_NODE: pw.print("ELEMENT_NODE"); break;
          case Node.ENTITY_NODE: pw.print("ENTITY_NODE"); break;
          case Node.ENTITY_REFERENCE_NODE: pw.print("ENTITY_REFERENCE_NODE"); 
break;
          case Node.NOTATION_NODE: pw.print("NOTATION_NODE"); break;
          case Node.PROCESSING_INSTRUCTION_NODE: 
pw.print("PROCESSING_INSTRUCTION_NODE"); break;
          case Node.TEXT_NODE: pw.print("TEXT_NODE"); break;
          default: pw.print("???");
          }
          pw.print(")]");
          pw.print("[parent: "+gotslot[1]+"]");
          if(Node.TEXT_NODE == type)
          {
            pw.print("[data: "+gotslot[2]+"]");
            // pw.print("[2]: "+gotslot[2]+" (char data: 
"+intToString(gotslot[2])+")");
            // pw.print("[3]: "+gotslot[3]+" (empty)");
          }
          else
          {
            pw.print("[next: "+gotslot[2]+"]");
            pw.print("[name: "+gotslot[3]+", "+intToString(gotslot[3])+"]");
          }
          pw.println("");
        }
        pw.close();
      }
      catch(java.io.IOException ioe)
      {
        System.out.println("Could not dump DTM");
      }
  
    }
  
  }
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/dtm/DTMException.java
  
  Index: DTMException.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
  
  /** 
   * <meta name="usage" content="internal"/>
   * Simple implementation of DOMException. Could have used the one in
   * com.ibm.xml.dom, but didn't want to depend on that package.
   */
  public class DTMException
    extends org.w3c.dom.DOMException
  {
    /** Constructs a DOM/DTM exception. */
    public DTMException(short code, String message) 
    {
      super(code, message);
    }    
    
    public DTMException(short code) 
    {
      super(code,"");
    }    
  }
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/dtm/DTMLiaison.java
  
  Index: DTMLiaison.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
  
  import java.net.*;
  import java.io.*;
  import java.util.*;
  import org.apache.xerces.dom.*;
  import org.apache.xerces.parsers.*;
  import org.apache.xerces.framework.*;
  import org.xml.sax.*;
  import org.w3c.dom.*;
  
  import org.apache.xalan.xpath.DOM2Helper;
  import org.apache.xalan.xpath.XPathFactory;
  import org.apache.xalan.xpath.XLocator;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.res.XSLMessages;
  
  /**
   * <meta name="usage" content="internal"/>
   * Liaison to Document Table Model (DTM) XML parser -- the default liaison 
and parser that XSLTProcessor
   * uses to perform transformations.
   * To enhance performance, DTM uses integer arrays to represent a DOM. If you 
are reading or writing a
   * DOM, use DOM2Helper.
   *
   * @see org.apache.xalan.xslt.XSLTProcessor
   * @see org.apache.xalan.xpath.DOM2Helper
   */
  public class DTMLiaison extends DOM2Helper
  {
    /**
     * Flag to tell whether or not the parse is done on a seperate thread,
     * so the transform can occur at the same time.  The default
     * is true.
     */
    private boolean m_doThreading = false;
  
    /**
     * Set whether or not the parse is done on a seperate thread,
     * so the transform can occur at the same time.  The default
     * is true.
     */
    boolean getDoThreading()
    {
      return m_doThreading;
    }
  
    /**
     * Set whether or not the parse is done on a seperate thread,
     * so the transform can occur at the same time.  The default
     * is true.
     */
    void setDoThreading(boolean b)
    {
      m_doThreading = b;
    }
  
    /**
     * Construct an instance.
     */
    public DTMLiaison()
    {
    }
  
    /**
     * Check node to see if it matches this liaison.
     */
    public void checkNode(Node node)
      throws SAXException
    {
      if(!(node instanceof DTMProxy))
        throw new 
SAXException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_DTM_CANNOT_HANDLE_NODES,
 new Object[]{((Object)node).getClass()})); //"DTMLiaison can not handle nodes 
of type"
          //+((Object)node).getClass());
    }
    
    /**
     * Figure out if node2 should be placed after node1 when 
     * placing nodes in a list that is to be sorted in 
     * document order.  Assumes that node1 and node2 are not
     * equal.
     * NOTE: Make sure this does the right thing with attribute nodes!!!
     * @return true if node2 should be placed 
     * after node1, and false if node2 should be placed 
     * before node1.
     */
    public boolean isNodeAfter(Node node1, Node node2)
    {
      // Assume first that the nodes are DTM nodes, since discovering node 
      // order is massivly faster for the DTM.
      try
      {
        int index1 = ((DTMProxy)node1).getDTMNodeNumber();
        int index2 = ((DTMProxy)node2).getDTMNodeNumber();
        return index1 <= index2;
      }
      catch(ClassCastException cce)
      {
        // isNodeAfter will return true if node is after countedNode 
        // in document order. isDOMNodeAfter is sloooow (relativly).
        return super.isNodeAfter(node1, node2);
      }
    }    
  
    /**
     * Parse an XML document.
     *
     * <p>The application can use this method to instruct the SAX parser
     * to begin parsing an XML document from any valid input
     * source (a character stream, a byte stream, or a URI).</p>
     *
     * <p>Applications may not invoke this method while a parse is in
     * progress (they should create a new Parser instead for each
     * additional XML document).  Once a parse is complete, an
     * application may reuse the same Parser object, possibly with a
     * different input source.</p>
     *
     * @param source The input source for the top-level of the
     *        XML document.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @exception java.io.IOException An IO exception from the parser,
     *            possibly from a byte stream or character stream
     *            supplied by the application.
     * @see org.xml.sax.InputSource
     * @see #parse(java.lang.String)
     * @see #setEntityResolver
     * @see #setDTDHandler
     * @see #setContentHandler
     * @see #setErrorHandler
     */
    public void parse (InputSource source)
      throws SAXException
    {
      if(true)
      {
        DTM parser = new DTM();
        Thread parseThread = null;
        {
          String ident = (null == source.getSystemId())
                         ? "Input XSL" : source.getSystemId();
          parser.setErrorHandler(new 
org.apache.xalan.utils.DefaultErrorHandler(ident));
  
          // if(null != m_entityResolver)
          // {
            // System.out.println("Setting the entity resolver.");
          //  parser.setEntityResolver(m_entityResolver);
          // }
  
          // if(getUseValidation())
          //  parser.setFeature("http://xml.org/sax/features/validation";, true);
  
          // Set whether or not to create entity ref nodes
          // 
parser.setFeature("http://apache.org/xml/features/dom/create-entity-ref-nodes";, 
getShouldExpandEntityRefs());
  
          if(m_doThreading)
          {
            try
            {
              parser.parse(source);
            }
            catch(IOException ioe)
            {
              throw new SAXException(ioe);
            }
          }
          else
          {
            parser.setInputSource(source);
            parseThread = new Thread(parser);
            try
            {
              parseThread.start();
            }
            catch(RuntimeException re)
            {
              throw new SAXException(re.getMessage());
            }
          }
  
          setDocument(parser.getDocument());
        }
      }
      else
      {
        super.parse(source);
      }
    }
  
    /**
     * Returns true if the liaison supports the SAX ContentHandler
     * interface.  The default is that the parser does not support
     * the SAX interface.
     */
    public boolean supportsSAX()
    {
      return true;
    }
  
    /**
     * Returns the namespace of the given node.
     */
    public String getNamespaceOfNode(Node n)
    {
      return ((org.apache.xalan.dtm.DTMProxy)n).getNamespaceURI();
    }
  
    /**
     * Returns the local name of the given node.
     */
    public String getLocalNameOfNode(Node n)
    {
      return ((org.apache.xalan.dtm.DTMProxy)n).getLocalName();
    }
  
    /**
     * Get the parent of a node.
     */
    public Node getParentOfNode(Node n)
      throws RuntimeException
    {
      return ((org.apache.xalan.dtm.DTMProxy)n).getOwnerNode();
    }
  
    /**
     * Given an ID, return the element.
     */
    public Element getElementByID(String id, Document doc)
    {
      return ((DTMProxy)doc).getDTM().getIdentifier(id);
    }
  
    /**
     * The getUnparsedEntityURI function returns the URI of the unparsed
     * entity with the specified name in the same document as the context
     * node (see [3.3 Unparsed Entities]). It returns the empty string if
     * there is no such entity.
     * (Should this go here or in the XLocator??)
     * Since it states in the DOM draft: "An XML processor may choose to
     * completely expand entities before the structure model is passed
     * to the DOM; in this case, there will be no EntityReferences in the DOM 
tree."
     * So I'm not sure how well this is going to work.
     */
    public String getUnparsedEntityURI(String name, Document doc)
    {
      String url = null;
      DTMProxy docp = (DTMProxy)doc;
      DTM dtm = docp.dtm;
      int nameindex = dtm.getStringPool().addSymbol(name);
      int entityRefIndex = dtm.m_entities.get(nameindex);
      int entityRef[] = {0, 0, 0, 0};
      dtm.m_entityNodes.readSlot(entityRefIndex, entityRef);
      if((entityRef[3] >> 16) != 0)
      {
        url = dtm.getStringPool().toString(entityRef[3] & 0xFF);
        if(null == url)
        {
          url = dtm.getStringPool().toString(entityRef[2]);
        }
        else
        {
          // This should be resolved to an absolute URL, but that's hard
          // to do from here.
        }
      }
  
      return url;
      
      /*
      String url = "";
      DocumentType doctype = doc.getDoctype();
      if(null != doctype)
      {
        NamedNodeMap entities = doctype.getEntities();
        Entity entity = (Entity)entities.getNamedItem(name);
        String notationName = entity.getNotationName();
        if(null != notationName) // then it's unparsed
        {
          // The draft says: "The XSLT processor may use the public
          // identifier to generate a URI for the entity instead of the URI
          // specified in the system identifier. If the XSLT processor does
          // not use the public identifier to generate the URI, it must use
          // the system identifier; if the system identifier is a relative
          // URI, it must be resolved into an absolute URI using the URI of
          // the resource containing the entity declaration as the base
          // URI [RFC2396]."
          // So I'm falling a bit short here.
          url = entity.getSystemId();
          if(null == url)
          {
            url = entity.getPublicId();
          }
          else
          {
            // This should be resolved to an absolute URL, but that's hard
            // to do from here.
          }
        }
      }
      return url;
      */
    }
  
    /**
     * Get a factory to create XPaths.
     */
    public XPathFactory getDefaultXPathFactory()
    {
      return DTMNodeLocator.factory();
    }
  
    /**
     * Get an XLocator provider keyed by node.  This get's
     * the association based on the root of the tree that the
     * node is parented by.
     */
    public XLocator getXLocatorFromNode(Node node)
    {
      return DTMNodeLocator.getDefaultLocator();
    }
  
    /**
     * getXLocatorHandler.
     */
    public XLocator createXLocatorHandler()
    {
      return DTMNodeLocator.getDefaultLocator();
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/dtm/DTMNodeLocator.java
  
  Index: DTMNodeLocator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
  
  import org.apache.xalan.xpath.SimpleNodeLocator;
  
  import java.util.*;
  import java.io.*;
  import org.w3c.dom.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  /**
   * <meta name="usage" content="advanced"/>
   */
  public class DTMNodeLocator extends SimpleNodeLocator
  {
    /**
     * Create a DTMNodeLocator object.
     */
    public DTMNodeLocator()
    {
    }
  
    /**
     * The singleton instance of this class.
     */
    private static DTMNodeLocator m_locater = null;
  
    /**
     * The default locator.
     */
    public static XLocator getDefaultLocator()
    {
      m_locater = (null == m_locater) ? new DTMNodeLocator() : m_locater;
      return m_locater;
    }
  }
  
  /**
   * Override the createXLocatorHandler method.
   */
    class DTMXPath extends XPath
    {
      public DTMXPath()
      {
        super();
      }
  
      /**
       * getXLocatorHandler.
       */
      public XLocator createXLocatorHandler(XPath xpath)
      {
        return new DTMNodeLocator();
      }
    }
  
  /**
   * Implement an XPath factory.
   */
    class DTMNodeLocatorFactory implements XPathFactory
    {
      public XPath create()
      {
        return new DTMXPath();
      }
    }
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/dtm/DTMNodeVector.java
  
  Index: DTMNodeVector.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
  
  /**
   * <meta name="usage" content="internal"/>
   * Simple class to hold an array of nodes.
   */
  class DTMNodeVector
  {
    static final int BLOCKSIZE = 1024;
    DTMProxy m_map[] = new DTMProxy[BLOCKSIZE];
    int m_mapSize = BLOCKSIZE;
    
    DTMNodeVector()
    {
    }
    
    void put(int pos, DTMProxy value)
    {
      if(pos >= m_mapSize)
      {
        int orgMapSize = m_mapSize;
        while(pos >= m_mapSize)
          m_mapSize+=BLOCKSIZE;
        DTMProxy newMap[] = new DTMProxy[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, orgMapSize);
        m_map = newMap;
      }
      // For now, just do a simple append.  A sorted insert only 
      // makes sense if we're doing an binary search or some such.
      m_map[pos] = value;
    }
    
    DTMProxy get(int pos)
    {
      if(pos >= m_mapSize)
        return null;
      return m_map[pos];
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/dtm/DTMProxy.java
  
  Index: DTMProxy.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
  import org.w3c.dom.*;
  
  /**
   * <meta name="usage" content="internal"/>
   * <code>DTMProxy</code> presents a DOM Node API front-end to the DTM model.
   * <p>
   * It does _not_ attempt to address the "node identity" question; no effort
   * is made to prevent the creation of multiple proxies referring to a single
   * DTM node. Users can create a mechanism for managing this, or relinquish the
   * use of "==" and use the .sameNodeAs() mechanism, which is under
   * consideration for future versions of the DOM.
   * <p>
   * DTMProxy may be subclassed further to present specific DOM node types.
   *
   * @see org.w3c.dom
   */
  public class DTMProxy
    implements Node, Document, Text, Element, Attr, ProcessingInstruction, 
Comment
  {
    public DTM dtm;
    int node;
  
    /** Create a DTMProxy Node representing a specific Node in a DTM */
    DTMProxy(DTM dtm,int node,int type)
    {
      this.dtm=dtm;
      this.node=node;
    }
  
    /** Create a DTMProxy Node representing a specific Node in a DTM */
    DTMProxy(DTM dtm,int node)
    {
      this.dtm=dtm;
      this.node=node;
    }
  
    /** Create a DTMProxy Node representing the Document Node in a DTM */
    DTMProxy(DTM dtm)
    {
      this(dtm,0, Node.DOCUMENT_NODE);
    }
    
    /** NON-DOM: Return the DTM model */
    public final DTM getDTM()
    {
      return dtm;
    }
    
    /** NON-DOM: Return the DTM node number */
    public final int getDTMNodeNumber()
    {
      return node;
    }
    
    /**
     * Test for equality based on node number.
     */
    public final boolean equals(Node node)
    {
      try
      {
        DTMProxy dtmp = (DTMProxy)node;
        return (dtmp.node == this.node);
      }
      catch(ClassCastException cce)
      {
        return false;
      }
    }
  
    /**
     * Test for equality based on node number.
     */
    public final boolean equals(Object node)
    {
      try
      {
        DTMProxy dtmp = (DTMProxy)node;
        return (dtmp.node == this.node);
      }
      catch(ClassCastException cce)
      {
        return false;
      }
    }
  
    /** FUTURE DOM: Test node identity, in lieu of Node==Node */
    public final boolean sameNodeAs(Node other)
    {
      if(! (other instanceof DTMProxy) )
        return false;
      DTMProxy that=(DTMProxy)other;
      return this.dtm==that.dtm && this.node==that.node;
    }
    
    /** @see org.w3c.dom.Node */
    public final String             getNodeName()
    {
      return dtm.getNodeName(node);
    }
    
    /**
     * A PI's "target" states what processor channel the PI's data
     * should be directed to. It is defined differently in HTML and XML.
     * <p>
     * In XML, a PI's "target" is the first (whitespace-delimited) token
     * following the "<?" token that begins the PI.
     * <p>
     * In HTML, target is always null.
     * <p>
     * Note that getNodeName is aliased to getTarget.
     */
    public final String getTarget() 
    {
      return dtm.getNodeName(node);
    } // getTarget():String
    
    /** @see org.w3c.dom.Node as of DOM Level 2*/
    public final String             getLocalName()
    {
      return dtm.getLocalName(node);
    }
    
    /** @see org.w3c.dom.Node as of DOM Level 2*/
    public final String             getPrefix()
    {
      return dtm.getPrefix(node);
    }
    
    /** @see org.w3c.dom.Node as of DOM Level 2 -- DTMProxy is read-only */
    public final void               setPrefix(String prefix)
      throws DOMException
    {
      throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
    }
    
    /** @see org.w3c.dom.Node as of DOM Level 2*/
    public final String             getNamespaceURI()
    {
      return dtm.getNamespaceURI(node);
    }
    
    /** @see org.w3c.dom.Node as of DOM Level 2 */
    public final boolean            supports(String feature, 
                                             String version)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Node */
    public final String  getNodeValue()                                         
        
      throws DOMException
    {
      // ***** ASSUMPTION: ATTRIBUTES HAVE SINGLE TEXT-NODE CHILD.
      // (SIMILAR ASSUMPTION CURRENTLY MADE IN DTM; BE SURE TO
      // REVISIT THIS IF THAT CHANGES!)
      if (getNodeType()==Node.ATTRIBUTE_NODE)
        return dtm.getNodeValue(node+1);
      return dtm.getNodeValue(node);
    }
  
    /** @see org.w3c.dom.Node -- DTMProxy is read-only */
    public final void               setNodeValue(String nodeValue)
      throws DOMException
    {
      throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
    }
  
    /** @see org.w3c.dom.Node */
    public final short              getNodeType()
    {
      return (short) dtm.getNodeType(node);
    }
    
    /** @see org.w3c.dom.Node */
    public final Node               getParentNode()
    {
      if(getNodeType() == Node.ATTRIBUTE_NODE)
        return null;
      int newnode=dtm.getParent(node);
      return (newnode==-1) ? null : dtm.getNode(newnode);
    }
  
    /** @see org.w3c.dom.Node */
    public final Node               getOwnerNode()
    {
      int newnode=dtm.getParent(node);
      return (newnode==-1) ? null : dtm.getNode(newnode);
    }
  
    /** @see org.w3c.dom.Node */
    public final NodeList           getChildNodes()
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Node */
    public final Node               getFirstChild()
    {
      int newnode=dtm.getFirstChild(node);
      return (newnode==-1) ? null : dtm.getNode(newnode);
    }
    
    /** @see org.w3c.dom.Node */
    public final Node               getLastChild()
    {
      int newnode=dtm.getLastChild(node);
      return (newnode==-1) ? null : dtm.getNode(newnode);
    }
    
    /** @see org.w3c.dom.Node */
    public final Node               getPreviousSibling()
    {
      int newnode=dtm.getPreviousSibling(node);
      return (newnode==-1) ? null : dtm.getNode(newnode);
    }
    
    /** @see org.w3c.dom.Node */
    public final Node               getNextSibling()
    {
      // Attr's Next is defined at DTM level, but not at DOM level.
      if(dtm.getNodeType(node)==Node.ATTRIBUTE_NODE)
        return null;
      int newnode=dtm.getNextSibling(node);
      return (newnode==-1) ? null : dtm.getNode(newnode);
    }
  
    /** @see org.w3c.dom.Node */
    public final NamedNodeMap       getAttributes()
    {
      return new DTMProxyMap(dtm,node);
    }
  
    /** @see org.w3c.dom.Node */
    public final Document           getOwnerDocument()
    {
      return dtm.getDocument();
    }
    
    /** @see org.w3c.dom.Node -- DTMProxy is read-only */
    public final Node               insertBefore(Node newChild, 
                                           Node refChild)
      throws DOMException
    {
      throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
    }
  
    /** @see org.w3c.dom.Node -- DTMProxy is read-only */
    public final Node               replaceChild(Node newChild, 
                                           Node oldChild)
      throws DOMException
    {
      throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
    }
  
    /** @see org.w3c.dom.Node -- DTMProxy is read-only */
    public final Node               removeChild(Node oldChild)
      throws DOMException
    {
      throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
    }
  
    /** @see org.w3c.dom.Node -- DTMProxy is read-only */
    public final Node               appendChild(Node newChild)
      throws DOMException
    {
      throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
    }
  
    /** @see org.w3c.dom.Node */
    public final boolean            hasChildNodes()
    {
      return (-1 != dtm.getFirstChild(node));
    }
    
    /** @see org.w3c.dom.Node -- DTMProxy is read-only */
    public final Node               cloneNode(boolean deep)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Document */
    public final DocumentType       getDoctype()
    {
      return null;
    }
  
    /** @see org.w3c.dom.Document */
    public final DOMImplementation  getImplementation()
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final Element            getDocumentElement()
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final Element            createElement(String tagName)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final DocumentFragment   createDocumentFragment()
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final Text               createTextNode(String data)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final Comment            createComment(String data)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final CDATASection       createCDATASection(String data)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final ProcessingInstruction createProcessingInstruction(String 
target, 
                                                             String data)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final Attr               createAttribute(String name)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final EntityReference    createEntityReference(String name)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Document */
    public final NodeList           getElementsByTagName(String tagname)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Document as of DOM Level 2 -- DTMProxy is read-only*/
    public final Node               importNode(Node importedNode, 
                                               boolean deep)
      throws DOMException
    {
      throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
    }
  
    /** @see org.w3c.dom.Document as of DOM Level 2 */
    public final Element            createElementNS(String namespaceURI, 
                                                    String qualifiedName)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Document as of DOM Level 2 */
    public final Attr               createAttributeNS(String namespaceURI, 
                                                      String qualifiedName)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Document as of DOM Level 2 */
    public final NodeList           getElementsByTagNameNS(String namespaceURI, 
                                                           String localName)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Document as of DOM Level 2 */
    public final Element            getElementById(String elementId)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Text */
    public final Text               splitText(int offset)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.CharacterData */
    public final String             getData()
      throws DOMException
    {
      return dtm.getNodeValue(node);
    }
  
    /** @see org.w3c.dom.CharacterData */
    public final void               setData(String data)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.CharacterData */
    public final int                getLength()
    {
      // %%FIX: This should do something smarter?
      return dtm.getNodeValue(node).length();
    }
  
    /** @see org.w3c.dom.CharacterData */
    public final String             substringData(int offset, 
                                            int count)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.CharacterData */
    public final void               appendData(String arg)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.CharacterData */
    public final void               insertData(int offset, 
                                         String arg)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.CharacterData */
    public final void               deleteData(int offset, 
                                         int count)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.CharacterData */
    public final void               replaceData(int offset, 
                                          int count, 
                                          String arg)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Element */
    public final String             getTagName()
    {
      return dtm.getNodeName(node);
    }
  
    /** @see org.w3c.dom.Element */
    public final String             getAttribute(String name)
    { 
      DTMProxyMap  map = new DTMProxyMap(dtm, node);
      Node node = map.getNamedItem(name);
      return (null == node) ? null : node.getNodeValue();
    }
  
    /** @see org.w3c.dom.Element */
    public final void               setAttribute(String name, 
                                           String value)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Element */
    public final void               removeAttribute(String name)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Element */
    public final Attr               getAttributeNode(String name)
    {
      DTMProxyMap  map = new DTMProxyMap(dtm, node);
      return (Attr)map.getNamedItem(name);
    }
  
    /** @see org.w3c.dom.Element */
    public final Attr               setAttributeNode(Attr newAttr)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Element */
    public final Attr               removeAttributeNode(Attr oldAttr)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Element */
    public final void               normalize()
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    public boolean hasAttribute(String name)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
      // return false;
    }
  
    public boolean hasAttributeNS(String name, String x)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
      // return false;
    }
    
    /** @see org.w3c.dom.Element */
    public final String             getAttributeNS(String namespaceURI, 
                                                   String localName)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Element */
    public final void               setAttributeNS(String namespaceURI, 
                                                   String qualifiedName, 
                                                   String value)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Element */
    public final void               removeAttributeNS(String namespaceURI, 
                                                      String localName)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Element */
    public final Attr               getAttributeNodeNS(String namespaceURI, 
                                                       String localName)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Element */
    public final Attr               setAttributeNodeNS(Attr newAttr)
      throws DOMException
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
    
    /** @see org.w3c.dom.Attr */
    public final String             getName()
    {
      return dtm.getNodeName(node);
    }
  
    /** @see org.w3c.dom.Attr */
    public final boolean            getSpecified()
    {
      // %%FIX
      return true;
    }
  
    /** @see org.w3c.dom.Attr */
    public final String             getValue()
    {
      return dtm.getNodeValue(node+1);
    }
    
    /** @see org.w3c.dom.Attr */
    public final void               setValue(String value)
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
    /** @see org.w3c.dom.Attr as of DOM Level 2 */ 
    public final Element            getOwnerElement()
    {
      throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
    }
  
  }
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/dtm/DTMProxyMap.java
  
  Index: DTMProxyMap.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
  import org.w3c.dom.*;
  import java.util.Vector;
  
  /** 
   * <meta name="usage" content="internal"/>
   * DTMProxyMap is a quickie (as opposed to quick) implementation of the DOM's
   * NamedNodeMap interface, intended to support DTMProxy's getAttributes()
   * call. 
   * <p>
   * ***** Note: this does _not_ current attempt to cache any of the data;
   * if you ask for attribute 27 and then 28, you'll have to rescan the first
   * 27. It should probably at least keep track of the last one retrieved,
   * and possibly buffer the whole array.
   * <p>
   * ***** Also note that there's no fastpath for the by-name query; we search
   * linearly until we find it or fail to find it. Again, that could be
   * optimized at some cost in object creation/storage.
   */
  public class DTMProxyMap
  implements NamedNodeMap
  {
      DTM dtm;
      int element;
      
      /** Create a getAttributes NamedNodeMap for a given DTM element node */
      DTMProxyMap(DTM dtm,int element)
      {
          this.dtm=dtm;
          this.element=element;
      }
      
      /** Return the number of Attributes on this Element */
      public int getLength()
      {
          int count=0;
          for(int n=dtm.getNextAttribute(element);
              n!=-1;
              n=dtm.getNextAttribute(n))
          {
              ++count;
          }
          return count;           
      }
      
      /** Return the Attr node having a specific name */
      public Node getNamedItem(String name)
      {
          for(int n=dtm.getNextAttribute(element);
              n!=-1;
              n=dtm.getNextAttribute(n))
          {
              if(dtm.getNodeName(n).equals(name))
                  return dtm.getNode(n);
          }
          return null;
      }
      
      /** Return the i'th Attr node bound to this element */ 
      public Node item(int i)
      {
          int count=0;
          for(int n=dtm.getNextAttribute(element);
              n!=-1;
              n=dtm.getNextAttribute(n))
          {
              if(count == i)
                  return dtm.getNode(n);
              else
                  ++count;
          }
          return null;
      }
      
      /** DOM API requires this, but DTM is a read-only model */
      public Node setNamedItem(Node newNode)
      {
          throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
      }
      
      /** DOM API requires this, but DTM is a read-only model */ 
      public Node removeNamedItem(String name)
      {
          throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
      }
      
      /** Retrieve a node specified by local name and namespace URI -- DOMLevel 
2 */
      public Node getNamedItemNS(String namespaceURI, 
                                 String localName)
      {
          throw new DTMException(DTMException.NOT_SUPPORTED_ERR);
      }
   
      /** DOM 2 API requires this, but DTM is a read-only model */
      public Node setNamedItemNS(Node arg)
        throws DOMException
      {
          throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
      }
  
      /** DOM 2 API requires this, but DTM is a read-only model */
      public Node removeNamedItemNS(String namespaceURI, 
                                    String localName)
        throws DOMException
      {
          throw new DTMException(DTMException.NO_MODIFICATION_ALLOWED_ERR);
      }
      
  
  }
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/dtm/IntMap.java
  
  Index: IntMap.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
  
  /**
   * <meta name="usage" content="internal"/>
   * Simple int lookup.
   */
  class IntMap
  {
    static final int BLOCKSIZE = 64;
    int m_map[] = new int[BLOCKSIZE];
    int m_firstFree = 0;
    int m_mapSize = BLOCKSIZE;
    
    IntMap()
    {
    }
    
    void put(int key, int value)
    {
      if((m_firstFree+2) >= m_mapSize)
      {
        m_mapSize+=BLOCKSIZE;
        int newMap[] = new int[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      // For now, just do a simple append.  A sorted insert only 
      // makes sense if we're doing an binary search or some such.
      m_map[m_firstFree] = key;
      m_firstFree++;
      m_map[m_firstFree] = value;
      m_firstFree++;
    }
    
    int get(int key)
    {
      for(int i = 0; i < m_firstFree; i+=2)
      {
        if(m_map[i] == key)
        {
          return m_map[i+1];
        }
      }
      return -1;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/dtm/IntToObjectMap.java
  
  Index: IntToObjectMap.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.dtm;
  
  /**
   * <meta name="usage" content="internal"/>
   * Map simple ints to objects.
   */
  class IntToObjectMap
  {
    static final int BLOCKSIZE = 64;
    int m_map[] = new int[BLOCKSIZE];
    Object m_objects[] = new Object[BLOCKSIZE];
    int m_firstFree = 0;
    int m_mapSize = BLOCKSIZE;
    
    IntToObjectMap()
    {
    }
    
    void put(int key, Object value)
    {
      if(m_firstFree >= m_mapSize)
      {
        m_mapSize+=BLOCKSIZE;
        int newMap[] = new int[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree);
        m_map = newMap;
        Object newObjects[] = new Object[m_mapSize];
        System.arraycopy(m_objects, 0, newObjects, 0, m_firstFree);
        m_objects = newObjects;
      }
      // For now, just do a simple append.  A sorted insert only 
      // makes sense if we're doing an binary search or some such.
      m_map[m_firstFree] = key;
      m_objects[m_firstFree] = value;
      m_firstFree++;
    }
    
    Object get(int key)
    {
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i] == key)
        {
          return m_objects[i];
        }
      }
      return null;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/extensions/ExtensionFunctionHandler.java
  
  Index: ExtensionFunctionHandler.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.extensions;
  
  import java.util.Hashtable;
  import java.util.Vector;
  import java.util.StringTokenizer;
  import java.lang.reflect.Method;
  import java.lang.reflect.Constructor;
  import java.lang.reflect.InvocationTargetException;
  
  import org.xml.sax.SAXException;
  
  import com.ibm.bsf.BSFException;
  import com.ibm.cs.util.ReflectionUtils;
  
  // Temp??
  import org.apache.xalan.transformer.TransformerImpl;
  
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNull;
  
  
  /**
   * <meta name="usage" content="internal"/>
   * Class handling an extension namespace for XPath. Provides functions
   * to test a function's existence and call a function
   *
   * @author Sanjiva Weerawarana ([EMAIL PROTECTED])
   */
  public class ExtensionFunctionHandler 
  {
    public String namespaceUri;  // uri of the extension namespace
    public String scriptLang = "javaclass";    // scripting language of 
implementation
    public String scriptSrc;     // script source to run (if any)
    public String scriptSrcURL;  // URL of source of script (if any)
    public Object javaObject = null;    // object for javaclass engine
    protected boolean hasCalledCTor = false;  // we'll be nice and call a ctor 
if they haven't
    public Class classObject = null;  // class object for javaclass engine
    protected Hashtable functions = new Hashtable (); // functions of namespace
    protected Hashtable elements = new Hashtable (); // elements of namespace
    protected com.ibm.bsf.BSFManager mgr = null; // mgr used to run scripts
    protected boolean componentStarted; // true when the scripts in a
    // component description (if any) have
    // been run
  
    /////////////////////////////////////////////////////////////////////////
    // Constructors
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Construct a new extension namespace handler for a given extension NS.
     * This doesn't do anything - just hang on to the namespace URI.
     * 
     * @param namespaceUri the extension namespace URI that I'm implementing
     */
    public ExtensionFunctionHandler (String namespaceUri) 
    {
      this.namespaceUri = namespaceUri;
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Construct a new extension namespace handler given all the information
     * needed. 
     * 
     * @param namespaceUri the extension namespace URI that I'm implementing
     * @param funcNames    string containing list of functions of extension NS
     * @param lang         language of code implementing the extension
     * @param srcURL       value of src attribute (if any) - treated as a URL
     *                     or a classname depending on the value of lang. If
     *                     srcURL is not null, then scriptSrc is ignored.
     * @param scriptSrc    the actual script code (if any)
     */
    public ExtensionFunctionHandler (String namespaceUri, String funcNames, 
                                     String lang, String srcURL, String src) 
    {
      this (namespaceUri);
      setFunctions (funcNames);
      setScript (lang, srcURL, src);
    }
  
    /////////////////////////////////////////////////////////////////////////
    // Main API
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Set function local parts of extension NS.
     *
     * @param functions whitespace separated list of function names defined
     *        by this extension namespace.
     */
    public void setFunctions (String funcNames) 
    {
      if (funcNames == null) 
      {
        return;
      }
      StringTokenizer st = new StringTokenizer (funcNames, " \t\n\r", false);
      Object junk = new Object ();
      while (st.hasMoreTokens ()) 
      {
        String tok = st.nextToken ();
        functions.put (tok, junk); // just stick it in there basically
      }
    }
  
    /**
     * Set element local parts of extension NS.
     *
     * @param elements whitespace separated list of element names defined
     *        by this extension namespace.
     */
    public void setElements (String elemNames) 
    {
      if (elemNames == null) 
      {
        return;
      }
      StringTokenizer st = new StringTokenizer (elemNames, " \t\n\r", false);
      Object junk = new Object ();
      while (st.hasMoreTokens ()) 
      {
        String tok = st.nextToken ();
        elements.put (tok, junk); // just stick it in there basically
      }
    }
    
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Set the script data for this extension NS. If srcURL is !null then
     * the script body is read from that URL. If not the scriptSrc is used
     * as the src. This method does not actually execute anything - that's
     * done when the component is first hit by the user by an element or 
     * a function call.
     *
     * @param lang      language of the script.
     * @param srcURL    value of src attribute (if any) - treated as a URL
     *                  or a classname depending on the value of lang. If
     *                  srcURL is not null, then scriptSrc is ignored.
     * @param scriptSrc the actual script code (if any)
     */
    public void setScript (String lang, String srcURL, String scriptSrc) 
    {
      this.scriptLang = lang;
      this.scriptSrcURL = srcURL;
      this.scriptSrc = scriptSrc;
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Tests whether a certain function name is known within this namespace.
     *
     * @param function name of the function being tested
     *
     * @return true if its known, false if not.
     */
    public boolean isFunctionAvailable (String function) 
    {
      return (functions.get (function) != null);
    }
    
    /**
     * Tests whether a certain element name is known within this namespace.
     *
     * @param function name of the function being tested
     *
     * @return true if its known, false if not.
     */
    public boolean isElementAvailable (String element) 
    {
      return (elements.get (element) != null);
    }
  
  
    Hashtable m_cachedMethods = null;
    
    /**
     * call the named method on the object that was loaded by eval. 
     * The method selection stuff is very XSLT-specific, hence the
     * custom engine.
     *
     * @param object ignored - should always be null
     */
    public Object callJava (Object object, String method, Object[] args, 
                            Object methodKey) 
      throws BSFException
    {
      // if the function name has a "." in it, then its a static
      // call with the args being arguments to the call. If it 
      // does not, then its a method call on args[0] with the rest
      // of the args as the arguments to the call
      int dotPos = method.lastIndexOf (".");
      Object[] methodArgs = null;
      boolean isNew = false;
      if (dotPos == -1) 
      {
        methodArgs = args;
        object = args[0];
        if (args.length > 1) 
        {
          methodArgs = new Object[args.length-1];
          System.arraycopy (args, 1, methodArgs, 0, args.length - 1);
        }
        else
          methodArgs = null;
      }
      else 
      {
        String className = method.substring (0, dotPos);
        method = method.substring (dotPos+1);
        methodArgs = args;
        isNew = method.equals ("new");
        try 
        {
          if(null == object)
            object = Class.forName (className);
        }
        catch (ClassNotFoundException e) 
        {
          throw new BSFException(1, "unable to load class '" + 
            className + "'", e);
        }
      }
      
      if((null != m_cachedMethods) && !isNew && (null != object))
      {
        try
        {
          Method thisMethod = (Method)m_cachedMethods.get(methodKey);
          if(null != thisMethod)
          {
            return thisMethod.invoke (object, methodArgs);
          }
        }
        catch(Exception e)
        {
          // try again below...
        }
      
      }
  
      // determine the argument types as they are given
      Class[] argTypes = null;
      if (methodArgs != null) 
      {
        argTypes = new Class[methodArgs.length];
        for (int i = 0; i < argTypes.length; i++) 
        {
          argTypes[i] = (methodArgs[i]!=null) ? methodArgs[i].getClass() : null;
        }
      }
  
      // try to find the method and run it, taking into account the special
      // type conversions we want. If an arg is a Double, we first try with
      // double and then with Double. Same for Boolean/boolean. This is done
      // wholesale tho - that is, if there are two Double args both are
      // tried double first and then Double.
      boolean done = false;
      boolean toggled = false;
      try 
      {
        while (!done) 
        {
          if (methodArgs == null) 
          {
            done = true; // nothing to retry - do as-is or give up
          }
          else 
          {
            if (!toggled) 
            {
              for (int i = 0; i < argTypes.length; i++) 
              {
                Class cl = argTypes[i];
                if (cl != null) 
                {
                  if (cl == Double.class) 
                  {
                    cl = double.class;
                  }
                  if (cl == Float.class) 
                  {
                    cl = float.class;
                  }
                  else if (cl == Boolean.class) 
                  {
                    cl = boolean.class;
                  }
                  else if (cl == Byte.class) 
                  {
                    cl = byte.class;
                  }
                  else if (cl == Character.class) 
                  {
                    cl = char.class;
                  }
                  else if (cl == Short.class) 
                  {
                    cl = short.class;
                  }
                  else if (cl == Integer.class) 
                  {
                    cl = int.class;
                  }
                  else if (cl == Long.class) 
                  {
                    cl = long.class;
                  }
                  argTypes[i] = cl;
                }
              }
              toggled = true;
            }
            else 
            {
              for (int i = 0; i < argTypes.length; i++) 
              {
                Class cl = argTypes[i];
                if (cl != null) 
                {
                  if (cl == double.class) 
                  {
                    cl = Double.class;
                  }
                  if (cl == float.class) 
                  {
                    cl = Float.class;
                  }
                  else if (cl == boolean.class) 
                  {
                    cl = Boolean.class;
                  }
                  else if (cl == byte.class) 
                  {
                    cl = Byte.class;
                  }
                  else if (cl == char.class) 
                  {
                    cl = Character.class;
                  }
                  else if (cl == short.class) 
                  {
                    cl = Short.class;
                  }
                  else if (cl == int.class) 
                  {
                    cl = Integer.class;
                  }
                  else if (cl == long.class) 
                  {
                    cl = Long.class;
                  }
                  argTypes[i] = cl;
                }
              }
              done = true;
            }
          }
          
          // now find method with the right signature, call it and return 
result.
          try 
          {
            if (isNew) 
            {
              // if its a "new" call then need to find and invoke a constructor
              // otherwise find and invoke the appropriate method. The method
              // searching logic is the same of course.
              Constructor c =
                             ReflectionUtils.getConstructor ((Class) object, 
argTypes);
              Object obj = c.newInstance (methodArgs);
              return obj;
            }
            else 
            {
              Method m = ReflectionUtils.getMethod (object, method, argTypes);
              Object returnObj = m.invoke (object, methodArgs);
              if(!isNew)
              {
                if(null == m_cachedMethods)
                  m_cachedMethods = new Hashtable();
                m_cachedMethods.put(methodKey, m);
              }
              return returnObj;
            }
          }
          catch (NoSuchMethodException e) 
          {
            // ignore if not done looking
            if (done) 
            {
              throw e;
            }
          }
        }
      }
      catch (Exception e) 
      {
        Throwable t = (e instanceof InvocationTargetException) ?
                      ((InvocationTargetException)e).getTargetException () :
                      null;
        throw new BSFException (BSFException.REASON_OTHER_ERROR,
          "method call/new failed: " + e +
          ((t==null)?"":(" target exception: "+t)), t);
      }
      // should not get here
      return null;
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Process a call to a function.
     *
     * @param funcName Function name.
     * @param args     The arguments of the function call.
     *
     * @return the return value of the function evaluation.
     *
     * @exception XSLProcessorException thrown if something goes wrong 
     *            while running the extension handler.
     * @exception MalformedURLException if loading trouble
     * @exception FileNotFoundException if loading trouble
     * @exception IOException           if loading trouble
     * @exception SAXException          if parsing trouble
     */
    public Object callFunction (String funcName, 
                                Vector args, 
                                Object methodKey, Class javaClass)
      throws SAXException 
    {
      /*
      if (!componentStarted) 
      {
        startupComponent (javaClass);
      }
      */
  
      boolean isJava = false;
      try 
      {
        com.ibm.bsf.BSFEngine e;
        Object[] argArray;
        int argStart;
        
        if(null == mgr)
        {
          mgr = new com.ibm.bsf.BSFManager ();
        }
  
        // we want to use the xslt-javaclass engine to handle the javaclass
        // case 'cause of the funky method selection rules. That engine 
        // expects the first arg to be the object on which to make the call.
        boolean isCTorCall = false;
        if (scriptLang.equals ("javaclass")) 
        {
          isJava = true;
          isCTorCall = funcName.equals("new");
          e = mgr.loadScriptingEngine ("xslt-javaclass");
          if(isCTorCall)
          {
            argArray = new Object[args.size ()];
            argStart = 0;
            funcName = this.classObject.getName()+".new";
            javaObject = null;
            hasCalledCTor = true;
          }
          else
          {
            if(!hasCalledCTor)
            {
              if(null == javaObject)
              {
                javaObject = this.classObject.newInstance();
              }
              
              argArray = new Object[args.size () + 1];
              
              argArray[0] = javaObject;
              argStart = 1;
              // argArray = new Object[args.size ()];
              // argStart = 0;
            }
            else
            {
              argArray = new Object[args.size ()];
              argStart = 0;
            }
          }
        }
        else 
        {
          e = ((com.ibm.bsf.BSFManager)mgr).loadScriptingEngine (scriptLang);
          argArray = new Object[args.size ()];
          argStart = 0;
        }
  
        // convert the xobject args to their object forms
        for (int i = 0; i < args.size (); i++) 
        {
          Object o = args.elementAt (i);
          argArray[i+argStart] = 
                                (o instanceof XObject) ? ((XObject)o).object () 
: o;
        }
        
        if(isJava)
          return callJava(javaObject, funcName, argArray, methodKey);
        else
          return e.call (null, funcName, argArray);
      }
      catch (Exception e) 
      {
        String msg = e.getMessage();
        if(null != msg)
        {
          if(msg.startsWith("Stopping after fatal error:"))
          {
            msg = msg.substring("Stopping after fatal error:".length());
          }
          System.out.println("Call to extension function failed: "+msg);
        }
        else
        {
          // Should probably make a TRaX Extension Exception.
          throw new SAXException ("Extension not found");
        }
      }
      return new XNull();
    }
  
    /////////////////////////////////////////////////////////////////////////
    // Private/Protected Functions
    /////////////////////////////////////////////////////////////////////////
    
    /**
     * Tell if we've already initialized the bsf engine.
     */
    protected static boolean bsfInitialized = false;
  
    /**
     * Start the component up by executing any script that needs to run
     * at startup time. This needs to happen before any functions can be
     * called on the component. 
     * 
     * @exception XPathProcessorException if something bad happens.
     */
    protected void startupComponent (TransformerImpl transformer,
                                     Class classObj) 
      throws  SAXException 
    {
      if(!bsfInitialized)
      {
        synchronized(com.ibm.bsf.BSFManager.class)
        {
          bsfInitialized = true;
          com.ibm.bsf.BSFManager.registerScriptingEngine ("xslt-javaclass",
                                                          
"org.apache.xalan.extensions.XSLTJavaClassEngine",
                                                          new String[0]);
        }
      }
  
      // special case the javaclass engine - the scriptSrcURL is 
      // the class name to run. If it starts with class: then use the
      // class object with that name instead of init'ing it as the
      // target of the calls later
      if(null != classObj)
      {
        classObject = classObj;
        if (scriptSrcURL.startsWith ("class:")) 
        {
          javaObject = classObj;
        }
        return;
      }
      else
      {
        if (scriptLang.equals ("javaclass") && (scriptSrcURL != null)) 
        {
          try 
          {
            String cname = scriptSrcURL;
            boolean isClass = false;
            if (scriptSrcURL.startsWith ("class:")) 
            {
              cname = scriptSrcURL.substring (6);
              isClass = true;
            }
            classObject = Class.forName (cname);
            if (isClass) 
            {
              javaObject = classObject;
            }
            else
            {
              // We'll only do this if they haven't called a ctor.
              // javaObject = classObject.newInstance ();
            }
            componentStarted = true;
            return;
          }
          catch (Exception e) 
          {
            // System.out.println("Extension error: "+e.getMessage ());
            throw new SAXException (e.getMessage (), e);
          }
        }
      }
  
      // if scriptSrcURL is specified read it off
      if (scriptSrcURL != null) 
      {
        throw new SAXException ("src attr not supported (yet)");
      }
  
      if (scriptSrc == null) 
      {
        return;
      }
      
      if(null == mgr)
        mgr = new com.ibm.bsf.BSFManager ();
  
      // evaluate the src to load whatever content is in that string to 
      // the engines
      try 
      {
        ((com.ibm.bsf.BSFManager)mgr).exec (scriptLang, "LotusXSLScript", -1, 
-1, scriptSrc);
      }
      catch (com.ibm.bsf.BSFException bsfe) 
      {
        throw new SAXException (bsfe.getMessage (), bsfe);
      }
      componentStarted = true;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/extensions/ExtensionNSHandler.java
  
  Index: ExtensionNSHandler.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.extensions;
  
  import java.util.Hashtable;
  import java.util.Vector;
  import java.util.StringTokenizer;
  import java.net.URL;
  import java.net.MalformedURLException;
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import org.w3c.dom.CharacterData;
  import org.w3c.dom.Attr;
  import org.w3c.dom.NodeList;
  import org.xml.sax.SAXException;
  import org.xml.sax.SAXParseException;
  import org.xml.sax.ErrorHandler;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.templates.Stylesheet;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.xpath.XPathProcessorException;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Represents an extension namespace. Provides functions
   * to call into the extension via both element syntax and function
   * syntax. Extends XPath's extension function capability to a full
   * namespace extension model.
   *
   * @author Sanjiva Weerawarana ([EMAIL PROTECTED])
   */
  public class ExtensionNSHandler extends ExtensionFunctionHandler
  {
    TransformerImpl xslp;        // xsl transformer for whom I'm working
    Hashtable elements = new Hashtable (); // ext. elements of this namespace
    boolean componentDescLoaded; // true when info from the component desc
    // has been loaded. This gets set as soon
    // as any of the info has been specified.
    // If this is false, when processElement or
    // processFunction is called it will use the
    // namespace URI as a URL and try to load
    // that location as the component desc.
  
    /////////////////////////////////////////////////////////////////////////
    // Constructors
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Construct a new extension namespace handler for a given extension NS.
     * This doesn't do anything - just hang on to the namespace URI.
     *
     * @param xslp         handle to the XSL transformer that I'm working for
     * @param namespaceUri the extension namespace URI that I'm implementing
     */
    public ExtensionNSHandler (String namespaceUri)
    {
      super (namespaceUri);
      this.xslp = xslp;
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Construct a new extension namespace handler given all the information
     * needed.
     *
     * @param xslp         handle to the XSL transformer that I'm working for
     * @param namespaceUri the extension namespace URI that I'm implementing
     * @param elemNames    string containing list of elements of extension NS
     * @param funcNames    string containing list of functions of extension NS
     * @param lang         language of code implementing the extension
     * @param srcURL       value of src attribute (if any) - treated as a URL
     *                     or a classname depending on the value of lang. If
     *                     srcURL is not null, then scriptSrc is ignored.
     * @param scriptSrc    the actual script code (if any)
     */
    public ExtensionNSHandler (TransformerImpl xslp, String namespaceUri,
                               String elemNames, String funcNames,
                               String lang, String srcURL, String src)
    {
      super (namespaceUri, funcNames, lang, srcURL, src);
      this.xslp = xslp;
      setElements (elemNames);
      componentDescLoaded = true;
    }
  
    /////////////////////////////////////////////////////////////////////////
    // Main API
    /////////////////////////////////////////////////////////////////////////
  
    /*
    * Set function local parts of extension NS. Super does the work; I
    * just record that a component desc has been loaded.
    *
    * @param functions whitespace separated list of function names defined
    *        by this extension namespace.
    */
    public void setFunctions (String funcNames)
    {
      super.setFunctions (funcNames);
      componentDescLoaded = true;
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Set the script data for this extension NS. Deferred to super for
     * actual work - I only record that a component desc has been loaded.
     *
     * @param lang      language of the script.
     * @param srcURL    value of src attribute (if any) - treated as a URL
     *                  or a classname depending on the value of lang. If
     *                  srcURL is not null, then scriptSrc is ignored.
     * @param scriptSrc the actual script code (if any)
     */
    public void setScript (String lang, String srcURL, String scriptSrc)
    {
      super.setScript (lang, srcURL, scriptSrc);
      componentDescLoaded = true;
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Set element local parts of extension NS.
     *
     * @param elemNames whitespace separated list of element names defined
     *        by this extension namespace.
     */
    public void setElements (String elemNames)
    {
      if (elemNames == null)
      {
        return;
      }
      StringTokenizer st = new StringTokenizer (elemNames, " \t\n\r", false);
      Object junk = new Object ();
      while (st.hasMoreTokens ())
      {
        String tok = st.nextToken ();
        elements.put (tok, junk); // just stick it in there basically
      }
      componentDescLoaded = true;
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Tests whether a certain element name is known within this namespace.
     *
     * @param element name of the element being tested
     *
     * @return true if its known, false if not.
     */
    public boolean isElementAvailable (String element)
    {
      return (elements.get (element) != null);
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Process a call to this extension namespace via an element. As a side
     * effect, the results are sent to the TransformerImpl's result tree.
     *
     * @param localPart      Element name's local part.
     * @param element        The extension element being processed.
     * @param transformer      Handle to TransformerImpl.
     * @param stylesheetTree The compiled stylesheet tree.
     * @param mode           The current mode.
     * @param sourceTree     The root of the source tree (but don't assume
     *                       it's a Document).
     * @param sourceNode     The current context node.
     *
     * @exception XSLProcessorException thrown if something goes wrong
     *            while running the extension handler.
     * @exception MalformedURLException if loading trouble
     * @exception FileNotFoundException if loading trouble
     * @exception IOException           if loading trouble
     * @exception SAXException          if parsing trouble
     */
    public void processElement (String localPart, Element element,
                                TransformerImpl transformer,
                                Stylesheet stylesheetTree,
                                Node sourceTree, Node sourceNode, QName mode,
                                Class classObj, Object methodKey)
      throws SAXException, IOException
    {
      if (!componentStarted)
      {
        try
        {
          startupComponent (transformer, classObj);
        }
        catch (XPathProcessorException e)
        {
          // e.printStackTrace ();
          throw new SAXException (e.getMessage (), e);
        }
      }
  
      Object result = null;
      XSLProcessorContext xpc = new XSLProcessorContext (transformer, 
                                                         stylesheetTree,
                                                         sourceTree, 
                                                         sourceNode, 
                                                         mode);
      try
      {
        Vector argv = new Vector (2);
        argv.addElement (xpc);
        argv.addElement (element);
        result = super.callFunction (localPart, argv, methodKey, classObj);
      }
      catch (XPathProcessorException e)
      {
        // e.printStackTrace ();
        throw new SAXException (e.getMessage (), e);
      }
  
      if (result != null)
      {
        xpc.outputToResultTree (stylesheetTree, result);
      }
    }
  
    /////////////////////////////////////////////////////////////////////////
    // Private/Protected Functions
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Start the component up by executing any script that needs to run
     * at startup time. This needs to happen before any functions can be
     * called on the component.
     *
     * @exception XPathProcessorException if something bad happens.
     */
    protected void startupComponent (TransformerImpl transformer, 
                                     Class classObj) 
      throws  SAXException
    {
      if(!bsfInitialized)
      {
        synchronized(com.ibm.bsf.BSFManager.class)
        {
          bsfInitialized = true;
          com.ibm.bsf.BSFManager.registerScriptingEngine ("xslt-javaclass",
                                                          
"org.apache.xalan.extensions.XSLTJavaClassEngine",
                                                          new String[0]);
        }
      }
  
      if (!componentDescLoaded)
      {
        try
        {
          loadComponentDescription ();
        }
        catch (Exception e)
        {
          throw new XPathProcessorException (e.getMessage (), e);
        }
      }
      super.startupComponent (transformer, classObj);
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * Load the component spec for this extension namespace taking the URI
     * of this namespace as the URL to read from.
     *
     * @exception XSLProcessorException if something bad happens.
     * @exception MalformedURLException if loading trouble
     * @exception FileNotFoundException if loading trouble
     * @exception IOException           if loading trouble
     * @exception SAXException          if parsing trouble
     */
    private void loadComponentDescription ()
      throws  SAXException
    {
      // first try treaing the URI of the extension as a fully qualified
      // class name; if it works then go with treating this an extension
      // implemented in "javaclass" for with that class being the srcURL.
      // forget about setting elements and functions in that case - so if
      // u do extension-{element,function}-available then u get false,
      // but that's ok.
      try {
        String cname = namespaceUri.startsWith ("class:") ?
                         namespaceUri.substring (6) : namespaceUri;
        Class.forName (cname); // does it load?
        setScript ("javaclass", namespaceUri, null);
        componentDescLoaded = true;
        return;
      } catch (Exception e) {
        // oops, it failed .. ok, so this path ain't gonna pan out. shucks.
      }
  
      // parse the document at the URI of the extension, if any
      URL url = null; // xslp.getURLFromString(namespaceUri,
                       //               
xslp.m_stylesheetRoot.getBaseIdentifier());
      // System.out.println("Extension URI: "+url.toString());
      org.apache.xalan.xpath.XPathContext liaison = xslp.getXPathContext();
  
      Element componentElement = null;
      /*
      try
      {
      */
      // liaison.parse(new InputSource(url.toString()));
      // Document compSpec = liaison.getDocument();
      Document compSpec = null;
      componentElement = compSpec.getDocumentElement ();
  
      // determine the functions and elements of this component
      setElements (componentElement.getAttribute ("elements"));
      setFunctions (componentElement.getAttribute ("functions"));
  
      // is there an lxslt:script element child? [NOTE THAT THIS IS NOT
      // PROPER NAMESPACE-WISE .. I'll FIX IT LATER. .. Sanjiva 8/20/99.]
      NodeList nl = componentElement.getElementsByTagName ("lxslt:script");
      switch (nl.getLength ())
      {
      case 0:
        break;
      case 1:
        Element scriptElem = (Element) nl.item (0);
        String lang = scriptElem.getAttribute ("lang");
        Attr srcURLAttr = scriptElem.getAttributeNode ("src");
        String srcURL = (srcURLAttr == null) ? null : srcURLAttr.getValue ();
        String src = getScriptString (scriptElem);
        setScript (lang, srcURL, src);
        break;
      default:
        throw new SAXException ("too many <script>s in component");
      }
      componentDescLoaded = true;
      /*
      }
      catch(org.xml.sax.SAXException se)
      {
  
      }
      catch(java.net.UnknownHostException uhe)
      {
  
      }
      */
    }
  
    /////////////////////////////////////////////////////////////////////////
  
    /**
     * extract the text nodes and CDATA content children of the given
     * elem and return as a string. Any other types of node children
     * are ignored
     *
     * @param elem element whose text and cdata children are to be
     *        concatenated together.
     *
     * @return string resulting from concatanating the text/cdata child
     *         nodes' values.
     */
    private String getScriptString (Element elem)
    {
      StringBuffer strBuf = new StringBuffer();
      for (Node n = elem.getFirstChild (); n != null; n = n.getNextSibling ())
      {
        switch (n.getNodeType())
        {
        case Node.TEXT_NODE:
        case Node.CDATA_SECTION_NODE:
          strBuf.append(((CharacterData) n).getData());
          break;
        default:
          break;
        }
      }
      return strBuf.toString();
    }
  
  
    /**
     * Implement SAX error handler for default reporting.
     */
    class ExtErrorHandler implements ErrorHandler
    {
      String m_xmlID = null;
  
      public ExtErrorHandler(String identifier)
      {
        m_xmlID = identifier;
      }
  
      /**
       * Receive notification of a warning.
       *
       * <p>SAX parsers will use this method to report conditions that
       * are not errors or fatal errors as defined by the XML 1.0
       * recommendation.  The default behaviour is to take no action.</p>
       *
       * <p>The SAX parser must continue to provide normal parsing events
       * after invoking this method: it should still be possible for the
       * application to process the document through to the end.</p>
       *
       * @param exception The warning information encapsulated in a
       *                  SAX parse exception.
       * @exception org.xml.sax.SAXException Any SAX exception, possibly
       *            wrapping another exception.
       * @see org.xml.sax.SAXParseException
       */
      public void warning (SAXParseException exception)
        throws SAXException
      {
        System.out.println("Parser warning: "+exception.getMessage());
      }
  
  
      /**
       * Receive notification of a recoverable error.
       *
       * <p>This corresponds to the definition of "error" in section 1.2
       * of the W3C XML 1.0 Recommendation.  For example, a validating
       * parser would use this callback to report the violation of a
       * validity constraint.  The default behaviour is to take no
       * action.</p>
       *
       * <p>The SAX parser must continue to provide normal parsing events
       * after invoking this method: it should still be possible for the
       * application to process the document through to the end.  If the
       * application cannot do so, then the parser should report a fatal
       * error even if the XML 1.0 recommendation does not require it to
       * do so.</p>
       *
       * @param exception The error information encapsulated in a
       *                  SAX parse exception.
       * @exception org.xml.sax.SAXException Any SAX exception, possibly
       *            wrapping another exception.
       * @see org.xml.sax.SAXParseException
       */
      public void error (SAXParseException exception)
        throws SAXException
      {
        System.out.println("Parser error: "+exception.getMessage());
      }
  
      /**
       * Receive notification of a non-recoverable error.
       *
       * <p>This corresponds to the definition of "fatal error" in
       * section 1.2 of the W3C XML 1.0 Recommendation.  For example, a
       * parser would use this callback to report the violation of a
       * well-formedness constraint.</p>
       *
       * <p>The application must assume that the document is unusable
       * after the parser has invoked this method, and should continue
       * (if at all) only for the sake of collecting addition error
       * messages: in fact, SAX parsers are free to stop reporting any
       * other events once this method has been invoked.</p>
       *
       * @param exception The error information encapsulated in a
       *                  SAX parse exception.
       * @exception org.xml.sax.SAXException Any SAX exception, possibly
       *            wrapping another exception.
       * @see org.xml.sax.SAXParseException
       */
      public void fatalError (SAXParseException exception)
        throws SAXException
      {
      }
  
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/extensions/ExtensionsTable.java
  
  Index: ExtensionsTable.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.extensions;
  
  import java.util.Hashtable;
  import java.util.Vector;
  import org.apache.xalan.xpath.XNull;
  import org.apache.xalan.xpath.XPathProcessorException;
  
  public class ExtensionsTable
  {
    /**
     * <meta name="usage" content="internal"/>
     * Table of extensions that may be called from the expression language 
     * via the call(name, ...) function.  Objects are keyed on the call 
     * name.
     * @see extensions.html.
     */
    public Hashtable m_extensionFunctionNamespaces = new Hashtable();
    
    /**
     * Get an ExtensionNSHandler object that represents the 
     * given namespace.
     * @param extns A valid extension namespace.
     */
    public ExtensionNSHandler get(String extns)
    {
      return (ExtensionNSHandler)m_extensionFunctionNamespaces.get(extns);
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * Register an extension namespace handler. This handler provides
     * functions for testing whether a function is known within the 
     * namespace and also for invoking the functions.
     *
     * @param uri the URI for the extension.
     * @param extNS the extension handler.
     */
    public void addExtensionNamespace (String uri,
                                       ExtensionFunctionHandler extNS) {
      m_extensionFunctionNamespaces.put (uri, extNS);
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Register an element extension namespace handler. This handler provides
     * functions for testing whether a function is known within the 
     * namespace and also for invoking the functions.
     *
     * @param uri the URI for the extension.
     * @param extNS the extension handler.
     */
    public void addExtensionElementNamespace (String uri,
                                              ExtensionFunctionHandler extNS) {
      m_extensionFunctionNamespaces.put (uri, extNS);
    }
  
    /**
     * Execute the function-available() function.
     * @param ns       the URI of namespace in which the function is needed
     * @param funcName the function name being tested
     *
     * @return whether the given function is available or not.
     */
    public boolean functionAvailable (String ns, String funcName) 
    {
      boolean isAvailable = false;
      if (null != ns) 
      {
        ExtensionFunctionHandler extNS = 
                                        (ExtensionFunctionHandler) 
m_extensionFunctionNamespaces.get (ns);
        if (extNS != null) 
        {
          isAvailable = extNS.isFunctionAvailable (funcName);
        }
      }
      // System.err.println (">>> functionAvailable (ns=" + ns + 
      //                    ", func=" + funcName + ") = " + isAvailable);
      return isAvailable;
    }
    
    /**
     * Execute the element-available() function.
     * @param ns       the URI of namespace in which the function is needed
     * @param funcName the function name being tested
     *
     * @return whether the given function is available or not.
     */
    public boolean elementAvailable (String ns, String funcName) 
    {
      boolean isAvailable = false;
      if (null != ns) 
      {
        ExtensionFunctionHandler extNS = 
                                        (ExtensionFunctionHandler) 
m_extensionFunctionNamespaces.get (ns);
        if (extNS != null) 
        {
          isAvailable = extNS.isElementAvailable (funcName);
        }
      }
      // System.err.println (">>> elementAvailable (ns=" + ns + 
      //                    ", func=" + funcName + ") = " + isAvailable);
      return isAvailable;
    }
  
  
    /**
     * Handle an extension function.
     * @param ns       the URI of namespace in which the function is needed
     * @param funcName the function name being called
     * @param argVec   arguments to the function in a vector
     *
     * @return result of executing the function
     */
    public Object extFunction (String ns, String funcName, Vector argVec, 
                               Object methodKey)
      throws org.xml.sax.SAXException
    {
      if(null == m_extensionFunctionNamespaces.get 
("http://xml.apache.org/xslt/java";))
      {
        // register the java namespace as being implemented by the 
        // xslt-javaclass engine. Note that there's no real code
        // per se for this extension as the functions carry the 
        // object on which to call etc. and all the logic of breaking
        // that up is in the xslt-javaclass engine.
        String uri = "http://xml.apache.org/xslt/java";;
        ExtensionFunctionHandler fh = new ExtensionFunctionHandler (uri, null, 
"xslt-javaclass", null, null);
        
        addExtensionNamespace (uri, fh);   
      }
      if(null == m_extensionFunctionNamespaces.get 
("http://xsl.lotus.com/java";))
      {
        // register the java namespace as being implemented by the 
        // xslt-javaclass engine. Note that there's no real code
        // per se for this extension as the functions carry the 
        // object on which to call etc. and all the logic of breaking
        // that up is in the xslt-javaclass engine.
        String uri = "http://xsl.lotus.com/java";;
        ExtensionFunctionHandler fh = new ExtensionFunctionHandler (uri, null, 
"xslt-javaclass", null, null);
        
        addExtensionNamespace (uri, fh);   
      }
  
      Object result = null;
      if (null != ns)
      {
        ExtensionFunctionHandler extNS = (ExtensionFunctionHandler)
                                          m_extensionFunctionNamespaces.get 
(ns);
  
        // if not found try to auto declare this extension namespace:
        // try treaing the URI of the extension as a fully qualified
        // class name; if it works then go with treating this an extension
        // implemented in "javaclass" for with that class being the srcURL.
        // forget about setting functions in that case - so if u do
        // extension-function-available then u get false, but that's ok.
        if (extNS == null) 
        {
          try 
          {
            // Scott: I don't think this is doing anything for us.
            // String cname = ns.startsWith ("class:") ? ns.substring (6) : ns;
            // Class.forName (cname); // does it load?
            extNS = new ExtensionFunctionHandler (ns, null, "javaclass",
                                                  ns, null);
            addExtensionNamespace (ns, extNS);
          }
          catch (Exception e) 
          {
            // oops, it failed .. ok, so this path ain't gonna pan out. shucks.
          }
        }
  
        if (extNS != null)
        {
          try
          {
            result = extNS.callFunction (funcName, argVec, methodKey, null);
          }
          catch (Exception e)
          {
            // e.printStackTrace();
            // throw new XPathProcessorException ("Extension function '" + ns +
            //  ":" + funcName +
            //  "', threw exception: " + e, e);
            String msg = e.getMessage();
            if(null != msg)
            {
              if(msg.startsWith("Stopping after fatal error:"))
              {
                msg = msg.substring("Stopping after fatal error:".length());
              }
              System.out.println("Call to extension function failed: "+msg);
              result = new XNull();
            }
          }
        }
        else 
        {
          throw new XPathProcessorException ("Extension function '" + ns +
            ":" + funcName + "' is unknown");
        }
      }
      return result;
    }
    
    /**
    * The table of extension namespaces.
    * @serial
    */
    // public Hashtable m_extensionNamespaces = new Hashtable();
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/extensions/XSLProcessorContext.java
  
  Index: XSLProcessorContext.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.extensions;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.traversal.NodeIterator;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.transformer.ResultTreeHandler;
  import org.apache.xalan.templates.Stylesheet;
  import org.apache.xalan.utils.QName;
  import org.xml.sax.SAXException;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  import org.apache.xalan.xpath.XBoolean;
  import org.apache.xalan.xpath.XNumber;
  import org.apache.xalan.xpath.XRTreeFrag;
  import org.apache.xalan.xpath.XNodeSet;
  import org.apache.xalan.xpath.XPathContext;
  
  // import org.apache.xalan.xslt.*;
  
  /**
   * <meta name="usage" content="general"/>
   * Provides transformer context to be passed to an extension element.
   *
   * @author Sanjiva Weerawarana ([EMAIL PROTECTED])
   */
  public class XSLProcessorContext {
    
    /**
     * Create a processor context to be passed to an extension.
     * (Notice it is a package-only constructor).
     */
    XSLProcessorContext (TransformerImpl transformer,
                         Stylesheet stylesheetTree,
                         Node sourceTree, Node sourceNode, QName mode) 
    {
      this.transformer = transformer;
      this.stylesheetTree = stylesheetTree;
      this.mode = mode;
      this.sourceTree = sourceTree;
      this.sourceNode = sourceNode;
    }
    
    private TransformerImpl transformer;
    
    /**
     * Get the transformer.
     */
    public TransformerImpl getTransformer()
    {
      return transformer;
    }
    
    private Stylesheet stylesheetTree;
    
    /**
     * Get the Stylesheet being executed.
     */
    public Stylesheet getStylesheet()
    {
      return stylesheetTree;
    }
    
    private Node sourceTree;
    
    /**
     * Get the root of the source tree being executed.
     */
    public Node getSourceTree()
    {
      return sourceTree;
    }
    
    private Node sourceNode;
    
    /**
     * Get the current context node.
     */
    public Node getContextNode()
    {
      return sourceNode;
    }
    
    private QName mode;
    
    /**
     * Get the current mode being executed.
     */
    public QName getMode()
    {
      return mode;
    }
  
    /**
     * Output an object to the result tree by doing the right conversions.
     * This is public for access by extensions.
     *
     * @param obj the Java object to output. If its of an X<something> type
     *        then that conversion is done first and then sent out.
     */
    public void outputToResultTree (Stylesheet stylesheetTree, Object obj)
      throws SAXException,
      java.net.MalformedURLException,
      java.io.FileNotFoundException,
      java.io.IOException
    {
      ResultTreeHandler rtreeHandler = transformer.getResultTreeHandler();
      
      XObject value;
      // Make the return object into an XObject because it
      // will be easier below.  One of the reasons to do this
      // is to keep all the conversion functionality in the
      // XObject classes.
      if(obj instanceof XObject)
      {
        value = (XObject)obj;
      }
      else if(obj instanceof String)
      {
        value = new XString((String)obj);
      }
      else if(obj instanceof Boolean)
      {
        value = new XBoolean(((Boolean)obj).booleanValue());
      }
      else if(obj instanceof Double)
      {
        value = new XNumber(((Double)obj).doubleValue());
      }
      else if(obj instanceof DocumentFragment)
      {
        value = new XRTreeFrag((DocumentFragment)obj);
      }
      else if(obj instanceof Node)
      {
        value = new XNodeSet((Node)obj);
      }
      else if(obj instanceof NodeIterator)
      {
        value = new XNodeSet((NodeIterator)obj);
      }
      else
      {
        value = new XString(obj.toString());
      }
  
      int type = value.getType();
      String s;
      switch(type)
      {
      case XObject.CLASS_BOOLEAN:        case XObject.CLASS_NUMBER:        case 
XObject.CLASS_STRING:
        s = value.str();
        rtreeHandler.characters(s.toCharArray(), 0, s.length());
        break;
      case XObject.CLASS_NODESET:          // System.out.println(value);
        NodeIterator nl = value.nodeset();
        Node pos;
        while(null != (pos = nl.nextNode()))
        {
          Node top = pos;
          while(null != pos)
          {
            rtreeHandler.flushPending();
            rtreeHandler.cloneToResultTree(stylesheetTree, pos, false, false,
                              true);
            Node nextNode = pos.getFirstChild();
            while(null == nextNode)
            {
              if(Node.ELEMENT_NODE == pos.getNodeType())
              {
                rtreeHandler.endElement("", "", pos.getNodeName());
              }
              if(top == pos)
                break;
              nextNode = pos.getNextSibling();
              if(null == nextNode)
              {
                pos = pos.getParentNode();
                if(top == pos)
                {
                  if(Node.ELEMENT_NODE == pos.getNodeType())
                  {
                    rtreeHandler.endElement("", "", pos.getNodeName());
                  }
                  nextNode = null;
                  break;
                }
              }
            }
            pos = nextNode;
          }
        }
        break;
  
      case XObject.CLASS_RTREEFRAG:
        rtreeHandler.outputResultTreeFragment(value, 
                                              transformer.getXPathContext());
        break;
      }
    }
  
  
    /**
     * I need a "Node transformNode (Node)" method somewhere that the
     * user can call to process the transformation of a node but not
     * serialize out automatically. ????????????????
     *
     * Does ElemTemplateElement.executeChildTemplates() cut it? It sends
     * results out to the stream directly, so that could be a problem.
     */
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/extensions/XSLTJavaClassEngine.java
  
  Index: XSLTJavaClassEngine.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  package org.apache.xalan.extensions;
  
  import java.util.*;
  import java.io.*;
  import java.lang.reflect.*;
  
  import com.ibm.bsf.*;
  import com.ibm.bsf.util.BSFEngineImpl;
  
  import com.ibm.cs.util.ReflectionUtils;
  
  /**
   * <meta name="usage" content="internal"/>
   * This is a custom scripting engine for the XSLT processor's needs of calling
   * into Java objects. 
   *
   * @author   Sanjiva Weerawarana ([EMAIL PROTECTED])
   */
  
  public class XSLTJavaClassEngine extends BSFEngineImpl 
  {
    /**
     * This is used by an application to evaluate an object containing
     * some expression - clearly not possible for compiled code ..
     */
    public Object eval (String source, int lineNo, int columnNo, 
                        Object oscript) throws BSFException 
    {
      throw new BSFException (BSFException.REASON_UNSUPPORTED_FEATURE,
        "Java bytecode engine can't evaluate expressions");
    }
  
    /**
     * call the named method on the object that was loaded by eval. 
     * The method selection stuff is very XSLT-specific, hence the
     * custom engine.
     *
     * @param object ignored - should always be null
     */
    public Object call (Object object, String method, Object[] args) 
      throws BSFException
    {
      // if the function name has a "." in it, then its a static
      // call with the args being arguments to the call. If it 
      // does not, then its a method call on args[0] with the rest
      // of the args as the arguments to the call
      int dotPos = method.lastIndexOf (".");
      Object[] methodArgs = null;
      boolean isNew = false;
      if (dotPos == -1) 
      {
        object = args[0];
        if (args.length > 1) 
        {
          methodArgs = new Object[args.length-1];
          System.arraycopy (args, 1, methodArgs, 0, args.length - 1);
        }
      }
      else 
      {
        String className = method.substring (0, dotPos);
        method = method.substring (dotPos+1);
        methodArgs = args;
        isNew = method.equals ("new");
        try 
        {
          object = Class.forName (className);
        }
        catch (ClassNotFoundException e) 
        {
          throw new BSFException(1, "unable to load class '" + 
            className + "'", e);
        }
      }
  
      // determine the argument types as they are given
      Class[] argTypes = null;
      if (methodArgs != null) 
      {
        argTypes = new Class[methodArgs.length];
        for (int i = 0; i < argTypes.length; i++) 
        {
          argTypes[i] = (methodArgs[i]!=null) ? methodArgs[i].getClass() : null;
        }
      }
  
      // try to find the method and run it, taking into account the special
      // type conversions we want. If an arg is a Double, we first try with
      // double and then with Double. Same for Boolean/boolean. This is done
      // wholesale tho - that is, if there are two Double args both are
      // tried double first and then Double.
      boolean done = false;
      boolean toggled = false;
      try 
      {
        while (!done) 
        {
          if (methodArgs == null) 
          {
            done = true; // nothing to retry - do as-is or give up
          }
          else 
          {
            if (!toggled) 
            {
              for (int i = 0; i < argTypes.length; i++) 
              {
                Class cl = argTypes[i];
                if (cl != null) 
                {
                  if (cl == Double.class) 
                  {
                    cl = double.class;
                  }
                  if (cl == Float.class) 
                  {
                    cl = float.class;
                  }
                  else if (cl == Boolean.class) 
                  {
                    cl = boolean.class;
                  }
                  else if (cl == Byte.class) 
                  {
                    cl = byte.class;
                  }
                  else if (cl == Character.class) 
                  {
                    cl = char.class;
                  }
                  else if (cl == Short.class) 
                  {
                    cl = short.class;
                  }
                  else if (cl == Integer.class) 
                  {
                    cl = int.class;
                  }
                  else if (cl == Long.class) 
                  {
                    cl = long.class;
                  }
                  argTypes[i] = cl;
                }
              }
              toggled = true;
            }
            else 
            {
              for (int i = 0; i < argTypes.length; i++) 
              {
                Class cl = argTypes[i];
                if (cl != null) 
                {
                  if (cl == double.class) 
                  {
                    cl = Double.class;
                  }
                  if (cl == float.class) 
                  {
                    cl = Float.class;
                  }
                  else if (cl == boolean.class) 
                  {
                    cl = Boolean.class;
                  }
                  else if (cl == byte.class) 
                  {
                    cl = Byte.class;
                  }
                  else if (cl == char.class) 
                  {
                    cl = Character.class;
                  }
                  else if (cl == short.class) 
                  {
                    cl = Short.class;
                  }
                  else if (cl == int.class) 
                  {
                    cl = Integer.class;
                  }
                  else if (cl == long.class) 
                  {
                    cl = Long.class;
                  }
                  argTypes[i] = cl;
                }
              }
              done = true;
            }
          }
          
          // now find method with the right signature, call it and return 
result.
          try 
          {
            if (isNew) 
            {
              // if its a "new" call then need to find and invoke a constructor
              // otherwise find and invoke the appropriate method. The method
              // searching logic is the same of course.
              Constructor c =
                             ReflectionUtils.getConstructor ((Class) object, 
argTypes);
              Object obj = c.newInstance (methodArgs);
              return obj;
            }
            else 
            {
              Method m = ReflectionUtils.getMethod (object, method, argTypes);
              return m.invoke (object, methodArgs);
            }
          }
          catch (NoSuchMethodException e) 
          {
            // ignore if not done looking
            if (done) 
            {
              throw e;
            }
          }
        }
      }
      catch (Exception e) 
      {
        Throwable t = (e instanceof InvocationTargetException) ?
                      ((InvocationTargetException)e).getTargetException () :
                      null;
        throw new BSFException (BSFException.REASON_OTHER_ERROR,
          "method call/new failed: " + e +
          ((t==null)?"":(" target exception: "+t)), t);
      }
      // should not get here
      return null;
    }
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/extensions/extensions.dfPackage
  
  Index: extensions.dfPackage
  ===================================================================
  package idcowc6wt02wac6wt9osw;
  
  /**
  @version 2.0
  @physicalPackage
  @__modelType diagram 
  */
  class diagram {
  }/**
  @__tags
  @shapeType ClassDiagram 
  */
  class __tags {
  }/**
  @__options 
  */
  class __options {
  }/**
  @__positions 
  */
  class __positions {
  }
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/lib/Redirect.java
  
  Index: Redirect.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.lib;
  
  import java.util.*;
  import java.io.*;
  import java.net.URL;
  import org.w3c.dom.*;
  import org.xml.sax.ContentHandler;
  import org.apache.xml.serialize.OutputFormat;
  import org.apache.xalan.extensions.XSLProcessorContext;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.templates.StylesheetRoot;
  import org.apache.xalan.templates.ElemExtensionCall;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XPathAPI;
  
  /**
   * Implements three extension elements to allow an XSLT transformation to
   * redirect its output to multiple output files.
   * You must declare the Xalan namespace 
(xmlns:lxslt="http://xml.apache.org/xslt";),
   * a namespace for the extension prefix (such as 
xmlns:redirect="org.apache.xalan.xslt.extensions.Redirect"),
   * and declare the extension namespace as an extension 
(extension-element-prefixes="redirect").
   * You can either just use redirect:write, in which case the file will be
   * opened and immediately closed after the write, or you can bracket the
   * write calls by redirect:open and redirect:close, in which case the
   * file will be kept open for multiple writes until the close call is
   * encountered.  Calls can be nested.  Calls can take a 'file' attribute
   * and/or a 'select' attribute in order to get the filename.  If a select
   * attribute is encountered, it will evaluate that expression for a string
   * that indicates the filename.  If the string evaluates to empty, it will
   * attempt to use the 'file' attribute as a default.  Filenames can be 
relative
   * or absolute.  If they are relative, the base directory will be the same as
   * the base directory for the output document (setOutputFileName(outFileName) 
must
   * be called first on the processor when using the API).
   *
   * <p>Example:</p>
   * <PRE>
   * &lt;?xml version="1.0"?>
   * &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0";
   *                 xmlns:lxslt="http://xml.apache.org/xslt";
   *                 xmlns:redirect="org.apache.xalan.xslt.extensions.Redirect"
   *                 extension-element-prefixes="redirect">
   *
   *   &lt;xsl:template match="/">
   *     &lt;out>
   *       default output.
   *     &lt;/out>
   *     &lt;redirect:open file="doc3.out"/>
   *     &lt;redirect:write file="doc3.out">
   *       &lt;out>
   *         &lt;redirect:write file="doc1.out">
   *           &lt;out>
   *             doc1 output.
   *             &lt;redirect:write file="doc3.out">
   *               Some text to doc3
   *             &lt;/redirect:write>
   *           &lt;/out>
   *         &lt;/redirect:write>
   *         &lt;redirect:write file="doc2.out">
   *           &lt;out>
   *             doc2 output.
   *             &lt;redirect:write file="doc3.out">
   *               Some more text to doc3
   *               &lt;redirect:write select="doc/foo">
   *                 text for doc4
   *               &lt;/redirect:write>
   *             &lt;/redirect:write>
   *           &lt;/out>
   *         &lt;/redirect:write>
   *       &lt;/out>
   *     &lt;/redirect:write>
   *     &lt;redirect:close file="doc3.out"/>
   *   &lt;/xsl:template>
   *
   * &lt;/xsl:stylesheet>
   * </PRE>
   *
   * @author Scott Boag
   * @version 1.0
   * @see <a href="../../../../../../extensions.html#ex-redirect" 
target="_top">Example with Redirect extension</a>
   */
  public class Redirect
  {
    /**
     * List of formatter listeners indexed by filename.
     */
    protected Hashtable m_formatterListeners = new Hashtable ();
  
    /**
     * List of output streams indexed by filename.
     */
    protected Hashtable m_outputStreams = new Hashtable ();
  
    /**
     * Open the given file and put it in the XML, HTML, or Text formatter 
listener's table.
     */
    public void open(XSLProcessorContext context, Element elem)
      throws java.net.MalformedURLException,
             java.io.FileNotFoundException,
             java.io.IOException,
             org.xml.sax.SAXException
    {
      String fileName = getFilename(context, elem);
      Object flistener = m_formatterListeners.get(fileName);
      if(null == flistener)
      {
        String mkdirsExpr 
          = ((ElemExtensionCall)elem).getAttribute ("mkdirs", 
context.getContextNode(), 
                                                    context.getTransformer());
        boolean mkdirs = (mkdirsExpr != null)
                         ? (mkdirsExpr.equals("true") || 
mkdirsExpr.equals("yes")) : true;
          // ContentHandler fl = 
          makeFormatterListener(context, fileName, true, mkdirs);
          // fl.startDocument();
      }
    }
    
    /**
     * Write the evalutation of the element children to the given file. Then 
close the file
     * unless it was opened with the open extension element and is in the 
formatter listener's table.
     */
    public void write(XSLProcessorContext context, Element elem)
      throws java.net.MalformedURLException,
             java.io.FileNotFoundException,
             java.io.IOException,
             org.xml.sax.SAXException
    {
      String fileName = getFilename(context, elem);
      Object flObject = m_formatterListeners.get(fileName);
      ContentHandler formatter;
      boolean inTable = false;
      if(null == flObject)
      {
        String mkdirsExpr 
          = ((ElemExtensionCall)elem).getAttribute ("mkdirs", 
                                                    context.getContextNode(), 
                                                    context.getTransformer());
        boolean mkdirs = (mkdirsExpr != null)
                         ? (mkdirsExpr.equals("true") || 
mkdirsExpr.equals("yes")) : true;
        formatter = makeFormatterListener(context, fileName, true, mkdirs);
      }
      else
      {
        inTable = true;
        formatter = (ContentHandler)flObject;
      }
  
      // context.getTransformer().writeChildren( formatter, 
context.getStylesheet(),
      //                                        (ElemTemplateElement)elem,
     //                                         context.getSourceTree(), 
     //                                         context.getContextNode(), 
      //                                        context.getMode());
      
      if(!inTable)
      {
        OutputStream ostream = (OutputStream)m_outputStreams.get(fileName);
        if(null != ostream)
        {
          formatter.endDocument();
          ostream.close();
          m_outputStreams.remove(fileName);
          m_formatterListeners.remove(fileName);
        }
      }
    }
  
  
    /**
     * Close the given file and remove it from the formatter listener's table.
     */
    public void close(XSLProcessorContext context, Element elem)
      throws java.net.MalformedURLException,
      java.io.FileNotFoundException,
      java.io.IOException,
      org.xml.sax.SAXException
    {
      String fileName = getFilename(context, elem);
      Object formatterObj = m_formatterListeners.get(fileName);
      if(null != formatterObj)
      {
        ContentHandler fl = (ContentHandler)formatterObj;
        fl.endDocument();
        OutputStream ostream = (OutputStream)m_outputStreams.get(fileName);
        if(null != ostream)
        {
          ostream.close();
          m_outputStreams.remove(fileName);
        }
        m_formatterListeners.remove(fileName);
      }
    }
  
    /**
     * Get the filename from the 'select' or the 'file' attribute.
     */
    private String getFilename(XSLProcessorContext context, Element elem)
      throws java.net.MalformedURLException,
      java.io.FileNotFoundException,
      java.io.IOException,
      org.xml.sax.SAXException
    {
      String fileName;
      String fileNameExpr 
        = ((ElemExtensionCall)elem).getAttribute ("select", 
                                                  context.getContextNode(), 
                                                  context.getTransformer());
      if(null != fileNameExpr)
      {
        org.apache.xalan.xpath.XPathContext xctxt 
          = context.getTransformer().getXPathContext();
        XObject xobj = XPathAPI.eval(context.getContextNode(), fileNameExpr, 
xctxt.getNamespaceContext());
        fileName = xobj.str();
        if((null == fileName) || (fileName.length() == 0))
        {
          fileName = ((ElemExtensionCall)elem).getAttribute ("file", 
                                                  context.getContextNode(), 
                                                  context.getTransformer());
        }
      }
      else
      {
        fileName = ((ElemExtensionCall)elem).getAttribute ("file", 
                                                           
context.getContextNode(), 
                                                           
context.getTransformer());
      }
      if(null == fileName)
      {
        context.getTransformer().getMsgMgr().error(elem, 
                                       context.getContextNode(), 
                                       
XSLTErrorResources.ER_REDIRECT_COULDNT_GET_FILENAME);
                                //"Redirect extension: Could not get filename - 
file or select attribute must return vald string.");
      }
      return fileName;
    }
  
    /**
     * Create a new ContentHandler, based on attributes of the current 
ContentHandler.
     */
    private ContentHandler makeFormatterListener(XSLProcessorContext context,
                                                  String fileName,
                                                  boolean shouldPutInTable,
                                                  boolean mkdirs)
      throws java.net.MalformedURLException,
      java.io.FileNotFoundException,
      java.io.IOException,
      org.xml.sax.SAXException
    {
      /*
      File file = new File(fileName);
      if(!file.isAbsolute())
      {
        if(null != context.processor.getOutputFileName())
        {
          File baseFile = new File(context.processor.getOutputFileName());
          file = new File(baseFile.getParent(), fileName);
        }
      }
  
      if(mkdirs)
      {
        String dirStr = file.getParent();
        if((null != dirStr) && (dirStr.length() > 0))
        {
          File dir = new File(dirStr);
          dir.mkdirs();
        }
      }
  
      StylesheetRoot sr = context.stylesheetTree.m_stylesheetRoot;
      OutputFormat formatter = sr.getOutput();
  
      FileOutputStream ostream = new FileOutputStream(file);
  
      ContentHandler flistener
        = sr.makeSAXSerializer(ostream, formatter);
  
      flistener.startDocument();
      if(shouldPutInTable)
      {
        m_outputStreams.put(fileName, ostream);
        m_formatterListeners.put(fileName, flistener);
      }
      return flistener;
      */
      return null;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorAttributeSet.java
  
  Index: ProcessorAttributeSet.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.ElemAttributeSet;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.xml.sax.Attributes;
  import org.xml.sax.SAXException;
  
  /**
   * This class processes parse events for an xsl:attribute-set.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a href="http://www.w3.org/TR/xslt#attribute-sets";>attribute-sets in 
XSLT Specification</a>
   */
  class ProcessorAttributeSet extends XSLTElementProcessor
  {
    /**
     * Receive notification of the start of an xsl:attribute-set element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      ElemAttributeSet eat = new ElemAttributeSet();
      eat.setLocaterInfo(handler.getLocator());
      eat.setPrefixes(handler.getNamespaceSupport());
      
      setPropertiesFromAttributes(handler, rawName, attributes, eat);
                                     
      handler.getStylesheet().setAttributeSet(eat);
      
      // handler.pushElemTemplateElement(eat);
      ElemTemplateElement parent = handler.getElemTemplateElement();
      parent.appendChild(eat);
      handler.pushElemTemplateElement(eat);
    }
    
    /**
     * Receive notification of the end of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endElement
     */
    public void endElement (StylesheetHandler handler, 
                            String uri, String localName, String rawName)
      throws SAXException
    {
      handler.popElemTemplateElement();
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorCharacters.java
  
  Index: ProcessorCharacters.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import java.lang.StringBuffer;
  import org.xml.sax.SAXException;
  import org.apache.xalan.templates.ElemText;
  import org.apache.xalan.templates.ElemTextLiteral;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.templates.Constants;
  
  /**
   * This class processes character events for a XSLT template element.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-the-Result-Tree";>section-Creating-the-Result-Tree
 in XSLT Specification</a>
   */
  public class ProcessorCharacters extends XSLTElementProcessor
  {    
    /**
     * Receive notification of the start of the non-text event.  This 
     * is sent to the current processor when any non-text event occurs.
     */
    public void startNonText(StylesheetHandler handler)
      throws SAXException
    {
      if(this == handler.getCurrentProcessor())
        handler.popProcessor();
  
      int nChars = m_accumulator.length();
      if((nChars > 0) &&
         ((null != m_xslTextElement) || !isWhiteSpace(m_accumulator)))
      {
        ElemTextLiteral elem = new ElemTextLiteral();
        elem.setLocaterInfo(handler.getLocator());
        elem.setPrefixes(handler.getNamespaceSupport());
        boolean doe = (null != m_xslTextElement) 
                      ? m_xslTextElement.getDisableOutputEscaping() : false;
        elem.setDisableOutputEscaping(doe);
        elem.setPreserveSpace(true);
  
        char[] chars = new char[nChars];
        m_accumulator.getChars(0, nChars, chars, 0);
        elem.setChars(chars);
        ElemTemplateElement parent = handler.getElemTemplateElement();
        parent.appendChild(elem);
      }
      m_accumulator.setLength(0);
    }
    
    /**
     * Returns whether the specified <var>ch</var> conforms to the XML 1.0 
definition
     * of whitespace.  Refer to <A 
href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S";>
     * the definition of <CODE>S</CODE></A> for details.
     * @param   ch      Character to check as XML whitespace.
     * @return          =true if <var>ch</var> is XML whitespace; otherwise 
=false.
     */
    public static boolean isSpace(char ch)
    {
      return (ch == 0x20) || (ch == 0x09) || (ch == 0xD) || (ch == 0xA);
    }
  
    /**
     * Tell if the string is whitespace.
     * @param   string      String to be trimmed.
     * @return              The trimmed string.
     */
    public static boolean isWhiteSpace(char ch[], int start, int length)
    {
      int end = start+length;
      for(int s = start;  s < end;  s++)
      {
        if (!isSpace(ch[s]))
          return false;
      }
      return true;
    }
    
    /**
     * Tell if the string is whitespace.
     * @param   string      String to be trimmed.
     * @return              The trimmed string.
     */
    public static boolean isWhiteSpace(StringBuffer buf)
    {
      int n = buf.length();
      for(int i = 0;  i < n;  i++)
      {
        if (!isSpace(buf.charAt(i)))
          return false;
      }
      return true;
    }
  
    
    /**
     * Receive notification of character data inside an element.
     *
     * @param ch The characters.
     * @param start The start position in the character array.
     * @param length The number of characters to use from the
     *               character array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#characters
     */
    public void characters (StylesheetHandler handler, 
                            char ch[], int start, int length)
      throws SAXException
    {
      m_accumulator.append(ch, start, length);
      
      // Catch all events until a non-character event.
      if(this != handler.getCurrentProcessor())
        handler.pushProcessor(this);
    } 
    
    /**
     * Receive notification of the end of an element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void endElement (StylesheetHandler handler, String uri, 
                            String localName, String rawName)
      throws SAXException
    {
      // Since this has been installed as the current processor, we 
      // may get and end element event, in which case, we pop and clear 
      // and then call the real element processor.
      startNonText(handler);
      handler.getCurrentProcessor().endElement (handler, uri, localName, 
rawName);
      handler.popProcessor();
    }
  
    /**
     * Accumulate characters, until a non-whitespace event has 
     * occured.
     */
    private StringBuffer m_accumulator = new StringBuffer();
    
    /**
     * The xsl:text processor will call this to set a 
     * preserve space state.
     */
    private ElemText m_xslTextElement;
    
    /**
     * Set the current setXslTextElement
     */
    void setXslTextElement(ElemText xslTextElement)
    {
      m_xslTextElement = xslTextElement;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorDecimalFormat.java
  
  Index: ProcessorDecimalFormat.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.DecimalFormatProperties;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  class ProcessorDecimalFormat extends XSLTElementProcessor
  {  
    /**
     * Receive notification of the start of an element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      DecimalFormatProperties dfp = new DecimalFormatProperties();
      
      setPropertiesFromAttributes(handler, rawName, attributes, dfp);
                                     
      handler.getStylesheet().setDecimalFormat(dfp);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorGlobalParamDecl.java
  
  Index: ProcessorGlobalParamDecl.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.templates.ElemParam;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  /**
   * This class processes parse events for an xsl:param element.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
   */
  class ProcessorGlobalParamDecl extends ProcessorTemplateElem
  {
    /**
     * Append the current template element to the current 
     * template element, and then push it onto the current template 
     * element stack.
     */
    protected void appendAndPush(StylesheetHandler handler,
                                 ElemTemplateElement elem)
      throws SAXException
    {
      // Just push, but don't append.
      handler.pushElemTemplateElement(elem);
    }
    
      /**
     * Receive notification of the end of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endElement
     */
    public void endElement (StylesheetHandler handler, 
                            String uri, String localName, String rawName)
      throws SAXException
    {
      ElemParam v = (ElemParam)handler.getElemTemplateElement();
      handler.getStylesheet().setParam(v);
      super.endElement(handler, uri, localName, rawName);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorGlobalVariableDecl.java
  
  Index: ProcessorGlobalVariableDecl.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.templates.ElemVariable;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  /**
   * This class processes parse events for an xsl:variable element.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
   */
  class ProcessorGlobalVariableDecl extends ProcessorTemplateElem
  {
    /**
     * Append the current template element to the current 
     * template element, and then push it onto the current template 
     * element stack.
     */
    protected void appendAndPush(StylesheetHandler handler,
                                 ElemTemplateElement elem)
      throws SAXException
    {
      // Just push, but don't append.
      handler.pushElemTemplateElement(elem);
    }
    
      /**
     * Receive notification of the end of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endElement
     */
    public void endElement (StylesheetHandler handler, 
                            String uri, String localName, String rawName)
      throws SAXException
    {
      ElemVariable v = (ElemVariable)handler.getElemTemplateElement();
      handler.getStylesheet().setVariable(v);
      super.endElement(handler, uri, localName, rawName);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorImport.java
  
  Index: ProcessorImport.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.Stylesheet;
  import org.apache.xalan.templates.StylesheetComposed;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  import org.xml.sax.XMLReader;
  import java.net.URL;
  import java.io.IOException;
  
  /**
   * This class processes parse events for an xsl:import element.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a href="http://www.w3.org/TR/xslt#import";>import in XSLT 
Specification</a>
   */
  class ProcessorImport extends ProcessorInclude
  {
    /**
     * Receive notification of the start of an xsl:import element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      setPropertiesFromAttributes(handler, rawName, attributes, this);
  
      URL hrefUrl = getHref();
      if(handler.importStackContains(hrefUrl))
      {
        throw new 
SAXException(XSLMessages.createMessage(XSLTErrorResources.ER_IMPORTING_ITSELF, 
new Object[] {hrefUrl})); //"(StylesheetHandler) "+hrefUrl+" is directly or 
indirectly importing itself!");
      }
  
      handler.pushImportURL(hrefUrl);
      int savedStylesheetType = handler.getStylesheetType();
      handler.setStylesheetType(StylesheetHandler.STYPE_IMPORT);
  
      try
      {
        XMLReader reader = handler.getStylesheetProcessor().getXMLReader();
        
        Class readerClass = ((Object)reader).getClass();
        XMLReader clonedReader = (XMLReader)readerClass.newInstance();
        
        clonedReader.setContentHandler(handler);
        clonedReader.parse(getHref().toExternalForm());
  
      }
      catch(InstantiationException ie)
      {
        handler.error("Could not clone parser!", ie);
      }
      catch(IllegalAccessException iae)
      {
        handler.error("Can not access class!", iae);
      }
      catch(IOException ioe)
      {
        handler.error(XSLTErrorResources.ER_IOEXCEPTION, new Object[] 
{hrefUrl}, ioe); 
      }
      catch(SAXException ioe)
      {
        handler.error(XSLTErrorResources.ER_IOEXCEPTION, new Object[] 
{hrefUrl}, ioe); 
      }
      finally
      {
        handler.setStylesheetType(savedStylesheetType);
        handler.popImportURL();
        handler.popStylesheet();
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorInclude.java
  
  Index: ProcessorInclude.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.Stylesheet;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  import org.xml.sax.XMLReader;
  import java.net.URL;
  import java.io.IOException;
  
  /**
   * Processor class for xsl:include markup.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a href="http://www.w3.org/TR/xslt#include";>include in XSLT 
Specification</a>
   */
  class ProcessorInclude extends XSLTElementProcessor
  {
    /**
     * The base URL of the XSL document.
     * @serial
     */
    private URL m_href = null;
  
    /**
     * Get the base identifier with which this stylesheet is associated.
     */
    URL getHref()
    {
      return m_href;
    }
  
    /**
     * Get the base identifier with which this stylesheet is associated.
     */
    void setHref(URL baseIdent)
    {
      m_href = baseIdent;
    }
  
    /**
     * Receive notification of the start of an xsl:include element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      setPropertiesFromAttributes(handler, rawName, attributes, this);
      
      int savedStylesheetType = handler.getStylesheetType();
      handler.setStylesheetType(StylesheetHandler.STYPE_INCLUDE);
  
      try
      {
        XMLReader reader = handler.getStylesheetProcessor().getXMLReader();
        
        Class readerClass = ((Object)reader).getClass();
        XMLReader clonedReader = (XMLReader)readerClass.newInstance();
        
        clonedReader.setContentHandler(handler);
        clonedReader.parse(getHref().toExternalForm());
      }
      catch(InstantiationException ie)
      {
        handler.error("Could not clone parser!", ie);
      }
      catch(IllegalAccessException iae)
      {
        handler.error("Can not access class!", iae);
      }
      catch(IOException ioe)
      {
        handler.error(XSLTErrorResources.ER_IOEXCEPTION, new Object[] 
{getHref()}, ioe); 
      }
      catch(SAXException ioe)
      {
        handler.error(XSLTErrorResources.ER_IOEXCEPTION, new Object[] 
{getHref()}, ioe); 
      }
      finally
      {
        handler.setStylesheetType(savedStylesheetType);
        handler.popStylesheet();
      }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorKey.java
  
  Index: ProcessorKey.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.KeyDeclaration;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  /**
   * Processor for xsl:key markup.
   * <pre>
   * <!ELEMENT xsl:key EMPTY>
   * <!ATTLIST xsl:key
   *   name %qname; #REQUIRED
   *   match %pattern; #REQUIRED
   *   use %expr; #REQUIRED
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a href="http://www.w3.org/TR/xslt#key";>key in XSLT Specification</a>
   */
  class ProcessorKey extends XSLTElementProcessor
  {
    /**
     * Receive notification of the start of an xsl:key element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      KeyDeclaration kd = new KeyDeclaration();
      kd.setLocaterInfo(handler.getLocator());
      
      setPropertiesFromAttributes(handler, rawName, attributes, kd);
                                     
      handler.getStylesheet().setKey(kd);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorLRE.java
  
  Index: ProcessorLRE.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.ElemLiteralResult;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  public class ProcessorLRE extends ProcessorTemplateElem
  {
    /**
     * Receive notification of the start of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#startElement
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      XSLTElementDef def = getElemDef();
      Class classObject = def.getClassObject();
      
      ElemLiteralResult elem = null;
      try
      {
        elem = (ElemLiteralResult)classObject.newInstance();
        elem.setLocaterInfo(handler.getLocator());
        elem.setPrefixes(handler.getNamespaceSupport());
        elem.setNamespace(uri);
        elem.setLocalName(localName);
        elem.setRawName(rawName);
      }
      catch(InstantiationException ie)
      {
        handler.error("Failed creating ElemLiteralResult instance!", ie);
      }
      catch(IllegalAccessException iae)
      {
        handler.error("Failed creating ElemLiteralResult instance!", iae);
      }
      
      setPropertiesFromAttributes(handler, rawName, attributes, elem);
      
      appendAndPush(handler, elem);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorNamespaceAlias.java
  
  Index: ProcessorNamespaceAlias.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.NamespaceAlias;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  /**
   * Processor for xsl:namespace-alias markup.
   * A stylesheet can use the xsl:namespace-alias element to 
   * declare that one namespace URI is an alias for another namespace URI. 
   * <pre>
   * <!ELEMENT xsl:namespace-alias EMPTY>
   * <!ATTLIST xsl:namespace-alias
   *   stylesheet-prefix CDATA #REQUIRED
   *   result-prefix CDATA #REQUIRED
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a 
href="http://www.w3.org/TR/xslt#literal-result-element";>literal-result-element 
in XSLT Specification</a>
   */
  class ProcessorNamespaceAlias extends XSLTElementProcessor
  {
    /**
     * Receive notification of the start of an xsl:namespace-alias element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      NamespaceAlias na = new NamespaceAlias();
      
      setPropertiesFromAttributes(handler, rawName, attributes, na);
                                     
      handler.getStylesheet().setNamespaceAlias(na);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorOutputElem.java
  
  Index: ProcessorOutputElem.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xml.serialize.OutputFormat;
  import java.util.Hashtable;
  import org.apache.xalan.templates.OutputFormatExtended;
  import org.apache.xalan.templates.StylesheetRoot;
  import org.apache.xalan.templates.Stylesheet;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  /**
   * Processor for xsl:output markup.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a href="http://www.w3.org/TR/xslt#output";>output in XSLT 
Specification</a>
   */
  class ProcessorOutputElem extends XSLTElementProcessor
  {  
    /**
     * Receive notification of the start of an xsl:output element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      OutputFormatExtended ofe = new OutputFormatExtended();
      
      setPropertiesFromAttributes(handler, rawName, attributes, ofe);
      
      handler.getStylesheet().setOutput(ofe);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorPreserveSpace.java
  
  Index: ProcessorPreserveSpace.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  import java.util.Vector;
  
  /**
   * Processor for xsl:preserve-space markup.
   * <pre>
   * <!ELEMENT xsl:preserve-space EMPTY>
   * <!ATTLIST xsl:preserve-space elements CDATA #REQUIRED>
   * </pre>
   */
  class ProcessorPreserveSpace extends XSLTElementProcessor
  {
    
    /**
     * Bean property to allow setPropertiesFromAttributes to 
     * get the elements attribute.
     */
    private Vector m_elements;
    
    /**
     * Set from the elements attribute.
     */
    public void setElements(Vector elems)
    {
      m_elements = elems;
    }
  
    /**
     * Get the property set by setElements().
     */
    Vector getElements()
    {
      return m_elements;
    }
  
    /**
     * Receive notification of the start of an preserve-space element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      setPropertiesFromAttributes(handler, rawName, attributes, this);
                                     
      handler.getStylesheet().setPreserveSpaces(getElements());
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorStripSpace.java
  
  Index: ProcessorStripSpace.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  import java.util.Vector;
  
  /**
   * Processor for xsl:strip-space markup.
   * <pre>
   * <!ELEMENT xsl:strip-space EMPTY>
   * <!ATTLIST xsl:strip-space elements CDATA #REQUIRED>
   * </pre>
   */
  class ProcessorStripSpace extends ProcessorPreserveSpace
  {
    /**
     * Receive notification of the start of an strip-space element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      setPropertiesFromAttributes(handler, rawName, attributes, this);
                                     
      handler.getStylesheet().setStripSpaces(getElements());
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorStylesheetDoc.java
  
  Index: ProcessorStylesheetDoc.java
  ===================================================================
  package org.apache.xalan.processor;
  
  public class ProcessorStylesheetDoc extends XSLTElementProcessor
  {
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorStylesheetElement.java
  
  Index: ProcessorStylesheetElement.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.StylesheetRoot;
  import org.apache.xalan.templates.Stylesheet;
  import org.apache.xalan.templates.StylesheetComposed;
  
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  /**
   * Processor for xsl:stylesheet or xsl:transform markup.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a 
href="http://www.w3.org/TR/xslt#stylesheet-element";>stylesheet-element in XSLT 
Specification</a>
   */
  class ProcessorStylesheetElement extends XSLTElementProcessor
  {
    /**
     * Receive notification of the start of an strip-space element.
     *
     * @param handler The calling StylesheetHandler/TemplatesBuilder.
     * @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 localName The local name (without prefix), or the
     *        empty string if Namespace processing is not being
     *        performed.
     * @param rawName The raw XML 1.0 name (with prefix), or the
     *        empty string if raw names are not available.
     * @param atts The attributes attached to the element.  If
     *        there are no attributes, it shall be an empty
     *        Attributes object.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.apache.xalan.processor.StylesheetHandler#startElement
     * @see org.apache.xalan.processor.StylesheetHandler#endElement
     * @see org.xml.sax.ContentHandler#startElement
     * @see org.xml.sax.ContentHandler#endElement
     * @see org.xml.sax.Attributes
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      int stylesheetType = handler.getStylesheetType();
      Stylesheet stylesheet;
      if(stylesheetType == StylesheetHandler.STYPE_ROOT)
      {
        stylesheet = new StylesheetRoot();
      }
      else 
      {
        Stylesheet parent = handler.getStylesheet();
        if(stylesheetType == StylesheetHandler.STYPE_IMPORT)
        {
          StylesheetComposed sc = new StylesheetComposed(parent);
          parent.setImport(sc);
          stylesheet = sc;
        }
        else
        {
          stylesheet = new Stylesheet(parent);
          parent.setInclude(stylesheet);
        }
      }
      stylesheet.setLocaterInfo(handler.getLocator());
      stylesheet.setPrefixes(handler.getNamespaceSupport());
  
      handler.pushStylesheet(stylesheet);
      
      setPropertiesFromAttributes(handler, rawName, attributes, 
handler.getStylesheet());
  
      handler.pushElemTemplateElement(handler.getStylesheet());
    }
    
    /**
     * Receive notification of the end of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endElement
     */
    public void endElement (StylesheetHandler handler, 
                            String uri, String localName, String rawName)
      throws SAXException
    {
      handler.popElemTemplateElement();
    }
  
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorTemplate.java
  
  Index: ProcessorTemplate.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.ElemTemplate;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  
  /**
   * Processor for xsl:template markup.
   */
  class ProcessorTemplate extends ProcessorTemplateElem
  {
    /**
     * Append the current template element to the current 
     * template element, and then push it onto the current template 
     * element stack.
     */
    protected void appendAndPush(StylesheetHandler handler,
                                 ElemTemplateElement elem)
      throws SAXException
    {
      super.appendAndPush(handler, elem);
      handler.getStylesheet().setTemplate((ElemTemplate)elem);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorTemplateElem.java
  
  Index: ProcessorTemplateElem.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  import java.lang.reflect.Method;
  import java.lang.reflect.InvocationTargetException;
  import java.lang.NoSuchMethodException;
  import java.lang.InstantiationException;
  import java.lang.IllegalAccessException;
  import java.util.Vector;
  
  /**
   * This class processes parse events for an XSLT template element.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-the-Result-Tree";>section-Creating-the-Result-Tree
 in XSLT Specification</a>
   */
  public class ProcessorTemplateElem extends XSLTElementProcessor
  {
    /**
     * Receive notification of the start of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#startElement
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      XSLTElementDef def = getElemDef();
      Class classObject = def.getClassObject();
      
      ElemTemplateElement elem = null;
      try
      {
        elem = (ElemTemplateElement)classObject.newInstance();
        elem.setLocaterInfo(handler.getLocator());
        elem.setPrefixes(handler.getNamespaceSupport());
      }
      catch(InstantiationException ie)
      {
        handler.error("Failed creating ElemTemplateElement instance!", ie);
      }
      catch(IllegalAccessException iae)
      {
        handler.error("Failed creating ElemTemplateElement instance!", iae);
      }
      
      setPropertiesFromAttributes(handler, rawName, attributes, elem);
      
      appendAndPush(handler, elem);
    }
    
    /**
     * Append the current template element to the current 
     * template element, and then push it onto the current template 
     * element stack.
     */
    protected void appendAndPush(StylesheetHandler handler,
                                 ElemTemplateElement elem)
      throws SAXException
    {
      ElemTemplateElement parent = handler.getElemTemplateElement();
      parent.appendChild(elem);
      handler.pushElemTemplateElement(elem);
    }
    
    /**
     * Receive notification of the end of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endElement
     */
    public void endElement (StylesheetHandler handler, 
                            String uri, String localName, String rawName)
      throws SAXException
    {
      handler.popElemTemplateElement();
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/ProcessorText.java
  
  Index: ProcessorText.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.templates.ElemText;
  import org.xml.sax.SAXException;
  
  /**
   * Process xsl:text.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   * @see <a href="http://www.w3.org/TR/xslt#element-text";>element-text in XSLT 
Specification</a>
   */
  public class ProcessorText extends ProcessorTemplateElem
  {
    /**
     * Append the current template element to the current 
     * template element, and then push it onto the current template 
     * element stack.
     */
    protected void appendAndPush(StylesheetHandler handler,
                                 ElemTemplateElement elem)
      throws SAXException
    {
      // Don't push this element onto the element stack.
      ProcessorCharacters charProcessor 
        = (ProcessorCharacters)handler.getProcessorFor( null, "text()",  "text" 
);
      charProcessor.setXslTextElement((ElemText)elem);
      ElemTemplateElement parent = handler.getElemTemplateElement();
      parent.appendChild(elem);
    }
      
    /**
     * Receive notification of the end of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endElement
     */
    public void endElement (StylesheetHandler handler, 
                            String uri, String localName, String rawName)
      throws SAXException
    {
      ProcessorCharacters charProcessor 
        = (ProcessorCharacters)handler.getProcessorFor( null, "text()",  "text" 
);
      charProcessor.setXslTextElement(null);
    }
  
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/StylesheetHandler.java
  
  Index: StylesheetHandler.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import java.net.URL;
  import java.util.Stack;
  import org.apache.xalan.templates.Constants;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.templates.StylesheetRoot;
  import org.apache.xalan.templates.Stylesheet;
  import trax.ProcessorException;
  import trax.TemplatesBuilder;
  import trax.Templates;
  import trax.TransformException;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XPathFactory;
  import org.apache.xalan.xpath.XPathParser;
  import org.apache.xalan.xpath.FunctionTable;
  import org.apache.xalan.xpath.functions.Function;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.utils.PrefixResolver;
  import org.xml.sax.Attributes;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.DTDHandler;
  import org.xml.sax.EntityResolver;
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.helpers.NamespaceSupport;
  import org.xml.sax.InputSource;
  import org.xml.sax.Locator;
  import org.xml.sax.SAXException;
  import org.xml.sax.SAXParseException;
  
  
  /**
   * <meta name="usage" content="advanced"/>
   * Initializes and processes a stylesheet via SAX events.
   * This class acts as essentially a state machine, maintaining 
   * a ContentHandler stack, and pushing appropriate content 
   * handlers as parse events occur.
   */
  public class StylesheetHandler
    implements EntityResolver, DTDHandler, 
    ContentHandler, ErrorHandler, TemplatesBuilder, PrefixResolver
  {
    static boolean m_xpathFunctionsInited = false;
    
    /**
     * Create a StylesheetHandler object, creating a root stylesheet 
     * as the target.
     * @exception May throw ProcessorException if a StylesheetRoot 
     * can not be constructed for some reason.
     */
    public StylesheetHandler(StylesheetProcessor processor)
      throws ProcessorException
    {
      // m_schema = new XSLTSchema();
      
      init(processor);
    }
    
    /**
     * Do common initialization.
     */
    void init(StylesheetProcessor processor)
    {
      // Not sure about double-check of this flag, but 
      // it seems safe...
      if(false == m_xpathFunctionsInited)
      {
        synchronized (this)
        {
          if(false == m_xpathFunctionsInited)
          {
            m_xpathFunctionsInited = true;
            Function func 
              = new org.apache.xalan.templates.FuncDocument();
            FunctionTable.installFunction("document", func);
            
            // func = new org.apache.xalan.templates.FuncKey();
            // FunctionTable.installFunction("key", func);
            
            func = new org.apache.xalan.templates.FuncFormatNumb();
            FunctionTable.installFunction("format-number", func);
          }
        }
      }
  
      m_stylesheetProcessor = processor;
      
      // Set the initial content handler.
      m_processors.push(m_schema.getElementProcessor());
      
      // 
m_includeStack.push(SystemIDResolver.getURLFromString(this.getBaseIdentifier(), 
null));
      // initXPath(processor, null);
    }
  
    /**
     * Process an expression string into an XPath.
     * Must be public for access by the AVT class.
     */
    public XPath createXPath(String str)
      throws org.xml.sax.SAXException
    {
      XPath xpath = m_xpathFactory.create();
  
      m_xpathProcessor.initXPath(xpath, str, this);
  
      return xpath;
    }
  
    /**
     * Process an expression string into an XPath.
     */
    XPath createMatchPatternXPath(String str)
      throws org.xml.sax.SAXException
    {
      XPath xpath = m_xpathFactory.create();
  
      m_xpathProcessor.initMatchPattern(xpath, str, this);
  
      return xpath;
    }
    
    /**
     * Given a namespace, get the corrisponding prefix.  This assumes that 
     * the PrevixResolver hold's it's own namespace context, or is a namespace
     * context itself.
     */
    public String getNamespaceForPrefix(String prefix)
    {
      return m_nsSupport.getURI(prefix);
    }
  
    /**
     * Given a namespace, get the corrisponding prefix.
     */
    public String getNamespaceForPrefix(String prefix, org.w3c.dom.Node context)
    {
      // Don't need to support this here.  Return the current URI for the 
prefix, 
      // ignoring the context.
      assert(true, "can't process a context node in StylesheetHandler!");
      return null;
    }
    
    /** 
     * Return the base identifier.
     */
    public String getBaseIdentifier()
    {
      org.xml.sax.Locator locator = getLocator();
      
      return (null == locator) ? "" : locator.getSystemId();
    }
    
    /**
     * Test to see if the stack contains the given URL.
     */
    private boolean stackContains(Stack stack, URL url)
    {
      int n = stack.size();
      boolean contains = false;
      for(int i = 0; i < n; i++)
      {
        URL url2 = (URL)stack.elementAt(i);
        if(url2.toString().equals(url.toString()))
        {
          contains = true;
          break;
        }
      }
      return contains;
    }
  
    ////////////////////////////////////////////////////////////////////
    // Implementation of the TRAX TemplatesBuilder interface.
    ////////////////////////////////////////////////////////////////////
    
    /**
     * When this object is used as a ContentHandler or ContentHandler, it will 
     * create a Templates object, which the caller can get once 
     * the SAX events have been completed.
     * @return The stylesheet object that was created during 
     * the SAX event process, or null if no stylesheet has 
     * been created.
     *
     * @version Alpha
     * @author <a href="mailto:[EMAIL PROTECTED]">Scott Boag</a>
     */
    public Templates getTemplates() 
      throws TransformException
    {
      return getStylesheetRoot();
    }
    
    /**
     * Set the base ID (URL or system ID) for the stylesheet 
     * created by this builder.  This must be set in order to 
     * resolve relative URLs in the stylesheet.
     * @param baseID Base URL for this stylesheet.
     */
    public void setBaseID(String baseID)
    {
      m_baseIdentifiers.push(baseID);
      
    }
  
    ////////////////////////////////////////////////////////////////////
    // Implementation of the EntityResolver interface.
    ////////////////////////////////////////////////////////////////////
    
    /**
     * Resolve an external entity.
     *
     * <p>Always return null, so that the parser will use the system
     * identifier provided in the XML document.  This method implements
     * the SAX default behaviour: application writers can override it
     * in a subclass to do special translations such as catalog lookups
     * or URI redirection.</p>
     *
     * @param publicId The public identifer, or null if none is
     *                 available.
     * @param systemId The system identifier provided in the XML 
     *                 document.
     * @return The new input source, or null to require the
     *         default behaviour.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.EntityResolver#resolveEntity
     */
    public InputSource resolveEntity (String publicId, String systemId)
      throws SAXException
    {
      return getCurrentProcessor().resolveEntity (this, publicId, systemId);
    }
    
    
    ////////////////////////////////////////////////////////////////////
    // Implementation of DTDHandler interface.
    ////////////////////////////////////////////////////////////////////
    
    
    /**
     * Receive notification of a notation declaration.
     *
     * <p>By default, do nothing.  Application writers may override this
     * method in a subclass if they wish to keep track of the notations
     * declared in a document.</p>
     *
     * @param name The notation name.
     * @param publicId The notation public identifier, or null if not
     *                 available.
     * @param systemId The notation system identifier.
     * @see org.xml.sax.DTDHandler#notationDecl
     */
    public void notationDecl (String name, String publicId, String systemId)
    {
      getCurrentProcessor().notationDecl (this, name, publicId, systemId);
    }
    
    
    /**
     * Receive notification of an unparsed entity declaration.
     *
     * @param name The entity name.
     * @param publicId The entity public identifier, or null if not
     *                 available.
     * @param systemId The entity system identifier.
     * @param notationName The name of the associated notation.
     * @see org.xml.sax.DTDHandler#unparsedEntityDecl
     */
    public void unparsedEntityDecl (String name, String publicId,
                                    String systemId, String notationName)
    {
      getCurrentProcessor().unparsedEntityDecl (this, name, publicId,
                                                systemId, notationName);
    }
    
    /**
     * Given a namespace URI, and a local name or a node type, get the 
processor 
     * for the element, or return null if not allowed.
     */
    XSLTElementProcessor getProcessorFor( String uri, String localName,  
                                          String rawName)
      throws SAXException
    {
      XSLTElementProcessor currentProcessor = getCurrentProcessor();
      XSLTElementDef def = currentProcessor.getElemDef();
      XSLTElementProcessor elemProcessor = def.getProcessorFor(uri, localName);
      
      if(null == elemProcessor)
        error(rawName+" is not allowed in this position in the stylesheet!", 
null);
      
      return elemProcessor;
    }
  
    
    ////////////////////////////////////////////////////////////////////
    // Implementation of ContentHandler interface.
    ////////////////////////////////////////////////////////////////////
    
    
    /**
     * Receive a Locator object for document events.
     *
     * @param locator A locator for all SAX document events.
     * @see org.xml.sax.ContentHandler#setDocumentLocator
     * @see org.xml.sax.Locator
     */
    public void setDocumentLocator (Locator locator)
    {
      // System.out.println("pushing locator for: "+locator.getSystemId());
      m_stylesheetLocatorStack.push(locator);
    }  
    
    /**
     * The level of the stylesheet we are at.
     */
    private int m_stylesheetLevel = -1;
    
    /**
     * Receive notification of the beginning of the document.
     *
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#startDocument
     */
    public void startDocument ()
      throws SAXException
    {
      m_stylesheetLevel++;
    }
    
    /**
     * Receive notification of the end of the document.
     *
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endDocument
     */
    public void endDocument ()
      throws SAXException
    {
      if(0 == m_stylesheetLevel)
        getStylesheetRoot().recompose();
      
      // Resolve the result prefix tables in the elements.
      getStylesheet().resolvePrefixTables();
  
      XSLTElementProcessor elemProcessor = getCurrentProcessor();
      if(null != elemProcessor)
        elemProcessor.startNonText(this);
      
      m_stylesheetLevel--;
    }
  
  
    /**
     * Receive notification of the start of a Namespace mapping.
     *
     * <p>By default, do nothing.  Application writers may override this
     * method in a subclass to take specific actions at the start of
     * each element (such as allocating a new tree node or writing
     * output to a file).</p>
     *
     * @param prefix The Namespace prefix being declared.
     * @param uri The Namespace URI mapped to the prefix.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#startPrefixMapping
     */
    public void startPrefixMapping (String prefix, String uri)
      throws SAXException
    {
      // m_nsSupport.pushContext();
      m_nsSupport.declarePrefix(prefix, uri);
    }
  
  
    /**
     * Receive notification of the end of a Namespace mapping.
     *
     * <p>By default, do nothing.  Application writers may override this
     * method in a subclass to take specific actions at the start of
     * each element (such as allocating a new tree node or writing
     * output to a file).</p>
     *
     * @param prefix The Namespace prefix being declared.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endPrefixMapping
     */
    public void endPrefixMapping (String prefix)
      throws SAXException
    {
      // m_nsSupport.popContext();
    }
    
    /**
     * Flush the characters buffer.
     */
    private void flushCharacters()
      throws SAXException
    {
      XSLTElementProcessor elemProcessor = getCurrentProcessor();
      if(null != elemProcessor)
        elemProcessor.startNonText(this);
    }
    
    
    /**
     * Receive notification of the start of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#startElement
     */
    public void startElement (String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      flushCharacters();   
      XSLTElementProcessor elemProcessor = getProcessorFor( uri, localName,  
rawName );
      this.pushProcessor(elemProcessor);
      elemProcessor.startElement (this, uri, localName,
                                  rawName, attributes);
      m_nsSupport.pushContext();
    }
    
    /**
     * Receive notification of the end of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endElement
     */
    public void endElement (String uri, String localName, String rawName)
      throws SAXException
    {
      flushCharacters();
      getCurrentProcessor().endElement (this, uri, localName, rawName);
      this.popProcessor();
      m_nsSupport.popContext();
    }
    
    /**
     * Tell if the given character array is whitespace.
     */
    private boolean isWhitespaceArray(char ch[], int start, int length)
    {
      int n = start+length;
      for(int i = start; i < n; i++)
      {
        if(!Character.isWhitespace(ch[i]))
           return false;
      }
      return true;
    }
    
    /**
     * Receive notification of character data inside an element.
     *
     * @param ch The characters.
     * @param start The start position in the character array.
     * @param length The number of characters to use from the
     *               character array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#characters
     */
    public void characters (char ch[], int start, int length)
      throws SAXException
    {
      XSLTElementProcessor elemProcessor = getCurrentProcessor();
      XSLTElementDef def = elemProcessor.getElemDef();
      if(def.getType() != XSLTElementDef.T_PCDATA)
        elemProcessor = def.getProcessorFor(null, "text()");
      
      if(null == elemProcessor)
      {
        // If it's whitespace, just ignore it, otherwise flag an error.
        if(!isWhitespaceArray(ch, start, length))
          error("Non-whitespace text is not allowed in this position in the 
stylesheet!", null);
      }
      else
        elemProcessor.characters (this, ch, start, length);
    }
    
    /**
     * Receive notification of ignorable whitespace in element content.
     *
     * @param ch The whitespace characters.
     * @param start The start position in the character array.
     * @param length The number of characters to use from the
     *               character array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#ignorableWhitespace
     */
    public void ignorableWhitespace (char ch[], int start, int length)
      throws SAXException
    {
      getCurrentProcessor().ignorableWhitespace (this, ch, start, length);
    }
    
    
    /**
     * Receive notification of a processing instruction.
     *
     * <p>By default, do nothing.  Application writers may override this
     * method in a subclass to take specific actions for each
     * processing instruction, such as setting status variables or
     * invoking other methods.</p>
     *
     * @param target The processing instruction target.
     * @param data The processing instruction data, or null if
     *             none is supplied.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#processingInstruction
     */
    public void processingInstruction (String target, String data)
      throws SAXException
    {
      flushCharacters();
      getCurrentProcessor().processingInstruction (this, target, data);
    }
  
  
    /**
     * Receive notification of a skipped entity.
     *
     * <p>By default, do nothing.  Application writers may override this
     * method in a subclass to take specific actions for each
     * processing instruction, such as setting status variables or
     * invoking other methods.</p>
     *
     * @param name The name of the skipped entity.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#processingInstruction
     */
    public void skippedEntity (String name)
      throws SAXException
    {
      getCurrentProcessor().skippedEntity (this, name);
    }
    
    
    ////////////////////////////////////////////////////////////////////
    // Implementation of the ErrorHandler interface.
    ////////////////////////////////////////////////////////////////////
    
    /**
     * <meta name="usage" content="internal"/>
     * Warn the user of an problem.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void warn(int msg, Object args[])
      throws SAXException
    {
      String formattedMsg = m_XSLMessages.createWarning(msg, args);
      Locator locator = getLocator();
      
      ErrorHandler handler = m_stylesheetProcessor.getErrorHandler ();
      if(null != handler)
        handler.warning(new ProcessorException(formattedMsg, locator));
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Assert that a condition is true.  If it is not true, throw an error.
     * @exception throws Runtime Exception.
     */
    private void assert(boolean condition, String msg)
    {
      if(!condition)
        throw new RuntimeException(msg);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    protected void error(String msg, Exception e)
      throws SAXException
    {
      Locator locator = getLocator();
      
      ErrorHandler handler = m_stylesheetProcessor.getErrorHandler ();
      ProcessorException pe = (null == e) ? new ProcessorException(msg, 
locator) :
                                            new ProcessorException(msg, 
locator, e);
      if(null != handler)
        handler.fatalError(pe);
      else
        throw pe;
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    protected void error(int msg, Object args[], Exception e)
      throws SAXException
    {
      String formattedMsg = m_XSLMessages.createMessage(msg, args);    
      error(formattedMsg, e);
    }
    
    /**
     * Receive notification of a parser warning.
     *
     * @param e The warning information encoded as an exception.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ErrorHandler#warning
     * @see org.xml.sax.SAXParseException
     */
    public void warning (SAXParseException e)
      throws SAXException
    {
      // Need to set up a diagnosticsWriter here?
      System.out.println("WARNING: "+e.getMessage());
      System.out.println(" ID: "+e.getSystemId()
                         +" Line #"+e.getLineNumber()
                         +" Column #"+e.getColumnNumber());
    }
    
    
    /**
     * Receive notification of a recoverable parser error.
     *
     * @param e The warning information encoded as an exception.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ErrorHandler#warning
     * @see org.xml.sax.SAXParseException
     */
    public void error (SAXParseException e)
      throws SAXException
    {
      // Need to set up a diagnosticsWriter here?
      System.out.println("RECOVERABLE ERROR: "+e.getMessage());
      System.out.println(" ID: "+e.getSystemId()
                         +" Line #"+e.getLineNumber()
                         +" Column #"+e.getColumnNumber());
    }
    
    
    /**
     * Report a fatal XML parsing error.
     *
     * <p>The default implementation throws a SAXParseException.
     * Application writers may override this method in a subclass if
     * they need to take specific actions for each fatal error (such as
     * collecting all of the errors into a single report): in any case,
     * the application must stop all regular processing when this
     * method is invoked, since the document is no longer reliable, and
     * the parser may no longer report parsing events.</p>
     *
     * @param e The error information encoded as an exception.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ErrorHandler#fatalError
     * @see org.xml.sax.SAXParseException
     */
    public void fatalError (SAXParseException e)
      throws SAXException
    {
      throw e;
    }
    
   /**
     * The XSLT Processor for needed services.
     */
    private StylesheetProcessor m_stylesheetProcessor;
    
    /**
     * Get the XSLT Processor for needed services.
     */
    StylesheetProcessor getStylesheetProcessor()
    {
      return m_stylesheetProcessor;
    }
    
    static final int STYPE_ROOT = 1;
    static final int STYPE_INCLUDE = 2;
    static final int STYPE_IMPORT = 3;
    
    private int m_stylesheetType = STYPE_ROOT;
    
    /**
     * Get the type of stylesheet that should be built 
     * or is being processed.
     */
    int getStylesheetType()
    {
      return m_stylesheetType;
    }
    
    /**
     * Set the type of stylesheet that should be built 
     * or is being processed.
     */
    void setStylesheetType(int type)
    {
      m_stylesheetType = type;
    }
  
    /**
     * The stack of stylesheets being processed.
     */
    private Stack m_stylesheets = new Stack();
    
    /**
     * Return the stylesheet that this handler is constructing.
     */
    Stylesheet getStylesheet()
    {
      return (Stylesheet)m_stylesheets.peek();
    }
    
    /**
     * Return the stylesheet that this handler is constructing.
     */
    StylesheetRoot getStylesheetRoot()
    {
      return (StylesheetRoot)m_stylesheets.elementAt(0);
    }
  
    /**
     * Return the stylesheet that this handler is constructing.
     */
    void pushStylesheet(Stylesheet s)
    {
      m_stylesheets.push(s);
    }
    
    /**
     * Return the stylesheet that this handler is constructing.
     */
    Stylesheet popStylesheet()
    {
      return (Stylesheet)m_stylesheets.pop();
    }
  
    /**
     * The stack of current processors.
     */
    private Stack m_processors = new Stack();
    
    /**
     * Get the current XSLTElementProcessor at the top of the stack.
     * @return Valid XSLTElementProcessor, which should never be null.
     */
    XSLTElementProcessor getCurrentProcessor()
    {
      return (XSLTElementProcessor)m_processors.peek();
    }
    
    /**
     * Push the current XSLTElementProcessor onto the top of the stack.
     */
    void pushProcessor(XSLTElementProcessor processor)
    {
      m_processors.push(processor);
    }
  
    /**
     * Pop the current XSLTElementProcessor from the top of the stack.
     * @return the XSLTElementProcessor which was popped.
     */
    XSLTElementProcessor popProcessor()
    {
      return (XSLTElementProcessor)m_processors.pop();
    }
    
    /**
     * The root of the XSLT Schema, which tells us how to 
     * transition content handlers, create elements, etc.
     */
    private static XSLTSchema m_schema = new XSLTSchema();
    
    /**
     * Get the root of the XSLT Schema, which tells us how to 
     * transition content handlers, create elements, etc.
     */
    XSLTSchema getSchema()
    {
      return m_schema;
    }
    
    /**
     * The stack of elements, pushed and popped as events occur.
     */
    private Stack m_elems = new Stack();
    
    /**
     * Get the current ElemTemplateElement at the top of the stack.
     * @return Valid ElemTemplateElement, which may be null.
     */
    ElemTemplateElement getElemTemplateElement()
    {
      return (ElemTemplateElement)m_elems.peek();
    }
    
    /**
     * Push the current XSLTElementProcessor to the top of the stack.
     */
    void pushElemTemplateElement(ElemTemplateElement elem)
    {
      m_elems.push(elem);
    }
  
    /**
     * Get the current XSLTElementProcessor from the top of the stack.
     * @return the ElemTemplateElement which was popped.
     */
    ElemTemplateElement popElemTemplateElement()
    {
      return (ElemTemplateElement)m_elems.pop();
    }
  
    /**
     * Flag to let us know when we've found an element inside the
     * stylesheet that is not an xsl:import, so we can restrict imports
     * to being the first elements.
     */
    private boolean m_foundNotImport = false;
    
    /**
     * A XSLMessages instance capable of producing user messages.
     */
    private static XSLMessages m_XSLMessages = new XSLMessages();
    
    /**
     * Get an XSLMessages instance capable of producing user messages.
     */
    XSLMessages getXSLMessages()
    {
      return m_XSLMessages;
    }
    
    /**
     * This will act as a stack to keep track of the
     * current include base.
     */
    Stack m_baseIdentifiers = new Stack();
    
    /**
     * Push a base identifier onto the base URI stack.
     */
    void pushBaseIndentifier(String base)
    {
      m_baseIdentifiers.push(base);
    }
    
    /**
     * Pop a base URI from the stack.
     * @return baseIdentifier.
     */
    String popBaseIndentifier()
    {
      return (String)m_baseIdentifiers.pop();
    }
    
    /**
     * The top of this stack should contain the currently processed
     * stylesheet SAX locator object.
     */
    private Stack m_stylesheetLocatorStack = new Stack();
    
    /**
     * Get the current stylesheet Locator object.
     */
    Locator getLocator()
    {
      return m_stylesheetLocatorStack.isEmpty()
             ? null :
               ((Locator)m_stylesheetLocatorStack.peek());
    }
    
    /**
     * A stack of URL hrefs for imported stylesheets.  This is 
     * used to diagnose circular imports.
     */
    private Stack m_importStack = new Stack();
    
    /**
     * Push an import href onto the stylesheet stack.
     */
    void pushImportURL(URL hrefUrl)
    {
      m_importStack.push(hrefUrl);
    }
    
    /**
     * See if the imported stylesheet stack already contains 
     * the given URL.
     */
    boolean importStackContains(URL hrefUrl)
    {
      return stackContains(m_importStack, hrefUrl);
    }
    
    /**
     * Pop an import href from the stylesheet stack.
     */
    URL popImportURL()
    {
      return (URL)m_importStack.pop();
    }
  
    
    /**
     * If this is set to true, we've already warned about using the
     * older XSLT namespace URL.
     */
    private boolean warnedAboutOldXSLTNamespace = false;
    
    /**
     * Factory for creating xpaths.
     */
    private XPathFactory m_xpathFactory = SimpleNodeLocator.factory();
  
    /**
     * The query/pattern-matcher object.
     */
    private XPathParser m_xpathProcessor = new XPathParser();
    
    /**
     * Use the SAX2 helper class to track namespaces.
     */
    private NamespaceSupport m_nsSupport = new NamespaceSupport();
    
    /**
     * Get the NamespaceSupport object.
     */
    NamespaceSupport getNamespaceSupport()
    {
      return m_nsSupport;
    }
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/StylesheetProcessor.java
  
  Index: StylesheetProcessor.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import java.io.IOException;
  import org.xml.sax.InputSource;
  import org.xml.sax.helpers.XMLReaderFactory;
  import org.xml.sax.XMLReader;
  import org.xml.sax.SAXException;
  
  import org.w3c.dom.Node;
  
  import trax.Processor;
  import trax.ProcessorException;
  import trax.Templates;
  import trax.TemplatesBuilder;
  
  /**
   * The StylesheetProcessor, which implements the TRaX Processor 
   * interface, processes XSLT Stylesheets into a Templates object.
   */
  public class StylesheetProcessor extends Processor
  {
    /**
     * Process the source into a templates object.
     * 
     * @param source An object that holds a URL, input stream, etc.
     * @returns A Templates object capable of being used for transformation 
purposes.
     */
    public Templates process(InputSource source)
      throws ProcessorException, SAXException, IOException
    {
      TemplatesBuilder builder = getTemplatesBuilder();
      builder.setBaseID(source.getSystemId());
      XMLReader reader = this.getXMLReader();
      if(null == reader)
      {
        reader = XMLReaderFactory.createXMLReader();
      }
      reader.setContentHandler(builder);
      reader.parse(source);
      return builder.getTemplates();
    }
  
    /**
     * Process the stylesheet from a DOM tree, if the 
     * processor supports the "http://xml.org/trax/features/dom/input"; 
     * feature.    
     * 
     * @param node A DOM tree which must contain 
     * valid transform instructions that this processor understands.
     * @returns A Templates object capable of being used for transformation 
purposes.
     */
    public Templates processFromNode(Node node)
      throws ProcessorException
    {
      return null;
    }
  
    /**
     * Process a series of inputs, treating them in import or cascade 
     * order.  This is mainly for support of the getAssociatedStylesheets
     * method, but may be useful for other purposes.
     * 
     * @param sources An array of SAX InputSource objects.
     * @returns A Templates object capable of being used for transformation 
purposes.
     */
    public Templates processMultiple(InputSource[] source)
      throws ProcessorException
    {
      return null;
    }
  
    /**
     * Get InputSource specification(s) that are associated with the 
     * given document specified in the source param,
     * via the xml-stylesheet processing instruction 
     * (see http://www.w3.org/TR/xml-stylesheet/), and that matches 
     * the given criteria.  Note that it is possible to return several 
stylesheets 
     * that match the criteria, in which case they are applied as if they were 
     * a list of imports or cascades.
     * <p>Note that DOM2 has it's own mechanism for discovering stylesheets. 
     * Therefore, there isn't a DOM version of this method.</p>
     * 
     * <h3>Open issues:</h3>
     * <dl>
   *    <dt><h4>Does the xml-stylesheet recommendation really support multiple 
stylesheets?</h4></dt>
     *    <dd>Mike Kay wrote:  I don't see any support in the
     *        xml-stylesheet recommendation for this interpretation of what you 
should do
     *        if there's more than one match. Scott Boag replies: It's in the 
HTML references.  
     *        But it's a bit subtle.  We talked about this at the last XSL WG 
F2F, and people 
     *        agreed to the multiple stylesheet stuff.  I'll try and work out 
the specific 
     *        references.  Probably the xml-stylesheet recommendation needs to 
have a note 
     *        added to it.</dd>
     * </dl>
   * 
     * @param media The media attribute to be matched.  May be null, in which 
     *              case the prefered templates will be used (i.e. alternate = 
no).
     * @param title The value of the title attribute to match.  May be null.
     * @param charset The value of the charset attribute to match.  May be null.
     * @returns An array of InputSources that can be passed to processMultiple 
method.
     */
    public InputSource[] getAssociatedStylesheets(InputSource source,
                                                        String media, 
                                                        String title,
                                                        String charset)
      throws ProcessorException
    {
      return null;
    }
    
    /**
     * Get a TemplatesBuilder object that can process SAX 
     * events into a Templates object, if the processor supports the 
     * "http://xml.org/trax/features/sax/input"; feature.
     * 
     * <h3>Open issues:</h3>
     * <dl>
   *    <dt><h4>Should Processor derive from 
org.xml.sax.ContentHandler?</h4></dt>
     *    <dd>Instead of requesting an object from the Processor class, should 
     *        the Processor class simply derive from 
org.xml.sax.ContentHandler?</dd>
     * </dl>
   * @return A TemplatesBuilder object, or null if not supported.
     * @exception May throw a ProcessorException if a StylesheetHandler can 
     * not be constructed for some reason.
     */
    public TemplatesBuilder getTemplatesBuilder()
      throws ProcessorException
    {
      return new StylesheetHandler(this);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/TemplateElementFactory.java
  
  Index: TemplateElementFactory.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  public class TemplateElementFactory
  {
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/XSLProcessorVersion.java
  
  Index: XSLProcessorVersion.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  /**
   * <meta name="usage" content="general"/>
   * Administrative class to keep track of the version number of
   * the Xalan release.
   * <P>See also: org/apache/xalan/res/XSLTInfo.properties</P>
   */
  public class XSLProcessorVersion
  {
    /**
     * Print the processor version to the command line.
     */
    public static void main( String argv[] )
    {
      System.out.println(PRODUCT + " "+LANGUAGE+" Version "+S_VERSION);
    }
    
    /**
     * Version String like <CODE>"<B>Xalan</B>i v.r[.dd| <B>D</B>nn]"</CODE>.
     * <P>Semantics of the version string are identical to the Xerces 
project.</P>
     */
    public static String S_VERSION = "1.1D01";
  
    /**
     * Constant name of product.
     */
    public static final String PRODUCT = "Xalan";
  
    /**
     * Implementation Language.
     */
    public static String LANGUAGE = "Java";
  
    /**
     * Major version number.
     * Version number. This changes only when there is a
     *          significant, externally apparent enhancement from
     *          the previous release. 'n' represents the n'th
     *          version.
     *
     *          Clients should carefully consider the implications
     *          of new versions as external interfaces and behaviour
     *          may have changed.
     */
    public static int VERSION = 1;
  
    /**
     * Release Number.
     * Release number. This changes when:
     *            -  a new set of functionality is to be added, eg,
     *               implementation of a new W3C specification.
     *            -  API or behaviour change.
     *            -  its designated as a reference release.
     */
    public static int RELEASE = 1;
  
    /**
     * Maintenance Drop Number.
     * Optional identifier used to designate maintenance
     *          drop applied to a specific release and contains
     *          fixes for defects reported. It maintains compatibility
     *          with the release and contains no API changes.
     *          When missing, it designates the final and complete
     *          development drop for a release.
     */
    public static int MAINTENANCE = 0;
  
    /**
     * Development Drop Number.
     * Optional identifier designates development drop of
     *          a specific release. D01 is the first development drop
     *          of a new release.
     *
     *          Development drops are works in progress towards a
     *          compeleted, final release. A specific development drop
     *
     *          may not completely implement all aspects of a new
     *          feature, which may take several development drops to
     *          complete. At the point of the final drop for the
     *          release, the D suffix will be omitted.
     *
     *          Each 'D' drops can contain functional enhancements as
     *          well as defect fixes. 'D' drops may not be as stable as
     *          the final releases.
     */
    public static int DEVELOPMENT = 1;
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/XSLTAttributeDef.java
  
  Index: XSLTAttributeDef.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.utils.StringToIntTable;
  import java.lang.IllegalAccessException;
  import java.lang.IndexOutOfBoundsException;
  import java.lang.InstantiationException;
  import java.lang.NoSuchMethodException;
  import java.lang.reflect.InvocationTargetException;
  import java.lang.reflect.Method;
  import java.lang.StringBuffer;
  import java.net.URL;
  import java.util.StringTokenizer;
  import java.util.Vector;
  import org.apache.xalan.templates.AVT;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.utils.SystemIDResolver;
  import org.apache.xalan.utils.StringVector;
  import org.apache.xalan.xpath.XPath;
  import org.xml.sax.SAXException;
  
  /**
   * This class defines an attribute for an element in a XSLT stylesheet, 
   * is meant to reflect the structure defined in 
http://www.w3.org/TR/xslt#dtd, and the 
   * mapping between Xalan classes and the markup attributes in the element.
   */
  public class XSLTAttributeDef
  {
    /**
     * Construct an instance of XSLTAttributeDef.
     */
    XSLTAttributeDef(String namespace, String name, int type, boolean required)
    {
      this.m_namespace = namespace;
      this.m_name = name;
      this.m_type = type;
      this.m_required = required;
    }
  
    /**
     * Construct an instance of XSLTAttributeDef.
     */
    XSLTAttributeDef(String namespace, String name, int type, String defaultVal)
    {
      this.m_namespace = namespace;
      this.m_name = name;
      this.m_type = type;
      this.m_required = false;
      this.m_default = defaultVal;
    }
  
    /**
     * Construct an instance of XSLTAttributeDef that uses two 
     * enumerated values.
     */
    XSLTAttributeDef(String namespace, String name, boolean required,
                     String k1, int v1,
                     String k2, int v2)
    {
      this.m_namespace = namespace;
      this.m_name = name;
      this.m_type = this.T_ENUM;
      this.m_required = required;
      m_enums = new StringToIntTable(2);
      m_enums.put(k1, v1);
      m_enums.put(k2, v2);
    }
  
    /**
     * Construct an instance of XSLTAttributeDef that uses three 
     * enumerated values.
     */
    XSLTAttributeDef(String namespace, String name, boolean required,
                     String k1, int v1,
                     String k2, int v2,
                     String k3, int v3)
    {
      this.m_namespace = namespace;
      this.m_name = name;
      this.m_type = this.T_ENUM;
      this.m_required = required;
      m_enums = new StringToIntTable(3);
      m_enums.put(k1, v1);
      m_enums.put(k2, v2);
      m_enums.put(k3, v3);
    }
  
    /**
     * Construct an instance of XSLTAttributeDef that uses three 
     * enumerated values.
     */
    XSLTAttributeDef(String namespace, String name, boolean required,
                     String k1, int v1,
                     String k2, int v2,
                     String k3, int v3,
                     String k4, int v4)
    {
      this.m_namespace = namespace;
      this.m_name = name;
      this.m_type = this.T_ENUM;
      this.m_required = required;
      m_enums = new StringToIntTable(4);
      m_enums.put(k1, v1);
      m_enums.put(k2, v2);
      m_enums.put(k3, v3);
      m_enums.put(k4, v4);
    }
  
    static final int 
      T_CDATA = 1,
      
      // <!-- Used for the type of an attribute value that is a URI 
reference.-->
      T_URL = 2,
      
      // <!-- Used for the type of an attribute value that is an
      // attribute value template.-->
      T_AVT = 3, // Attribute Value Template
      
      // <!-- Used for the type of an attribute value that is a pattern.-->
      T_PATTERN = 4,
      
      // <!-- Used for the type of an attribute value that is an expression.-->
      T_EXPR = 5,
      
      // <!-- Used for the type of an attribute value that consists
      // of a single character.-->
      T_CHAR = 6, 
      
      // <!-- Used for the type of an attribute value that is a priority. -->
      T_PRIORITY = 7,
      
      // Used for boolean values
      T_YESNO = 8,
      
      // <!-- Used for the type of an attribute value that is a QName; the 
prefix
      // gets expanded by the XSLT processor. -->
      T_QNAME = 9,
      
      // <!-- Like qname but a whitespace-separated list of QNames. -->
      T_QNAMES = 10,
      
      // <!-- Used for enumerated values -->
      T_ENUM = 11,
      
      // Used for simple match patterns, i.e. xsl:strip-space spec.
      T_SIMPLEPATTERNLIST = 12,
      
      // Used for a known token.
      T_NMTOKEN = 13,
  
      // Used for a list of white-space delimited strings.
      T_STRINGLIST = 14
      ;
  
    static XSLTAttributeDef m_foreignAttr 
      = new XSLTAttributeDef("*", "*", XSLTAttributeDef.T_CDATA, false);
  
    /**
     * The allowed namespace for this element.
     */
    private String m_namespace;
    
    /**
     * Get the allowed namespace for this element.
     */
    String getNamespace() {return m_namespace; }
    
    /**
     * The name of this element.
     */
    private String m_name;
    
    /**
     * Get the name of this element.
     */
    String getName() {return m_name; }
    
    /**
     * The type of this attribute value.
     */
    private int m_type;
    
    /**
     * Get the type of this attribute value.
     */
    int getType() {return m_type; }
    
    /**
     * If this element is of type T_ENUM, this will contain 
     * a map from the attribute string to the Xalan integer 
     * value.
     */
    private StringToIntTable m_enums;
  
    /**
     * If this element is of type T_ENUM, this will return 
     * a map from the attribute string to the Xalan integer 
     * value.
     * @param key The XSLT attribute value.
     * @exception Throws NullPointerException if m_enums is null.
     */
    private int getEnum(String key) { return m_enums.get(key); }
    
    /**
     * The default value for this attribute.
     */
    private String m_default;
    
    /**
     * Get the default value for this attribute.
     */
    String getDefault() { return m_default; }
  
    
    /**
     * Set the default value for this attribute.
     */
    void setDefault(String def) { m_default = def; }
  
    /**
     * If true, this is a required attribute.
     */
    private boolean m_required;
    
    /**
     * Get whether or not this is a required attribute.
     */
    boolean getRequired() { return m_required; }
    
    String m_setterString = null;
  
    /**
     * Return a string that should represent the setter method.  
     * The setter method name will be created algorithmically
     */
    public String getSetterMethodName()
    {
      if(null == m_setterString)
      {
        if(m_foreignAttr == this)
        {
          return null;
        }
        else if(m_name.equals("*"))
        {
          m_setterString = "addLiteralResultAttribute";
          return m_setterString;
        }
        StringBuffer outBuf = new StringBuffer();
        outBuf.append("set");
        int n = m_name.length();
        for(int i = 0; i < n; i++)
        {
          char c = m_name.charAt(i);
          if('-' == c)
          {
            i++;
            c = m_name.charAt(i);
            c = Character.toUpperCase(c);
          }
          else if(0 == i)
          {
            c = Character.toUpperCase(c);
          }
          outBuf.append(c);
        }
        m_setterString = outBuf.toString();
      }
      return m_setterString;
    }
    
    /**
     * Process an attribute string of type T_AVT into 
     * a AVT value.
     */
    AVT processAVT(StylesheetHandler handler,
                      String uri, String name,
                      String rawName, String value)
      throws SAXException
    {
      AVT avt = new AVT(handler, uri, name, rawName, value);
      return avt;
    }
    
    /**
     * Process an attribute string of type T_CDATA into 
     * a String value.
     */
    Object processCDATA(StylesheetHandler handler,
                        String uri, String name,
                        String rawName, String value)
      throws SAXException
    {
      return value;
    }
    
    /**
     * Process an attribute string of type T_CHAR into 
     * a Character value.
     */
    Object processCHAR(StylesheetHandler handler,
                       String uri, String name,
                       String rawName, String value)
      throws SAXException
    {  
      if(value.length() != 1)
      {
        handler.error("An XSLT attribute of type T_CHAR must be only 1 
character!", null);
      }
      
      return new Character(value.charAt(0));
    }
    
    /**
     * Process an attribute string of type T_ENUM into 
     * a int value.
     */
    Object processENUM(StylesheetHandler handler,
                       String uri, String name,
                       String rawName, String value)
      throws SAXException
    {
      int enum = this.getEnum(value);
      return new Integer(enum);
    }
    
    /**
     * Process an attribute string of type T_EXPR into 
     * an XPath value.
     */
    Object processEXPR(StylesheetHandler handler,
                       String uri, String name,
                       String rawName, String value)
      throws SAXException
    {
      XPath expr = handler.createXPath(value);
      return expr;
    }
    
    /**
     * Process an attribute string of type T_NMTOKEN into 
     * a String value.
     */
    Object processNMTOKEN(StylesheetHandler handler,
                          String uri, String name,
                          String rawName, String value)
      throws SAXException
    {
      return value;
    }
    
    /**
     * Process an attribute string of type T_PATTERN into 
     * an XPath match pattern value.
     */
    Object processPATTERN(StylesheetHandler handler,
                          String uri, String name,
                          String rawName, String value)
      throws SAXException
    {
      XPath pattern = handler.createMatchPatternXPath(value);
      return pattern;
    }
    
    /**
     * Process an attribute string of type T_PRIORITY into 
     * a double value.
     */
    Object processPRIORITY(StylesheetHandler handler,
                           String uri, String name,
                           String rawName, String value)
      throws SAXException
    {
      return Double.valueOf(value);
    }
    
    /**
     * Process an attribute string of type T_QNAME into 
     * a QName value.
     */
    Object processQNAME(StylesheetHandler handler,
                        String uri, String name,
                        String rawName, String value)
      throws SAXException
    {
      return new QName(value, handler);
    }
    
    /**
     * Process an attribute string of type T_QNAMES into 
     * a vector of QNames.
     */
    Vector processQNAMES(StylesheetHandler handler,
                         String uri, String name,
                         String rawName, String value)
      throws SAXException
    {
      StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
      int nQNames = tokenizer.countTokens();
      Vector qnames = new Vector(nQNames);
      for(int i = 0; i < nQNames; i++)
      {
        qnames.addElement(new QName(tokenizer.nextToken()));
      }
      return qnames;
    }
    
    /**
     * Process an attribute string of type T_SIMPLEPATTERNLIST into 
     * a vector of XPath match patterns.
     */
    Vector processSIMPLEPATTERNLIST(StylesheetHandler handler,
                                    String uri, String name,
                                    String rawName, String value)
      throws SAXException
    {
      StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
      int nPatterns = tokenizer.countTokens();
      Vector patterns = new Vector(nPatterns);
      for(int i = 0; i < nPatterns; i++)
      {
        XPath pattern = handler.createMatchPatternXPath(tokenizer.nextToken());
        patterns.addElement(pattern);
      }
      return patterns;
    }
    
    /**
     * Process an attribute string of type T_STRINGLIST into 
     * a vector of XPath match patterns.
     */
    StringVector processSTRINGLIST(StylesheetHandler handler,
                                    String uri, String name,
                                    String rawName, String value)
      throws SAXException
    {
      StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
      int nStrings = tokenizer.countTokens();
      StringVector strings = new StringVector(nStrings);
      for(int i = 0; i < nStrings; i++)
      {
        strings.addElement(tokenizer.nextToken());
      }
      return strings;
    }
    
    /**
     * Process an attribute string of type T_URL into 
     * a URL value.
     */
    URL processURL(StylesheetHandler handler,
                      String uri, String name,
                      String rawName, String value)
      throws SAXException
    {
      return SystemIDResolver.getURLFromString(value, 
                                               handler.getBaseIdentifier());
    }
    
    /**
     * Process an attribute string of type T_YESNO into 
     * a Boolean value.
     */
    private Boolean processYESNO(StylesheetHandler handler,
                         String uri, String name,
                         String rawName, String value)
      throws SAXException
    {
      return new Boolean(value.equals("yes") ? true : false);
    }
    
    /**
     * Process an attribute value.
     */
    Object processValue(StylesheetHandler handler,
                        String uri, String name,
                        String rawName, String value)
      throws SAXException
    {
      int type = getType();
      Object processedValue = null;
      switch(type)
      {
      case T_AVT:
        processedValue = processAVT(handler, uri, name, rawName, value);
        break;
      case T_CDATA:
        processedValue = processCDATA(handler, uri, name, rawName, value);
        break;
      case T_CHAR:
        processedValue = processCHAR(handler, uri, name, rawName, value);
        break;
      case T_ENUM:
        processedValue = processENUM(handler, uri, name, rawName, value);
        break;
      case T_EXPR:
        processedValue = processEXPR(handler, uri, name, rawName, value);
        break;
      case T_NMTOKEN:
        processedValue = processNMTOKEN(handler, uri, name, rawName, value);
        break;
      case T_PATTERN:
        processedValue = processPATTERN(handler, uri, name, rawName, value);
        break;
      case T_PRIORITY:
        processedValue = processPRIORITY(handler, uri, name, rawName, value);
        break;
      case T_QNAME:
        processedValue = processQNAME(handler, uri, name, rawName, value);
        break;
      case T_QNAMES:
        processedValue = processQNAMES(handler, uri, name, rawName, value);
        break;
      case T_SIMPLEPATTERNLIST:
        processedValue = processSIMPLEPATTERNLIST(handler, uri, name, rawName, 
value);
        break;
      case T_URL:
        processedValue = processURL(handler, uri, name, rawName, value);
        break;
      case T_YESNO:
        processedValue = processYESNO(handler, uri, name, rawName, value);
        break;
      case T_STRINGLIST:
        processedValue = processSTRINGLIST(handler, uri, name, rawName, value);
        break;
      default:
      }
      return processedValue;
    }
    
    /**
     * Set the default value of an attribute.
     */
    void setDefAttrValue(StylesheetHandler handler,
                         Object elem)
      throws SAXException
    {
      setAttrValue(handler, this.getNamespace(), this.getName(), this.getName(),
                      this.getDefault(), elem);
    }
    
    /**
     * Get the primative type for the class, if there 
     * is one.  If the class is a Double, for instance, 
     * this will return double.class.  If the class is not one 
     * of the 9 primative types, it will return the same 
     * class that was passed in.
     */
    private Class getPrimativeClass(Object obj)
    {
      if(obj instanceof XPath)
        return XPath.class;
      
      Class cl = obj.getClass();
      if (cl == Double.class) 
      {
        cl = double.class;
      }
      if (cl == Float.class) 
      {
        cl = float.class;
      }
      else if (cl == Boolean.class) 
      {
        cl = boolean.class;
      }
      else if (cl == Byte.class) 
      {
        cl = byte.class;
      }
      else if (cl == Character.class) 
      {
        cl = char.class;
      }
      else if (cl == Short.class) 
      {
        cl = short.class;
      }
      else if (cl == Integer.class) 
      {
        cl = int.class;
      }
      else if (cl == Long.class) 
      {
        cl = long.class;
      }
      return cl;
    }
    
    /**
     * Set a value on an attribute.
     */
    void setAttrValue(StylesheetHandler handler,
                      String attrUri, String attrLocalName, String attrRawName,
                      String attrValue, 
                      Object elem)
      throws SAXException
    {
      String setterString = getSetterMethodName();
      
      // If this is null, then it is a foreign namespace and we 
      // do not process it.
      if(null != setterString)
      {
        Object value = processValue(handler,
                                            attrUri, attrLocalName,
                                            attrRawName, 
                                            attrValue);
        try
        {
          Method meth;
          // First try to match with the primative value.
          Class[] argTypes = new Class[] { getPrimativeClass(value) };
          try
          {
            meth = elem.getClass().getMethod(setterString, argTypes);
          }
          catch(NoSuchMethodException nsme)
          {
            Class cl = ((Object)value).getClass();
            // If this doesn't work, try it with the non-primative value;
            argTypes[0] = cl;
            meth = elem.getClass().getMethod(setterString, argTypes);
          }
          Object[] args = new Object[] { value };
          meth.invoke(elem, args);
        }
        catch(NoSuchMethodException nsme)
        {
          handler.error("Failed calling "+setterString+" method!", nsme);
        }
        catch(IllegalAccessException iae)
        {
          handler.error("Failed calling "+setterString+" method!", iae);
        }
        catch(InvocationTargetException nsme)
        {
          handler.error("Failed calling "+setterString+" method!", nsme);
        }
      }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/XSLTElementDef.java
  
  Index: XSLTElementDef.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.xml.sax.ContentHandler;
  import org.apache.xalan.templates.Constants;
  
  /**
   * This class defines the allowed structure for an element in a XSLT 
stylesheet, 
   * is meant to reflect the structure defined in 
http://www.w3.org/TR/xslt#dtd, and the 
   * mapping between Xalan classes and the markup elements in the XSLT instance.
   * This actually represents both text nodes and elements.
   */
  class XSLTElementDef
  {
    
    /**
     * Construct an instance of XSLTElementDef.  This must be followed by a
     * call to build().
     */
    XSLTElementDef()
    {
    }
  
    /**
     * Construct an instance of XSLTElementDef.
     */
    XSLTElementDef(String namespace, String name, String nameAlias,
                  XSLTElementDef[] elements,
                  XSLTAttributeDef[] attributes, 
                  XSLTElementProcessor contentHandler,
                  Class classObject)
    {
      build(namespace, name, nameAlias, elements,
            attributes, contentHandler, classObject);
    }
    
    /**
     * Construct an instance of XSLTElementDef that represents text.
     */
    XSLTElementDef(Class classObject, 
                   XSLTElementProcessor contentHandler, int type)
    {
      this.m_classObject = classObject;
      this.m_type = type;
      setElementProcessor(contentHandler);
    }
  
  
    /**
     * Construct an instance of XSLTElementDef.
     */
    void build(String namespace, String name, String nameAlias,
                  XSLTElementDef[] elements,
                  XSLTAttributeDef[] attributes, 
                  XSLTElementProcessor contentHandler,
                  Class classObject)
    {
      this.m_namespace = namespace;
      this.m_name = name;
      this.m_nameAlias = nameAlias;
      this.m_elements = elements;
      this.m_attributes = attributes;
      setElementProcessor(contentHandler);
      this.m_classObject = classObject;
    }
    
    /**
     * Tell if two objects are equal, when either one may be null. 
     * If both are null, they are considered equal.
     */
    private static boolean equalsMayBeNull(Object obj1, Object obj2)
    {
      return ((null == obj1) && (null == obj2)) ||
             ((null != obj1) && (null != obj2) && obj2.equals(obj1));
    }
  
    /**
     * Tell if the two string refs are equal, 
     * equality being defined as:
     * 1) Both strings are null.
     * 2) One string is null and the other is empty.
     * 3) Both strings are non-null, and equal.
     */
    private static boolean equalsMayBeNullOrZeroLen( String s1, String s2 )
    {
      int len1 = (s1 == null) ? 0 : s1.length();
      int len2 = (s2 == null) ? 0 : s2.length();
      return (len1 != len2) ? false : (len1 == 0) ? true : s1.equals(s2);
    }
    
    static final int 
      T_ELEMENT = 1,
      T_PCDATA = 2,
      T_ANY = 3;
      
    /**
     * The type of this element.
     */
    private int m_type = T_ELEMENT;
    
    /**
     * Get the type of this element.
     */
    int getType() {return m_type; }
    
    /**
     * Set the type of this element.
     */
    void setType(int t) { m_type = t; }
  
  
    /**
     * The allowed namespace for this element.
     */
    private String m_namespace;
    
    /**
     * Get the allowed namespace for this element.
     */
    String getNamespace() {return m_namespace; }
    
    /**
     * The name of this element.
     */
    private String m_name;
    
    /**
     * Get the name of this element.
     */
    String getName() {return m_name; }
  
    /**
     * The name of this element.
     */
    private String m_nameAlias;
    
    /**
     * Get the name of this element.
     */
    String getNameAlias() {return m_nameAlias; }
  
    /**
     * The allowed elements for this type.
     */
    private XSLTElementDef[] m_elements;
    
    /**
     * Get the allowed elements for this type.
     */
    XSLTElementDef[] getElements() { return m_elements; }
  
    /**
     * Set the allowed elements for this type.
     */
    void setElements(XSLTElementDef[] defs) { m_elements = defs; }
  
    /**
     * Tell if the namespace URI and local name match this 
     * element.
     * @param uri The namespace uri, which may be null.
     * @param localName The local name of an element, which may be null.
     */
    private boolean QNameEquals( String uri, String localName )
    {
      return (equalsMayBeNullOrZeroLen(m_namespace, uri) &&
             (equalsMayBeNullOrZeroLen(m_name, localName) ||
              equalsMayBeNullOrZeroLen(m_nameAlias, localName)));
    }
    
    /**
     * Given a namespace URI, and a local name, get the processor 
     * for the element, or return null if not allowed.
     */
    XSLTElementProcessor getProcessorFor( String uri, String localName )
    {
      XSLTElementProcessor lreDef = null; // return value
      if(null == m_elements)
        return null;
      int n = m_elements.length;
      for(int i = 0; i < n; i++)
      {
        XSLTElementDef def = m_elements[i];
        // A "*" signals that the element allows literal result
        // elements, so just assign the def, and continue to  
        // see if anything else matches.
        if(def.m_name.equals("*"))
          lreDef = def.m_elementProcessor;
        else if(def.QNameEquals(uri, localName))
          return def.m_elementProcessor;
      }
      return lreDef;
    }
      
    /**
     * The allowed attributes for this type.
     */
    private XSLTAttributeDef[] m_attributes;
    
    /**
     * Get the allowed attributes for this type.
     */
    XSLTAttributeDef[] getAttributes() {return m_attributes; }
    
    /**
     * Given a namespace URI, and a local name, return the element's 
     * attribute definition, if it has one.
     */
    XSLTAttributeDef getAttributeDef( String uri, String localName )
    {
      XSLTAttributeDef defaultDef = null;
      XSLTAttributeDef[] attrDefs = getAttributes();
      int nAttrDefs = attrDefs.length;
      for(int k = 0; k < nAttrDefs; k++)
      {
        XSLTAttributeDef attrDef = attrDefs[k];
        String uriDef = attrDef.getNamespace();
        String nameDef = attrDef.getName();
        if(nameDef.equals("*"))
        {
          // In this case, all attributes are legal, so return 
          // this as the last resort.
          defaultDef = attrDef;
        }
        else if(equalsMayBeNullOrZeroLen(uri, uriDef) && 
localName.equals(nameDef))
        {
          return attrDef;
        }
      }
      if(null == defaultDef)
      {
        if(!equalsMayBeNullOrZeroLen(uri, Constants.S_XSLNAMESPACEURL))
        {
          return XSLTAttributeDef.m_foreignAttr;
        }
      }
      return defaultDef;
    }
  
    
    /**
     * If non-null, the ContentHandler/Processor for this element.
     */
    private XSLTElementProcessor m_elementProcessor;
  
    /**
     * Return the ContentHandler/Processor for this element.
     */
    XSLTElementProcessor getElementProcessor() {return m_elementProcessor; }
  
    /**
     * Return the ContentHandler/Processor for this element.
     */
    void setElementProcessor(XSLTElementProcessor handler) 
    {
      m_elementProcessor = handler; 
      m_elementProcessor.setElemDef(this);
    }
  
    /**
     * If non-null, the class object that should in instantiated for 
     * a Xalan instance of this element.
     */
    private Class m_classObject;
    
    /**
     * Return the class object that should in instantiated for 
     * a Xalan instance of this element.
     */
    Class getClassObject() {return m_classObject; }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/XSLTElementProcessor.java
  
  Index: XSLTElementProcessor.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.xml.sax.InputSource;
  import org.xml.sax.Locator;
  import org.xml.sax.Attributes;
  import org.xml.sax.EntityResolver;
  import org.xml.sax.DTDHandler;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.SAXException;
  import org.xml.sax.SAXParseException;
  import java.util.Vector;
  
  /**
   * This class acts as the superclass for all stylesheet element 
   * processors, and deals with things that are common to all elements.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   */
  public class XSLTElementProcessor
  {    
    /**
     * Construct a processor for top-level elements.
     * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
     */
    XSLTElementProcessor()
    {
    }
    
    /**
     * The element definition that this processor conforms to.
     */
    private XSLTElementDef m_elemDef;
  
    /**
     * Get the element definition that belongs to this element.
     */
    XSLTElementDef getElemDef()
    {
      return m_elemDef;
    }
  
    /**
     * Set the element definition that belongs to this element.
     */
    void setElemDef(XSLTElementDef def)
    {
      m_elemDef = def;
    }
    
    /**
     * Resolve an external entity.
     *
     * @param publicId The public identifer, or null if none is
     *                 available.
     * @param systemId The system identifier provided in the XML 
     *                 document.
     * @return The new input source, or null to require the
     *         default behaviour.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.EntityResolver#resolveEntity
     */
    public InputSource resolveEntity (StylesheetHandler handler, 
                                      String publicId, String systemId)
      throws SAXException
    {
      return null;
    }
    
    
    /**
     * Receive notification of a notation declaration.
     *
     * @param name The notation name.
     * @param publicId The notation public identifier, or null if not
     *                 available.
     * @param systemId The notation system identifier.
     * @see org.xml.sax.DTDHandler#notationDecl
     */
    public void notationDecl (StylesheetHandler handler, 
                              String name, String publicId, String systemId)
    {
      // no op
    }
    
    
    /**
     * Receive notification of an unparsed entity declaration.
     *
     * @param name The entity name.
     * @param publicId The entity public identifier, or null if not
     *                 available.
     * @param systemId The entity system identifier.
     * @param notationName The name of the associated notation.
     * @see org.xml.sax.DTDHandler#unparsedEntityDecl
     */
    public void unparsedEntityDecl (StylesheetHandler handler, 
                                    String name, String publicId,
                                    String systemId, String notationName)
    {
      // no op
    }
    
    /**
     * Receive notification of the start of the non-text event.  This 
     * is sent to the current processor when any non-text event occurs.
     */
    public void startNonText(StylesheetHandler handler)
      throws SAXException
    {
      // no op
    }
  
    /**
     * Receive notification of the start of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#startElement
     */
    public void startElement (StylesheetHandler handler, 
                              String uri, String localName,
                              String rawName, Attributes attributes)
      throws SAXException
    {
      // no op
    }
    
    
    /**
     * Receive notification of the end of an element.
     *
     * @param name The element type name.
     * @param attributes The specified or defaulted attributes.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#endElement
     */
    public void endElement (StylesheetHandler handler, 
                            String uri, String localName, String rawName)
      throws SAXException
    {
      // no op
    }
    
    
    /**
     * Receive notification of character data inside an element.
     *
     * @param ch The characters.
     * @param start The start position in the character array.
     * @param length The number of characters to use from the
     *               character array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#characters
     */
    public void characters (StylesheetHandler handler, 
                            char ch[], int start, int length)
      throws SAXException
    {
      handler.error("Characters are not allowed at this point in the 
document!", null);
    }
    
    
    /**
     * Receive notification of ignorable whitespace in element content.
     *
     * @param ch The whitespace characters.
     * @param start The start position in the character array.
     * @param length The number of characters to use from the
     *               character array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#ignorableWhitespace
     */
    public void ignorableWhitespace (StylesheetHandler handler, 
                                     char ch[], int start, int length)
      throws SAXException
    {
      // no op
    }
    
    
    /**
     * Receive notification of a processing instruction.
     *
     * @param target The processing instruction target.
     * @param data The processing instruction data, or null if
     *             none is supplied.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#processingInstruction
     */
    public void processingInstruction (StylesheetHandler handler, 
                                       String target, String data)
      throws SAXException
    {
      // no op
    }
  
  
    /**
     * Receive notification of a skipped entity.
     *
     * @param name The name of the skipped entity.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.ContentHandler#processingInstruction
     */
    public void skippedEntity (StylesheetHandler handler, 
                               String name)
      throws SAXException
    {
      // no op
    }
    
    /**
     * Set the properties of an object from the given attribute list.
     * @param handler The stylesheet's Content handler, needed for 
     *                error reporting.
     * @param rawName The raw name of the owner element, needed for 
     *                error reporting.
     * @param attributes The list of attributes.
     * @param target The target element where the properties will be set.
     */
    void setPropertiesFromAttributes(StylesheetHandler handler,
                                     String rawName,
                                     Attributes attributes, 
                                     Object target)
      throws SAXException
    {
      XSLTElementDef def = getElemDef();
  
      // Keep track of which XSLTAttributeDefs have been processed, so 
      // I can see which default values need to be set.
      Vector processedDefs = new Vector();
      int nAttrs = attributes.getLength();
      for(int i = 0; i < nAttrs; i++)
      {
        String attrUri = attributes.getURI(i);
        String attrLocalName = attributes.getLocalName(i);
        XSLTAttributeDef attrDef = def.getAttributeDef( attrUri, attrLocalName 
);
        
        if(null == attrDef)
        {
          // Then barf, because this element does not allow this attribute.
          handler.error(attributes.getQName(i)+
                        "attribute is not allowed on the "+
                rawName+" element!", null);
        }
        else
        {
          processedDefs.addElement(attrDef);
          attrDef.setAttrValue(handler, attrUri, attrLocalName,
                               attributes.getQName(i), 
                               attributes.getValue(i),
                               target);
        }
      }
      
      XSLTAttributeDef[] attrDefs = def.getAttributes();
      int nAttrDefs = attrDefs.length;
      for(int i = 0; i < nAttrDefs; i++)
      {
        XSLTAttributeDef attrDef = attrDefs[i];
        String defVal = attrDef.getDefault();
        if(null != defVal)
        {
          if(!processedDefs.contains(attrDef))
          {
            attrDef.setDefAttrValue(handler, target);
          }
        }
      }
  
    }
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/processor/XSLTSchema.java
  
  Index: XSLTSchema.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.processor;
  
  import org.apache.xalan.templates.*;
  
  /**
   * This class defines the allowed structure for a stylesheet, and the 
   * mapping between Xalan classes and the markup elements in the stylesheet.
   * @see <a href="http://www.w3.org/TR/xslt#dtd";>XSLT DTD</a>
   */
  public class XSLTSchema extends XSLTElementDef
  {
    /**
     * Construct a XSLTSchema which represents the XSLT "schema".
     */
    XSLTSchema()
    {
      build();
    }
    
    /**
     * This method builds an XSLT "schema" according to 
http://www.w3.org/TR/xslt#dtd.  This 
     * schema provides instructions for building the Xalan Stylesheet 
(Templates) structure.
     */
    void build()
    {
      XSLTAttributeDef hrefAttr 
        = new XSLTAttributeDef(null, "href", XSLTAttributeDef.T_URL, true);
                                
      XSLTAttributeDef elementsAttr 
        = new XSLTAttributeDef(null, "elements", 
XSLTAttributeDef.T_SIMPLEPATTERNLIST, true);
  
      XSLTAttributeDef methodAttr 
        = new XSLTAttributeDef(null, "method", XSLTAttributeDef.T_QNAME, false);
      XSLTAttributeDef versionAttr 
        = new XSLTAttributeDef(null, "version", XSLTAttributeDef.T_NMTOKEN, 
false);
      XSLTAttributeDef encodingAttr 
        = new XSLTAttributeDef(null, "encoding", XSLTAttributeDef.T_CDATA, 
false);
      XSLTAttributeDef omitXmlDeclarationAttr 
        = new XSLTAttributeDef(null, "omit-xml-declaration", 
XSLTAttributeDef.T_YESNO, false);
      XSLTAttributeDef standaloneAttr 
        = new XSLTAttributeDef(null, "standalone", XSLTAttributeDef.T_YESNO, 
false);
      XSLTAttributeDef doctypePublicAttr 
        = new XSLTAttributeDef(null, "doctype-public", 
XSLTAttributeDef.T_CDATA, false);
      XSLTAttributeDef doctypeSystemAttr 
        = new XSLTAttributeDef(null, "doctype-system", 
XSLTAttributeDef.T_CDATA, false);
      XSLTAttributeDef cdataSectionElementsAttr 
        = new XSLTAttributeDef(null, "cdata-section-elements", 
XSLTAttributeDef.T_QNAMES, false);
      XSLTAttributeDef indentAttr 
        = new XSLTAttributeDef(null, "indent", XSLTAttributeDef.T_YESNO, false);
      XSLTAttributeDef mediaTypeAttr 
        = new XSLTAttributeDef(null, "media-type", XSLTAttributeDef.T_CDATA, 
false);
  
      XSLTAttributeDef nameAttrRequired
        = new XSLTAttributeDef(null, "name", XSLTAttributeDef.T_QNAME, true);
      XSLTAttributeDef nameAttrOpt
        = new XSLTAttributeDef(null, "name", XSLTAttributeDef.T_QNAME, false);
      XSLTAttributeDef useAttr 
        = new XSLTAttributeDef(null, "use", XSLTAttributeDef.T_EXPR, true);
  
      XSLTAttributeDef nameAVTRequired
        = new XSLTAttributeDef(null, "name", XSLTAttributeDef.T_AVT, true);
      XSLTAttributeDef namespaceAVTOpt
        = new XSLTAttributeDef(null, "namespace", XSLTAttributeDef.T_AVT, 
false);
  
      XSLTAttributeDef decimalSeparatorAttr 
        = new XSLTAttributeDef(null, "decimal-separator", 
XSLTAttributeDef.T_CHAR, ".");
      XSLTAttributeDef groupingSeparatorAttr 
        = new XSLTAttributeDef(null, "grouping-separator", 
XSLTAttributeDef.T_CHAR, ",");
      XSLTAttributeDef infinityAttr 
        = new XSLTAttributeDef(null, "infinity", XSLTAttributeDef.T_CDATA, 
"Infinity");
      XSLTAttributeDef minusSignAttr 
        = new XSLTAttributeDef(null, "minus-sign", XSLTAttributeDef.T_CHAR, 
"-");
      XSLTAttributeDef NaNAttr 
        = new XSLTAttributeDef(null, "NaN", XSLTAttributeDef.T_CDATA, "NaN");
      XSLTAttributeDef percentAttr 
        = new XSLTAttributeDef(null, "percent", XSLTAttributeDef.T_CHAR, "%");
      XSLTAttributeDef perMilleAttr 
        = new XSLTAttributeDef(null, "per-mille", XSLTAttributeDef.T_CHAR, 
false /* ,"&#x2030;" */);
      XSLTAttributeDef zeroDigitAttr 
        = new XSLTAttributeDef(null, "zero-digit", XSLTAttributeDef.T_CHAR, 
"0");
      XSLTAttributeDef digitAttr 
        = new XSLTAttributeDef(null, "digit", XSLTAttributeDef.T_CHAR, "#");
      XSLTAttributeDef patternSeparatorAttr 
        = new XSLTAttributeDef(null, "pattern-separator", 
XSLTAttributeDef.T_CHAR, ";");
  
      XSLTAttributeDef useAttributeSetsAttr 
        = new XSLTAttributeDef(null, "use-attribute-sets", 
XSLTAttributeDef.T_QNAMES, false);
  
      XSLTAttributeDef selectAttrRequired
        = new XSLTAttributeDef(null, "select", XSLTAttributeDef.T_EXPR, true);
      XSLTAttributeDef testAttrRequired
        = new XSLTAttributeDef(null, "test", XSLTAttributeDef.T_EXPR, true);
      XSLTAttributeDef selectAttrOpt
        = new XSLTAttributeDef(null, "select", XSLTAttributeDef.T_EXPR, false);
      XSLTAttributeDef selectAttrDefNode
        = new XSLTAttributeDef(null, "select", XSLTAttributeDef.T_EXPR, 
"node()");
      XSLTAttributeDef selectAttrDefDot
        = new XSLTAttributeDef(null, "select", XSLTAttributeDef.T_EXPR, ".");
  
      XSLTAttributeDef matchAttrRequired
        = new XSLTAttributeDef(null, "match", XSLTAttributeDef.T_PATTERN, true);
      XSLTAttributeDef matchAttrOpt 
        = new XSLTAttributeDef(null, "match", XSLTAttributeDef.T_PATTERN, 
false);
      XSLTAttributeDef priorityAttr
        = new XSLTAttributeDef(null, "priority", XSLTAttributeDef.T_PRIORITY, 
false);
      XSLTAttributeDef modeAttr
        = new XSLTAttributeDef(null, "mode", XSLTAttributeDef.T_QNAME, false);
      XSLTAttributeDef spaceAttr
        = new XSLTAttributeDef(Constants.S_XMLNAMESPACEURI, "space", false,
                              "default", Constants.ATTRVAL_STRIP,
                              "preserve", Constants.ATTRVAL_PRESERVE);
      
      XSLTAttributeDef stylesheetPrefixAttr
        = new XSLTAttributeDef(null, "stylesheet-prefix", 
XSLTAttributeDef.T_CDATA, true);
      XSLTAttributeDef resultPrefixAttr
        = new XSLTAttributeDef(null, "result-prefix", XSLTAttributeDef.T_CDATA, 
true);
  
      XSLTAttributeDef disableOutputEscapingAttr
        = new XSLTAttributeDef(null, "disable-output-escaping", 
XSLTAttributeDef.T_YESNO, true);
      
      XSLTAttributeDef levelAttr
        = new XSLTAttributeDef(null, "level", false, 
                              "single", Constants.NUMBERLEVEL_SINGLE, 
                              "multiple", Constants.NUMBERLEVEL_MULTI,  
                              "any", Constants.NUMBERLEVEL_ANY);
      levelAttr.setDefault("single");
      
      XSLTAttributeDef countAttr
        = new XSLTAttributeDef(null, "count", XSLTAttributeDef.T_PATTERN, 
false);
      XSLTAttributeDef fromAttr
        = new XSLTAttributeDef(null, "from", XSLTAttributeDef.T_PATTERN, false);
      XSLTAttributeDef valueAttr
        = new XSLTAttributeDef(null, "value", XSLTAttributeDef.T_EXPR, false);
      XSLTAttributeDef formatAttr
        = new XSLTAttributeDef(null, "format", XSLTAttributeDef.T_AVT, false);
      formatAttr.setDefault("1");
      XSLTAttributeDef langAttr
        = new XSLTAttributeDef(null, "lang", XSLTAttributeDef.T_AVT, false);
      XSLTAttributeDef letterValueAttr
        = new XSLTAttributeDef(null, "letter-value", XSLTAttributeDef.T_AVT, 
false);
      XSLTAttributeDef groupingSeparatorAVT
        = new XSLTAttributeDef(null, "grouping-separator", 
XSLTAttributeDef.T_AVT, false);
      XSLTAttributeDef groupingSizeAttr
        = new XSLTAttributeDef(null, "grouping-size", XSLTAttributeDef.T_AVT, 
false);
  
      XSLTAttributeDef dataTypeAttr
        = new XSLTAttributeDef(null, "data-type", XSLTAttributeDef.T_AVT, 
"text");
      XSLTAttributeDef orderAttr
        = new XSLTAttributeDef(null, "order", XSLTAttributeDef.T_AVT, 
"ascending");
      XSLTAttributeDef caseOrderAttr
        = new XSLTAttributeDef(null, "case-order", XSLTAttributeDef.T_AVT, 
false);
      
      XSLTAttributeDef terminateAttr
        = new XSLTAttributeDef(null, "terminate", XSLTAttributeDef.T_YESNO, 
false);
      terminateAttr.setDefault("no");
  
      XSLTAttributeDef xslExcludeResultPrefixesAttr
        = new XSLTAttributeDef(Constants.S_XSLNAMESPACEURL, 
                               "exclude-result-prefixes", 
                               XSLTAttributeDef.T_STRINGLIST, false);
  
      XSLTAttributeDef xslExtensionElementPrefixesAttr
        = new XSLTAttributeDef(Constants.S_XSLNAMESPACEURL, 
                               "extension-element-prefixes", 
                               XSLTAttributeDef.T_STRINGLIST, false);
  
      XSLTAttributeDef xslUseAttributeSetsAttr
        = new XSLTAttributeDef(Constants.S_XSLNAMESPACEURL, 
                               "use-attribute-sets", 
                               XSLTAttributeDef.T_QNAMES, false);
  
      XSLTAttributeDef xslVersionAttr
        = new XSLTAttributeDef(Constants.S_XSLNAMESPACEURL, 
                               "version", 
                               XSLTAttributeDef.T_NMTOKEN, false);
  
      XSLTElementDef charData
        = new XSLTElementDef(null, "text()", 
                             null /*alias */, 
                             null /* elements */,
                             null, /* attributes */ 
                             new ProcessorCharacters(), 
                             ElemTextLiteral.class /* class object */ );
      charData.setType(XSLTElementDef.T_PCDATA);
      
      XSLTAttributeDef resultAttr
        = new XSLTAttributeDef(null, "*", XSLTAttributeDef.T_AVT, false);
  
      XSLTElementDef[] templateElements = new XSLTElementDef[20];
      XSLTElementDef[] templateElementsAndParams = new XSLTElementDef[21];
      XSLTElementDef[] templateElementsAndSort = new XSLTElementDef[21];
      XSLTElementDef[] charTemplateElements = new XSLTElementDef[15];
  
      XSLTElementDef resultElement
        = new XSLTElementDef(null, "*", 
                             null /*alias */, 
                             templateElements /* elements */,
                             new XSLTAttributeDef[] {
                             xslExcludeResultPrefixesAttr, 
                             xslExtensionElementPrefixesAttr,
                             xslUseAttributeSetsAttr, 
                             xslVersionAttr, resultAttr}, 
                             new ProcessorLRE(), 
                             ElemLiteralResult.class /* class object */ );
                             
      XSLTElementDef xslValueOf 
        = new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "value-of", 
                            null /*alias */, 
                            null /* elements */,
                            new XSLTAttributeDef[] {selectAttrRequired, 
disableOutputEscapingAttr}, 
                            new ProcessorTemplateElem(), 
                            ElemValueOf.class /* class object */ );
  
      XSLTElementDef xslCopyOf 
        = new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "copy-of", 
                            null /*alias */, 
                            null /* elements */,
                            new XSLTAttributeDef[] {selectAttrRequired}, 
                            new ProcessorTemplateElem(), 
                            ElemCopyOf.class /* class object */ );
  
      XSLTElementDef xslNumber 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "number", 
                             null /*alias */, 
                             null /* elements */,
                             new XSLTAttributeDef[] {
                             levelAttr, countAttr, fromAttr, valueAttr, 
formatAttr,
                             langAttr, letterValueAttr, groupingSeparatorAVT, 
                             groupingSizeAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemNumber.class /* class object */ );
  
      // <!-- xsl:sort cannot occur after any other elements or
      // any non-whitespace character -->
      XSLTElementDef xslSort 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "sort", 
                             null /*alias */, 
                             null /* elements */,
                             new XSLTAttributeDef[] {
                             selectAttrDefDot, langAttr, dataTypeAttr, 
orderAttr, caseOrderAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemSort.class /* class object */ );
  
      XSLTElementDef xslWithParam 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "with-param", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;>
                             new XSLTAttributeDef[] {nameAttrRequired, 
selectAttrOpt}, 
                             new ProcessorTemplateElem(), 
                             ElemWithParam.class /* class object */ );
  
      XSLTElementDef xslApplyTemplates 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "apply-templates", 
                             null /*alias */, 
                             new XSLTElementDef[] {xslSort, xslWithParam} /* 
elements */,
                             new XSLTAttributeDef[] {selectAttrDefNode, 
modeAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemApplyTemplates.class /* class object */ );
  
      XSLTElementDef xslApplyImports 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "apply-imports", 
                             null /*alias */, 
                             null /* elements */,
                             new XSLTAttributeDef[] {}, 
                             new ProcessorTemplateElem(), 
                             ElemApplyImport.class /* class object */ );
  
      XSLTElementDef xslForEach 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "for-each", 
                             null /*alias */, 
                             templateElementsAndSort, // (#PCDATA 
%instructions; %result-elements; | xsl:sort)*
                             new XSLTAttributeDef[] {selectAttrRequired, 
spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemForEach.class /* class object */ );
  
      XSLTElementDef xslIf 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "if", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;
                             new XSLTAttributeDef[] {testAttrRequired, 
spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemIf.class /* class object */ );
  
      XSLTElementDef xslWhen 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "when", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;>
                             new XSLTAttributeDef[] {testAttrRequired, 
spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemWhen.class /* class object */ );
  
      XSLTElementDef xslOtherwise 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "otherwise", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;>
                             new XSLTAttributeDef[] {spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemOtherwise.class /* class object */ );
  
      XSLTElementDef xslChoose 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "choose", 
                             null /*alias */, 
                             new XSLTElementDef[] {xslWhen, xslOtherwise} /* 
elements */,
                             new XSLTAttributeDef[] {spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemChoose.class /* class object */ );
  
      XSLTElementDef xslAttribute 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "attribute", 
                             null /*alias */, 
                             charTemplateElements /* elements */, // 
%char-template;>
                             new XSLTAttributeDef[] {nameAVTRequired, 
namespaceAVTOpt, spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemAttribute.class /* class object */ );
  
      XSLTElementDef xslCallTemplate 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "call-template", 
                             null /*alias */, 
                             new XSLTElementDef[] {xslWithParam} /* elements */,
                             new XSLTAttributeDef[] {nameAttrRequired}, 
                             new ProcessorTemplateElem(), 
                             ElemCallTemplate.class /* class object */ );
  
      XSLTElementDef xslVariable 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "variable", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;>
                             new XSLTAttributeDef[] {nameAttrRequired, 
selectAttrOpt}, 
                             new ProcessorTemplateElem(), 
                             ElemVariable.class /* class object */ );
  
      XSLTElementDef xslParam 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "param", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;>
                             new XSLTAttributeDef[] {nameAttrRequired, 
selectAttrOpt}, 
                             new ProcessorTemplateElem(), 
                             ElemParam.class /* class object */ );
  
      XSLTElementDef xslText 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "text", 
                             null /*alias */, 
                             new XSLTElementDef[] {charData} /* elements */,
                             new XSLTAttributeDef[] 
{disableOutputEscapingAttr}, 
                             new ProcessorText(), 
                             ElemText.class /* class object */ );
  
      XSLTElementDef xslProcessingInstruction 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, 
"processing-instruction", 
                             null /*alias */, 
                             charTemplateElements /* elements */, // 
%char-template;>
                             new XSLTAttributeDef[] {nameAVTRequired, 
spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemPI.class /* class object */ );
  
      XSLTElementDef xslElement 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "element", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;
                             new XSLTAttributeDef[] {nameAVTRequired, 
namespaceAVTOpt, 
                             useAttributeSetsAttr, spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemElement.class /* class object */ );
  
      XSLTElementDef xslComment 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "comment", 
                             null /*alias */, 
                             charTemplateElements /* elements */, // 
%char-template;>
                             new XSLTAttributeDef[] {spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemComment.class /* class object */ );
  
      XSLTElementDef xslCopy 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "copy", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;>
                             new XSLTAttributeDef[] {spaceAttr, 
useAttributeSetsAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemCopy.class /* class object */ );
  
      XSLTElementDef xslMessage 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "message", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;>
                             new XSLTAttributeDef[] {}, 
                             new ProcessorTemplateElem(), 
                             ElemMessage.class /* class object */ );
  
      XSLTElementDef xslFallback 
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "fallback", 
                             null /*alias */, 
                             templateElements /* elements */, // %template;>
                             new XSLTAttributeDef[] {spaceAttr}, 
                             new ProcessorTemplateElem(), 
                             ElemFallback.class /* class object */ );
      
      int i = 0;
      templateElements[i++] = charData; // #PCDATA
      
      // char-instructions
      templateElements[i++] = xslApplyTemplates;
      templateElements[i++] = xslCallTemplate;
      templateElements[i++] = xslApplyImports;
      templateElements[i++] = xslForEach;
      templateElements[i++] = xslValueOf;
      templateElements[i++] = xslCopyOf;
      templateElements[i++] = xslNumber;
      templateElements[i++] = xslChoose;
      templateElements[i++] = xslIf;
      templateElements[i++] = xslText;
      templateElements[i++] = xslCopy;
      templateElements[i++] = xslVariable;
      templateElements[i++] = xslMessage;
      templateElements[i++] = xslFallback;
      
      // instructions
      templateElements[i++] = xslProcessingInstruction;
      templateElements[i++] = xslComment;
      templateElements[i++] = xslElement;
      templateElements[i++] = xslAttribute;
      templateElements[i++] = resultElement;
      
      int k;
      for(k = 0; k < i; k++)
      {
        templateElementsAndParams[k] = templateElements[k];
      }
      templateElementsAndParams[k] = xslParam;
      
      for(k = 0; k < i; k++)
      {
        templateElementsAndSort[k] = templateElements[k];
      }
      templateElementsAndSort[k] = xslSort;
  
      i = 0;
      charTemplateElements[i++] = charData; // #PCDATA
      // char-instructions
      charTemplateElements[i++] = xslApplyTemplates;
      charTemplateElements[i++] = xslCallTemplate;
      charTemplateElements[i++] = xslApplyImports;
      charTemplateElements[i++] = xslForEach;
      charTemplateElements[i++] = xslValueOf;
      charTemplateElements[i++] = xslCopyOf;
      charTemplateElements[i++] = xslNumber;
      charTemplateElements[i++] = xslChoose;
      charTemplateElements[i++] = xslIf;
      charTemplateElements[i++] = xslText;
      charTemplateElements[i++] = xslCopy;
      charTemplateElements[i++] = xslVariable;
      charTemplateElements[i++] = xslMessage;
      charTemplateElements[i++] = xslFallback;
      
      XSLTElementDef  importDef
        =  new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "import", 
                              null /*alias */, 
                              null /* elements */,
                              new XSLTAttributeDef[] {hrefAttr}, // EMPTY
                              new ProcessorImport(), 
                              null /* class object */ );
      
      XSLTElementDef includeDef 
        = new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "include", 
                             null /*alias */, 
                             null /* elements */, // EMPTY
                             new XSLTAttributeDef[] {hrefAttr}, 
                             new ProcessorInclude(), 
                             null /* class object */ );
                 
      XSLTElementDef[] topLevelElements 
        = new XSLTElementDef[]
           {includeDef, importDef,
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "strip-space", 
           null /*alias */, 
           null /* elements */, // EMPTY
           new XSLTAttributeDef[] {elementsAttr}, 
           new ProcessorStripSpace(), 
           null /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "preserve-space", 
           null /*alias */, 
           null /* elements */, // EMPTY
           new XSLTAttributeDef[] {elementsAttr}, 
           new ProcessorPreserveSpace(), 
           null /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "output", 
           null /*alias */, 
           null /* elements */, // EMPTY
           new XSLTAttributeDef[] {methodAttr, versionAttr, 
           encodingAttr, omitXmlDeclarationAttr,
           standaloneAttr, doctypePublicAttr, doctypeSystemAttr, 
cdataSectionElementsAttr,
           indentAttr, mediaTypeAttr}, 
           new ProcessorOutputElem(), 
           null /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "key", 
           null /*alias */, 
           null /* elements */, // EMPTY
           new XSLTAttributeDef[] {nameAttrRequired, matchAttrRequired, 
useAttr}, 
           new ProcessorKey(), 
           null /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "decimal-format", 
           null /*alias */, 
           null /* elements */, // EMPTY
           new XSLTAttributeDef[] {
           nameAttrOpt, decimalSeparatorAttr, groupingSeparatorAttr,
           infinityAttr, minusSignAttr, NaNAttr,
           percentAttr, perMilleAttr, zeroDigitAttr,
           digitAttr, patternSeparatorAttr}, 
           new ProcessorDecimalFormat(), 
           null /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "attribute-set", 
           null /*alias */, 
           new XSLTElementDef[] {xslAttribute} /* elements */,
           new XSLTAttributeDef[] {nameAttrRequired, useAttributeSetsAttr}, 
           new ProcessorAttributeSet(), 
           null /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "variable", 
           null /*alias */, 
           templateElements /* elements */,
           new XSLTAttributeDef[] {nameAttrRequired, selectAttrOpt}, 
           new ProcessorGlobalVariableDecl(), 
           ElemVariable.class /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "param", 
           null /*alias */, 
           templateElements /* elements */,
           new XSLTAttributeDef[] {nameAttrRequired, selectAttrOpt}, 
           new ProcessorGlobalParamDecl(), 
           ElemParam.class /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "template", 
           null /*alias */, 
           templateElementsAndParams /* elements */,
           new XSLTAttributeDef[] {matchAttrOpt, nameAttrOpt, priorityAttr, 
modeAttr, spaceAttr}, 
           new ProcessorTemplate(), 
           ElemTemplate.class /* class object */ ),
  
           new XSLTElementDef(Constants.S_XSLNAMESPACEURL, "namespace-alias", 
           null /*alias */, 
           null /* elements */, // EMPTY
           new XSLTAttributeDef[] {stylesheetPrefixAttr, resultPrefixAttr}, 
           new ProcessorNamespaceAlias(), 
           null /* class object */ )
           };
  
       XSLTAttributeDef extensionElementPrefixesAttr
        = new XSLTAttributeDef(null, "extension-element-prefixes", 
                               XSLTAttributeDef.T_CDATA, false);
       
       XSLTAttributeDef idAttr
        = new XSLTAttributeDef(null, "id", 
                               XSLTAttributeDef.T_CDATA, false);
  
       XSLTAttributeDef versionAttrRequired
        = new XSLTAttributeDef(null, "version", 
                               XSLTAttributeDef.T_NMTOKEN, true);
      
      XSLTElementDef stylesheetElemDef 
        = new XSLTElementDef(Constants.S_XSLNAMESPACEURL, 
                             "stylesheet", 
                             "transform", 
                             topLevelElements,
                             new XSLTAttributeDef[] {
                             extensionElementPrefixesAttr, idAttr,
                             idAttr, versionAttrRequired, spaceAttr
                             }, 
                             new ProcessorStylesheetElement(), /* 
ContentHandler */
                             null /* class object */
                             );
  
      importDef.setElements(
        new XSLTElementDef[] {stylesheetElemDef, resultElement});
      
      includeDef.setElements(
        new XSLTElementDef[] {stylesheetElemDef, resultElement});
  
      build(null, 
            null, 
            null, 
            new XSLTElementDef[] {stylesheetElemDef, resultElement},
            null, 
            new ProcessorStylesheetDoc(), /* ContentHandler */
            null /* class object */
            );
  
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/res/XSLMessages.java
  
  Index: XSLMessages.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  
  import java.util.Locale;
  import java.util.ResourceBundle;
  import java.util.ListResourceBundle;
  import java.util.MissingResourceException;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  
  
  /**
   * <meta name="usage" content="internal"/>
   * Sets things up for issuing error messages.  This class is misnamed, and 
   * should be called XalanMessages, or some such.
   */
  public class XSLMessages 
  {
    
    private Locale fLocale = Locale.getDefault();
    private static XSLResourceBundle XSLTBundle = null ;
    private static XSLResourceBundle XPATHBundle = null ;
    private static final String XSLT_ERROR_RESOURCES = 
"org.apache.xalan.res.XSLTErrorResources";
    private static final String XPATH_ERROR_RESOURCES = 
"org.apache.xalan.xpath.res.XPATHErrorResources";
    private static String BAD_CODE = "BAD_CODE";
    private static String FORMAT_FAILED = "FORMAT_FAILED";
    
    /**
     *
     */
    public void setLocale(Locale locale) 
    {
      fLocale = locale;
    }
    
    /**
     *
     */
    public Locale getLocale() 
    {
      return fLocale;
    }
    
    /**
     * Creates a message from the specified key and replacement
     * arguments, localized to the given locale.
     *
     * @param errorCode The key for the message text.
     * @param args      The arguments to be used as replacement text
     *                  in the message created.
     */
    public static final String createXPATHWarning(int errorCode, Object args[]) 
//throws Exception 
    {
      if (XPATHBundle == null)        
        XPATHBundle = 
(XSLResourceBundle)loadResourceBundle(XPATH_ERROR_RESOURCES );      
      XSLResourceBundle fResourceBundle = XPATHBundle;
      
      if (fResourceBundle != null)
      {
        String msgKey = fResourceBundle.getWarningKey(errorCode);
        return createXPATHMsg(fResourceBundle, msgKey, args);
      }
      else
        return "Could not load any resource bundles.";
    }
    
    /**
     * Creates a message from the specified key and replacement
     * arguments, localized to the given locale.
     *
     * @param errorCode The key for the message text.
     * @param args      The arguments to be used as replacement text
     *                  in the message created.
     */
    public static final String createXPATHMessage(int errorCode, Object args[]) 
//throws Exception 
    {
      if (XPATHBundle == null)
        XPATHBundle = 
(XSLResourceBundle)loadResourceBundle(XPATH_ERROR_RESOURCES );
      XSLResourceBundle fResourceBundle = XPATHBundle;
      
      if (fResourceBundle != null)
      {
        String msgKey = fResourceBundle.getMessageKey(errorCode);
        return createXPATHMsg(fResourceBundle, msgKey, args);
      }
      else
        return "Could not load any resource bundles."; 
    }
    
    /**
     * Creates a message from the specified key and replacement
     * arguments, localized to the given locale.
     *
     * @param errorCode The key for the message text.
     * @param args      The arguments to be used as replacement text
     *                  in the message created.
     */
    public static final String createXPATHMsg(XSLResourceBundle 
fResourceBundle, String msgKey, Object args[]) //throws Exception 
    {
      String fmsg= null;
      boolean throwex = false;          
      
      String msg = null;
      if (msgKey != null)
        msg = fResourceBundle.getString(msgKey);
      if (msg == null)
      { 
        msg = fResourceBundle.getString(XPATHErrorResources.BAD_CODE);
        throwex = true;
      }
      if (args != null) 
      {
        try 
        {
          // Do this to keep format from crying.
          // This is better than making a bunch of conditional
          // code all over the place.
          int n = args.length;
          for(int i = 0; i < n; i++)
          {
            if(null == args[i])
              args[i]="";
          }
          fmsg = java.text.MessageFormat.format(msg, args);
        }
        catch (Exception e) 
        {
          fmsg = fResourceBundle.getString(XPATHErrorResources.FORMAT_FAILED);
          fmsg += " " + msg;
        }
      }
      else
        fmsg = msg;
  
      if (throwex) 
      {
        throw new RuntimeException(fmsg);
      }
      return fmsg;      
    } 
    
    /**
     * Creates a message from the specified key and replacement
     * arguments, localized to the given locale.
     *
     * @param errorCode The key for the message text.
     * @param args      The arguments to be used as replacement text
     *                  in the message created.
     */
    public static final String createWarning(int errorCode, Object args[]) 
//throws Exception 
    {
      if (XSLTBundle == null)
        XSLTBundle = (XSLResourceBundle)loadResourceBundle(XSLT_ERROR_RESOURCES 
);
      
      XSLResourceBundle fResourceBundle = XSLTBundle;
      
      if (fResourceBundle != null)
      { 
        String msgKey = fResourceBundle.getWarningKey(errorCode);
        return createMsg(fResourceBundle, msgKey, args);
      }
      else
        return "Could not load any resource bundles.";  
    }
    
    /**
     * Creates a message from the specified key and replacement
     * arguments, localized to the given locale.
     *
     * @param errorCode The key for the message text.
     * @param args      The arguments to be used as replacement text
     *                  in the message created.
     */
    public static final String createMessage(int errorCode, Object args[]) 
//throws Exception 
    {
      if (XSLTBundle == null)
        XSLTBundle = (XSLResourceBundle)loadResourceBundle(XSLT_ERROR_RESOURCES 
);
      
      XSLResourceBundle fResourceBundle = XSLTBundle;
      
      if (fResourceBundle != null)
      {  
        String msgKey = fResourceBundle.getMessageKey(errorCode);
        return createMsg(fResourceBundle, msgKey, args);
      }
      else
        return "Could not load any resource bundles.";
    }  
    
    /**
     * Creates a message from the specified key and replacement
     * arguments, localized to the given locale.
     *
     * @param errorCode The key for the message text.
     * @param args      The arguments to be used as replacement text
     *                  in the message created.
     */
    public static final String createMsg(XSLResourceBundle fResourceBundle, 
String msgKey, Object args[]) //throws Exception 
    {
      String fmsg= null;
      boolean throwex = false;
      
      String msg = null;
      if (msgKey != null)
        msg = fResourceBundle.getString(msgKey);
      if (msg == null)
      { 
        msg = fResourceBundle.getString(BAD_CODE);
        throwex = true;
      }
      if (args != null) 
      {
        try 
        {
          // Do this to keep format from crying.
          // This is better than making a bunch of conditional
          // code all over the place.
          int n = args.length;
          for(int i = 0; i < n; i++)
          {
            if(null == args[i])
              args[i]="";
          }
          fmsg = java.text.MessageFormat.format(msg, args);
        } 
        catch (Exception e) 
        {
          fmsg = fResourceBundle.getString(FORMAT_FAILED);
          fmsg += " " + msg;
        }
      }
      else
        fmsg = msg;
  
      if (throwex) 
      {
        throw new RuntimeException(fmsg);
      }
      return fmsg;      
    }   
  
    /**
     * Creates a message from the specified key and replacement
     * arguments, localized to the given locale.
     *
     * @param bundleName The name of the resource bundle to be
     *                  used.
     * @param errorCode The key for the message text.
     * @param args      The arguments to be used as replacement text
     *                  in the message created.
     */
    public String createMessage(String bundleName, int errorCode, Object 
args[]) throws Exception 
    {
      boolean throwex = false;
      int majorCode; 
      int minorCode;
      String fmsg = null;
      XSLResourceBundle aResourceBundle = null;
      
      aResourceBundle = (XSLResourceBundle)loadResourceBundle(bundleName );     
      
      
      String msgKey = aResourceBundle.getMessageKey(errorCode);
      String msg = null;
      if (msgKey != null)
        msg = aResourceBundle.getString(msgKey);
      
      if (msg == null)
      { 
        msg = aResourceBundle.getString(BAD_CODE);
        throwex = true;
      }
      
      if (args != null) 
      {
        try 
        {
          // Do this to keep format from crying.
          // This is better than making a bunch of conditional
          // code all over the place.
          int n = args.length;
          for(int i = 0; i < n; i++)
          {
            if(null == args[i])
              args[i]="";
          }
          fmsg = java.text.MessageFormat.format(msg, args);
        } 
        catch (Exception e) 
        {
          fmsg = aResourceBundle.getString(FORMAT_FAILED);
          fmsg += " " + msg;
        }
      }
      else
        fmsg = msg;
  
      if (throwex) 
      {
        throw new RuntimeException(fmsg);
      }
      return fmsg;
    }
    
    /**
     * Return a named ResourceBundle for a particular locale.  This method 
mimics the behavior
     * of ResourceBundle.getBundle(). 
     *
     * @param res the name of the resource to load. 
     * @param locale the locale to prefer when searching for the bundle
     * @return the ResourceBundle
     * @throws MissingResourceException  
     */
    public static final ListResourceBundle loadResourceBundle (String 
className) 
      throws MissingResourceException
    {
      Locale locale = Locale.getDefault();
      
      // String suffix = getResourceSuffix(locale);  
      try
      {
        //System.out.println("resource " +className+suffix);
        // first try with the given locale
        return (ListResourceBundle)ResourceBundle.getBundle (className, locale);
      }
      catch (MissingResourceException e)
      {         
        try                                                  // try to fall 
back to en_US if we can't load
        {
          // Since we can't find the localized property file,
          // fall back to en_US.
          return (ListResourceBundle)ResourceBundle.getBundle 
(XSLT_ERROR_RESOURCES, new Locale ("en", "US"));
        }
        catch (MissingResourceException e2)
        {                 
          // Now we are really in trouble.
          // very bad, definitely very bad...not going to get very far
          throw new MissingResourceException ("Could not load any resource 
bundles."+ className, className,"");
        }
      }
      
    }   
    
    
    /**
     * Return the resource file suffic for the indicated locale
     * For most locales, this will be based the language code.  However
     * for Chinese, we do distinguish between Taiwan and PRC
     *
     * @param locale the locale
     * @return an String suffix which canbe appended to a resource name
     */        
    private static final String getResourceSuffix(Locale locale)
    {
      String suffix = "_" + locale.getLanguage();
      
      String country = locale.getCountry();        
      
      if (country.equals("TW"))
        suffix += "_" + country;
  
      return suffix;
    }   
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLResourceBundle.java
  
  Index: XSLResourceBundle.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  
  import java.util.ListResourceBundle;
  
  /**
   * <meta name="usage" content="internal"/>
   * This is an interface for error messages.  This class is misnamed, 
   * and should be called XalanResourceBundle, or some such.
   */
  abstract public class XSLResourceBundle extends ListResourceBundle
  {  
    /**
     * Get the error string associated with the error code
     */ 
    abstract public String getMessageKey(int errorCode);
    
    
    /**
     * Get the error string associated with the error code
     */ 
    abstract public String getWarningKey(int errorCode);
    
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTErrorResources.java
  
  Index: XSLTErrorResources.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  
  import java.util.MissingResourceException;
  import java.util.Locale;
  import java.util.ResourceBundle;
  
  import java.text.DecimalFormat;
  
  import org.apache.xalan.templates.Constants;
  import org.apache.xalan.res.XSLResourceBundle;
  
  /**
   * Set up error messages.
   * We build a two dimensional array of message keys and 
   * message strings. In order to add a new message here,
   * you need to first update the count of messages(MAX_CODE)or 
   * the count of warnings(MAX_WARNING). The array will be 
   * automatically filled in with the keys, but you need to 
   * fill in the actual message string. Follow the instructions
   * below.   
   */
  public class XSLTErrorResources extends XSLResourceBundle 
  {  
  
  public static final String ERROR_SUFFIX = "ER";  
  public static final String WARNING_SUFFIX = "WR";
  
  public static final int MAX_CODE = 104;                  // this is needed to 
keep track of the number of messages          
  public static final int MAX_WARNING = 25;             // this is needed to 
keep track of the number of warnings
  public static final int MAX_OTHERS = 41;
  public static final int MAX_MESSAGES = MAX_CODE + MAX_WARNING +1;
  
  static final Object[][] contents = new Object[MAX_MESSAGES + MAX_OTHERS 
+1][2];
  
  /* 
   * Now fill in the message keys.
   * This does not need to be updated. If MAX_CODE and MAX_WARNING
   * are correct, the keys will get filled in automatically with
   * the value ERxxxx (WRxxxx for warnings) where xxxx is a 
   * formatted number corresponding to the error code (i.e. ER0001).
   */ 
  static 
  {
    for(int i = 0; i < MAX_CODE+1; i++)
    {
      contents[i][0] = getMKey(i);
    }
    for(int i = 1; i < MAX_WARNING+1; i++)
    {
      contents[i+ MAX_CODE][0] = getWKey(i);
    }
  }
  
  /*
   * Now fill in the message text.
   * First create an int for the message code. Make sure you 
   * update MAX_CODE for error messages and MAX_WARNING for warnings
   * Then fill in the message text for that message code in the
   * array. Use the new error code as the index into the array.
   */ 
  
  // Error messages...
  
  public static final int ERROR0000 = 0;
  static {contents[ERROR0000][1] 
            = "{0}";
  }
  
  public static final int ER_NO_CURLYBRACE = 1;
  static {contents[ER_NO_CURLYBRACE][1] 
            = "Error: Can not have '{' within expression";
  }
  
  public static final int ER_ILLEGAL_ATTRIBUTE = 2;
  static {contents[ER_ILLEGAL_ATTRIBUTE][1] 
            = "{0} has an illegal attribute: {1}";
  }
  
  public static final int ER_NULL_SOURCENODE_APPLYIMPORTS = 3;
  static {contents[ER_NULL_SOURCENODE_APPLYIMPORTS][1] 
            = "sourceNode is null in xsl:apply-imports!";
  }
  
  public static final int ER_CANNOT_ADD = 4;
  static {contents[ER_CANNOT_ADD][1] 
            = "Can not add {0} to {1}";
  }
  
  public static final int ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES = 5;
  static {contents[ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES][1] 
            = "sourceNode is null in handleApplyTemplatesInstruction!";
  }
  
  public static final int ER_NO_NAME_ATTRIB = 6;
  static {contents[ER_NO_NAME_ATTRIB][1] 
            = "{0} must have a name attribute.";
  }
  
  public static final int ER_TEMPLATE_NOT_FOUND = 7;
  static {contents[ER_TEMPLATE_NOT_FOUND][1] 
            = "Could not find template named: {0}";
  }
  
  public static final int ER_CANT_RESOLVE_NAME_AVT = 8;
  static {contents[ER_CANT_RESOLVE_NAME_AVT][1] 
            = "Could not resolve name AVT in xsl:call-template.";
  }
  
  public static final int ER_REQUIRES_ATTRIB = 9;
  static {contents[ER_REQUIRES_ATTRIB][1] 
            = "{0} requires attribute: {1}";
  }
  
  public static final int ER_MUST_HAVE_TEST_ATTRIB = 10;
  static {contents[ER_MUST_HAVE_TEST_ATTRIB][1] 
            = "{0} must have a 'test' attribute.";
  }
  
  public static final int ER_BAD_VAL_ON_LEVEL_ATTRIB = 11;
  static {contents[ER_BAD_VAL_ON_LEVEL_ATTRIB][1] 
            = "Bad value on level attribute: {0}";
  }
  
  public static final int ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML = 12;
  static {contents[ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML][1] 
            = "processing-instruction name can not be 'xml'";
  }
  
  public static final int ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME = 13;
  static {contents[ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME][1] 
            = "processing-instruction name must be a valid NCName: {0}";
  }
  
  public static final int ER_NEED_MATCH_ATTRIB = 14;
  static {contents[ER_NEED_MATCH_ATTRIB][1] 
            = "{0} must have a match attribute if it has a mode.";
  }
  
  public static final int ER_NEED_NAME_OR_MATCH_ATTRIB = 15;
  static {contents[ER_NEED_NAME_OR_MATCH_ATTRIB][1] 
            = "{0} requires either a name or a match attribute.";
  }
  
  public static final int ER_CANT_RESOLVE_NSPREFIX = 16;
  static {contents[ER_CANT_RESOLVE_NSPREFIX][1] 
            = "Can not resolve namespace prefix: {0}";
  }
  
  public static final int ER_ILLEGAL_VALUE = 17;
  static {contents[ER_ILLEGAL_VALUE][1] 
            = "xml:space has an illegal value: {0}";
  }
  
  public static final int ER_NO_OWNERDOC = 18;
  static {contents[ER_NO_OWNERDOC][1] 
            = "Child node does not have an owner document!";
  }
  
  public static final int ER_ELEMTEMPLATEELEM_ERR = 19;
  static {contents[ER_ELEMTEMPLATEELEM_ERR][1] 
            = "ElemTemplateElement error: {0}";
  }
  
  public static final int ER_NULL_CHILD = 20;
  static {contents[ER_NULL_CHILD][1] 
            = "Trying to add a null child!";
  }
  
  public static final int ER_NEED_SELECT_ATTRIB = 21;
  static {contents[ER_NEED_SELECT_ATTRIB][1] 
            = "{0} requires a select attribute.";
  }
  
  public static final int ER_NEED_TEST_ATTRIB = 22;
  static {contents[ER_NEED_TEST_ATTRIB][1] 
            = "xsl:when must have a 'test' attribute.";
  }
  
  public static final int ER_NEED_NAME_ATTRIB = 23;
  static {contents[ER_NEED_NAME_ATTRIB][1] 
            = "xsl:with-param must have a 'name' attribute.";
  }
  
  public static final int ER_NO_CONTEXT_OWNERDOC = 24;
  static {contents[ER_NO_CONTEXT_OWNERDOC][1] 
            = "context does not have an owner document!";
  }
  
  public static final int ER_COULD_NOT_CREATE_XML_PROC_LIAISON = 25;
  static {contents[ER_COULD_NOT_CREATE_XML_PROC_LIAISON][1] 
            = "Could not create XML Processor Liaison: {0}";
  }
  
  public static final int ER_PROCESS_NOT_SUCCESSFUL = 26;
  static {contents[ER_PROCESS_NOT_SUCCESSFUL][1] 
            = "Xalan: Process was not successful.";
  }
  
  public static final int ER_NOT_SUCCESSFUL = 27;
  static {contents[ER_NOT_SUCCESSFUL][1] 
            = "Xalan: was not successful.";
  }
  
  public static final int ER_ENCODING_NOT_SUPPORTED = 28;
  static {contents[ER_ENCODING_NOT_SUPPORTED][1] 
            = "Encoding not supported: {0}";
  }
  
  public static final int ER_COULD_NOT_CREATE_TRACELISTENER = 29;
  static {contents[ER_COULD_NOT_CREATE_TRACELISTENER][1] 
            = "Could not create TraceListener: {0}";
  }
  
  public static final int ER_KEY_REQUIRES_NAME_ATTRIB = 30;
  static {contents[ER_KEY_REQUIRES_NAME_ATTRIB][1] 
            = "xsl:key requires a 'name' attribute!";
  }
  
  public static final int ER_KEY_REQUIRES_MATCH_ATTRIB = 31;
  static {contents[ER_KEY_REQUIRES_MATCH_ATTRIB][1] 
            = "xsl:key requires a 'match' attribute!";
  }
  
  public static final int ER_KEY_REQUIRES_USE_ATTRIB = 32;
  static {contents[ER_KEY_REQUIRES_USE_ATTRIB][1] 
            = "xsl:key requires a 'use' attribute!";
  }
  
  public static final int ER_REQUIRES_ELEMENTS_ATTRIB = 33;
  static {contents[ER_REQUIRES_ELEMENTS_ATTRIB][1] 
            = "(StylesheetHandler) {0} requires an 'elements' attribute!";
  }
  
  public static final int ER_MISSING_PREFIX_ATTRIB = 34;
  static {contents[ER_MISSING_PREFIX_ATTRIB][1] 
            = "(StylesheetHandler) {0} attribute 'prefix' is missing";
  }
  
  public static final int ER_BAD_STYLESHEET_URL = 35;
  static {contents[ER_BAD_STYLESHEET_URL][1] 
            = "Stylesheet URL is bad: {0}";
  }
  
  public static final int ER_FILE_NOT_FOUND = 36;
  static {contents[ER_FILE_NOT_FOUND][1] 
            = "Stylesheet file was not found: {0}";
  }
  
  public static final int ER_IOEXCEPTION = 37;
  static {contents[ER_IOEXCEPTION][1] 
            = "Had IO Exception with stylesheet file: {0}";
  }
  
  public static final int ER_NO_HREF_ATTRIB = 38;
  static {contents[ER_NO_HREF_ATTRIB][1] 
            = "(StylesheetHandler) Could not find href attribute for {0}";
  }
  
  public static final int ER_STYLESHEET_INCLUDES_ITSELF = 39;
  static {contents[ER_STYLESHEET_INCLUDES_ITSELF][1] 
            = "(StylesheetHandler) {0} is directly or indirectly including 
itself!";
  }
  
  public static final int ER_PROCESSINCLUDE_ERROR = 40;
  static {contents[ER_PROCESSINCLUDE_ERROR][1] 
            = "StylesheetHandler.processInclude error, {0}";
  }
  
  public static final int ER_MISSING_LANG_ATTRIB = 41;
  static {contents[ER_MISSING_LANG_ATTRIB][1] 
            = "(StylesheetHandler) {0} attribute 'lang' is missing";
  }
  
  public static final int ER_MISSING_CONTAINER_ELEMENT_COMPONENT = 42;
  static {contents[ER_MISSING_CONTAINER_ELEMENT_COMPONENT][1] 
            = "(StylesheetHandler) misplaced {0} element?? Missing container 
element 'component'";
  }
  
  public static final int ER_CAN_ONLY_OUTPUT_TO_ELEMENT = 43;
  static {contents[ER_CAN_ONLY_OUTPUT_TO_ELEMENT][1] 
            = "Can only output to an Element, DocumentFragment, Document, or 
PrintWriter.";
  }
  
  public static final int ER_PROCESS_ERROR = 44;
  static {contents[ER_PROCESS_ERROR][1] 
            = "StylesheetRoot.process error";
  }
  
  public static final int ER_UNIMPLNODE_ERROR = 45;
  static {contents[ER_UNIMPLNODE_ERROR][1] 
            = "UnImplNode error: {0}";
  }
  
  public static final int ER_NO_SELECT_EXPRESSION = 46;
  static {contents[ER_NO_SELECT_EXPRESSION][1] 
            = "Error! Did not find xpath select expression (-select).";
  }
  
  public static final int ER_CANNOT_SERIALIZE_XSLPROCESSOR = 47;
  static {contents[ER_CANNOT_SERIALIZE_XSLPROCESSOR][1] 
            = "Can not serialize an XSLProcessor!";
  }
  
  public static final int ER_NO_INPUT_STYLESHEET = 48;
  static {contents[ER_NO_INPUT_STYLESHEET][1] 
            = "Stylesheet input was not specified!";
  }
  
  public static final int ER_FAILED_PROCESS_STYLESHEET = 49;
  static {contents[ER_FAILED_PROCESS_STYLESHEET][1] 
            = "Failed to process stylesheet!";
  }
  
  public static final int ER_COULDNT_PARSE_DOC = 50;
  static {contents[ER_COULDNT_PARSE_DOC][1] 
            = "Could not parse {0} document!";
  }
  
  public static final int ER_COULDNT_FIND_FRAGMENT = 51;
  static {contents[ER_COULDNT_FIND_FRAGMENT][1] 
            = "Could not find fragment: {0}";
  }
  
  public static final int ER_NODE_NOT_ELEMENT = 52;
  static {contents[ER_NODE_NOT_ELEMENT][1] 
            = "Node pointed to by fragment identifier was not an element: {0}";
  }
  
  public static final int ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB = 53;
  static {contents[ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB][1] 
            = "for-each must have either a match or name attribute";
  }
  
  public static final int ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB = 54;
  static {contents[ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB][1] 
            = "templates must have either a match or name attribute";
  }
  
  public static final int ER_NO_CLONE_OF_DOCUMENT_FRAG = 55;
  static {contents[ER_NO_CLONE_OF_DOCUMENT_FRAG][1] 
            = "No clone of a document fragment!";
  }
  
  public static final int ER_CANT_CREATE_ITEM = 56;
  static {contents[ER_CANT_CREATE_ITEM][1] 
            = "Can not create item in result tree: {0}";
  }
  
  public static final int ER_XMLSPACE_ILLEGAL_VALUE = 57;
  static {contents[ER_XMLSPACE_ILLEGAL_VALUE][1] 
            = "xml:space in the source XML has an illegal value: {0}";
  }
  
  public static final int ER_NO_XSLKEY_DECLARATION = 58;
  static {contents[ER_NO_XSLKEY_DECLARATION][1] 
            = "There is no xsl:key declaration for {0}!";
  }
  
  public static final int ER_CANT_CREATE_URL = 59;
  static {contents[ER_CANT_CREATE_URL][1] 
            = "Error! Cannot create url for: {0}";
  }
  
  public static final int ER_XSLFUNCTIONS_UNSUPPORTED = 60;
  static {contents[ER_XSLFUNCTIONS_UNSUPPORTED][1] 
            = "xsl:functions is unsupported";
  }
  
  public static final int ER_PROCESSOR_ERROR = 61;
  static {contents[ER_PROCESSOR_ERROR][1] 
            = "XSLT Processor Error";
  }
  
  public static final int ER_NOT_ALLOWED_INSIDE_STYLESHEET = 62;
  static {contents[ER_NOT_ALLOWED_INSIDE_STYLESHEET][1] 
            = "(StylesheetHandler) {0} not allowed inside a stylesheet!";
  }
  
  public static final int ER_RESULTNS_NOT_SUPPORTED = 63;
  static {contents[ER_RESULTNS_NOT_SUPPORTED][1] 
            = "result-ns no longer supported!  Use xsl:output instead.";
  }
  
  public static final int ER_DEFAULTSPACE_NOT_SUPPORTED = 64;
  static {contents[ER_DEFAULTSPACE_NOT_SUPPORTED][1] 
            = "default-space no longer supported!  Use xsl:strip-space or 
xsl:preserve-space instead.";
  }
  
  public static final int ER_INDENTRESULT_NOT_SUPPORTED = 65;
  static {contents[ER_INDENTRESULT_NOT_SUPPORTED][1] 
            = "indent-result no longer supported!  Use xsl:output instead.";
  }
  
  public static final int ER_ILLEGAL_ATTRIB = 66;
  static {contents[ER_ILLEGAL_ATTRIB][1] 
            = "(StylesheetHandler) {0} has an illegal attribute: {1}";
  }
  
  public static final int ER_UNKNOWN_XSL_ELEM = 67;
  static {contents[ER_UNKNOWN_XSL_ELEM][1] 
            = "Unknown XSL element: {0}";
  }
  
  public static final int ER_BAD_XSLSORT_USE = 68;
  static {contents[ER_BAD_XSLSORT_USE][1] 
            = "(StylesheetHandler) xsl:sort can only be used with 
xsl:apply-templates or xsl:for-each.";
  }
  
  public static final int ER_MISPLACED_XSLWHEN = 69;
  static {contents[ER_MISPLACED_XSLWHEN][1] 
            = "(StylesheetHandler) misplaced xsl:when!";
  }
  
  public static final int ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE = 70;
  static {contents[ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE][1] 
            = "(StylesheetHandler) xsl:when not parented by xsl:choose!";
  }
  
  public static final int ER_MISPLACED_XSLOTHERWISE = 71;
  static {contents[ER_MISPLACED_XSLOTHERWISE][1] 
            = "(StylesheetHandler) misplaced xsl:otherwise!";
  }
  
  public static final int ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE = 72;
  static {contents[ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE][1] 
            = "(StylesheetHandler) xsl:otherwise not parented by xsl:choose!";
  }
  
  public static final int ER_NOT_ALLOWED_INSIDE_TEMPLATE = 73;
  static {contents[ER_NOT_ALLOWED_INSIDE_TEMPLATE][1] 
            = "(StylesheetHandler) {0} is not allowed inside a template!";
  }
  
  public static final int ER_UNKNOWN_EXT_NS_PREFIX = 74;
  static {contents[ER_UNKNOWN_EXT_NS_PREFIX][1] 
            = "(StylesheetHandler) {0} extension namespace prefix {1} unknown";
  }
  
  public static final int ER_IMPORTS_AS_FIRST_ELEM = 75;
  static {contents[ER_IMPORTS_AS_FIRST_ELEM][1] 
            = "(StylesheetHandler) Imports can only occur as the first elements 
in the stylesheet!";
  }
  
  public static final int ER_IMPORTING_ITSELF = 76;
  static {contents[ER_IMPORTING_ITSELF][1] 
            = "(StylesheetHandler) {0} is directly or indirectly importing 
itself!";
  }
  
  public static final int ER_XMLSPACE_ILLEGAL_VAL = 77;
  static {contents[ER_XMLSPACE_ILLEGAL_VAL][1] 
            = "(StylesheetHandler) "+"xml:space has an illegal value: {0}";
  }
  
  public static final int ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL = 78;
  static {contents[ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL][1] 
            = "processStylesheet not succesfull!";
  }
  
  public static final int ER_SAX_EXCEPTION = 79;
  static {contents[ER_SAX_EXCEPTION][1] 
            = "SAX Exception";
  }
  
  public static final int ER_FUNCTION_NOT_SUPPORTED = 80;
  static {contents[ER_FUNCTION_NOT_SUPPORTED][1] 
            = "Function not supported!";
  }
  
  public static final int ER_XSLT_ERROR = 81;
  static {contents[ER_XSLT_ERROR][1] 
            = "XSLT Error";
  }
  
  public static final int ER_CURRENCY_SIGN_ILLEGAL = 82;
  static {contents[ER_CURRENCY_SIGN_ILLEGAL][1] 
            = "currency sign is not allowed in format pattern string";
  }
  
  public static final int ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM = 83;
  static {contents[ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM][1] 
            = "Document function not supported in Stylesheet DOM!";
  }
  
  public static final int ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER = 84;
  static {contents[ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER][1] 
            = "Can't resolve prefix of non-Prefix resolver!";
  }
  
  public static final int ER_REDIRECT_COULDNT_GET_FILENAME = 85;
  static {contents[ER_REDIRECT_COULDNT_GET_FILENAME][1] 
            = "Redirect extension: Could not get filename - file or select 
attribute must return vald string.";
  }
  
  public static final int ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT = 86;
  static {contents[ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT][1] 
            = "Can not build FormatterListener in Redirect extension!";
  }
  
  public static final int ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX = 87;
  static {contents[ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX][1] 
            = "Prefix in exclude-result-prefixes is not valid: {0}";
  }
  
  public static final int ER_MISSING_NS_URI = 88;
  static {contents[ER_MISSING_NS_URI][1] 
            = "Missing namespace URI for specified prefix";
  }
  
  public static final int ER_MISSING_ARG_FOR_OPTION = 89;
  static {contents[ER_MISSING_ARG_FOR_OPTION][1] 
            = "Missing argument for option: {0}";
  }
  
  public static final int ER_INVALID_OPTION = 90;
  static {contents[ER_INVALID_OPTION][1] 
            = "Invalid option: {0}";
  }
  
  public static final int ER_MALFORMED_FORMAT_STRING = 91;
  static {contents[ER_MALFORMED_FORMAT_STRING][1] 
            = "Malformed format string: {0}";
  }
  
  public static final int ER_STYLESHEET_REQUIRES_VERSION_ATTRIB = 92;
  static {contents[ER_STYLESHEET_REQUIRES_VERSION_ATTRIB][1] 
            = "xsl:stylesheet requires a 'version' attribute!";
  }
  
  public static final int ER_ILLEGAL_ATTRIBUTE_VALUE = 93;
  static {contents[ER_ILLEGAL_ATTRIBUTE_VALUE][1] 
                        = "Attribute: {0} has an illegal value: {1}";
  }
  
  public static final int ER_CHOOSE_REQUIRES_WHEN = 94;
  static {contents[ER_CHOOSE_REQUIRES_WHEN][1] 
                        = "xsl:choose requires an xsl:when";
  }
  
  public static final int ER_NO_APPLY_IMPORT_IN_FOR_EACH = 95;
  static {contents[ER_NO_APPLY_IMPORT_IN_FOR_EACH][1] 
                        = "xsl:apply-imports not allowed in a xsl:for-each";
  }
  
  public static final int ER_CANT_USE_DTM_FOR_OUTPUT = 96;
  static {contents[ER_CANT_USE_DTM_FOR_OUTPUT][1] 
                        = "Cannot use a DTMLiaison for an output DOM node... 
pass a org.apache.xalan.xpath.DOM2Helper instead!";
  }
  
  public static final int ER_CANT_USE_DTM_FOR_INPUT = 97;
  static {contents[ER_CANT_USE_DTM_FOR_INPUT][1] 
                        = "Cannot use a DTMLiaison for a input DOM node... pass 
a org.apache.xalan.xpath.DOM2Helper instead!";
  }
  
  public static final int ER_CALL_TO_EXT_FAILED = 98;
  static {contents[ER_CALL_TO_EXT_FAILED][1] 
            = "Call to extension element failed: {0}";
  }
  
  public static final int ER_PREFIX_MUST_RESOLVE = 99;
  static {contents[ER_PREFIX_MUST_RESOLVE][1] 
            = "Prefix must resolve to a namespace: {0}";
  }
  
  public static final int ER_INVALID_UTF16_SURROGATE = 100;
  static {contents[ER_INVALID_UTF16_SURROGATE][1] 
            = "Invalid UTF-16 surrogate detected: {0} ?";
  }
  
  public static final int ER_XSLATTRSET_USED_ITSELF = 101;
  static {contents[ER_XSLATTRSET_USED_ITSELF][1] 
            = "xsl:attribute-set {0} used itself, which will cause an infinite 
loop.";
  }
  
  public static final int ER_CANNOT_MIX_XERCESDOM = 102;
  static {contents[ER_CANNOT_MIX_XERCESDOM][1] 
            = "Can not mix non Xerces-DOM input with Xerces-DOM output!";      
  }
  
  public static final int ER_TOO_MANY_LISTENERS = 103;
  static {contents[ER_TOO_MANY_LISTENERS][1] 
            = "addTraceListenersToStylesheet - TooManyListenersException";      
  }
  
  public static final int ER_IN_ELEMTEMPLATEELEM_READOBJECT = 104;
  static {contents[ER_IN_ELEMTEMPLATEELEM_READOBJECT][1] 
            = "In ElemTemplateElement.readObject: {0}";      
  }
  
  // Warnings...
  
  public static final int WG_FOUND_CURLYBRACE = 1;
  static {contents[WG_FOUND_CURLYBRACE + MAX_CODE][1] 
            = "Found '}' but no attribute template open!";
  }
  
  public static final int WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR = 2;
  static {contents[WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR + MAX_CODE][1] 
            = "Warning: count attribute does not match an ancestor in 
xsl:number! Target = {0}";
  }
  
  public static final int WG_EXPR_ATTRIB_CHANGED_TO_SELECT = 3;
  static {contents[WG_EXPR_ATTRIB_CHANGED_TO_SELECT + MAX_CODE][1] 
            = "Old syntax: The name of the 'expr' attribute has been changed to 
'select'.";
  }
  
  public static final int WG_NO_LOCALE_IN_FORMATNUMBER = 4;
  static {contents[WG_NO_LOCALE_IN_FORMATNUMBER + MAX_CODE][1] 
            = "Xalan doesn't yet handle the locale name in the format-number 
function.";
  }
  
  public static final int WG_LOCALE_NOT_FOUND = 5;
  static {contents[WG_LOCALE_NOT_FOUND + MAX_CODE][1] 
            = "Warning: Could not find locale for xml:lang={0}";
  }
  
  public static final int WG_CANNOT_MAKE_URL_FROM = 6;
  static {contents[WG_CANNOT_MAKE_URL_FROM + MAX_CODE][1] 
            = "Can not make URL from: {0}";
  }
  
  public static final int WG_CANNOT_LOAD_REQUESTED_DOC = 7;
  static {contents[WG_CANNOT_LOAD_REQUESTED_DOC + MAX_CODE][1] 
            = "Can not load requested doc: {0}";
  }
  
  public static final int WG_CANNOT_FIND_COLLATOR = 8;
  static {contents[WG_CANNOT_FIND_COLLATOR + MAX_CODE][1] 
            = "Could not find Collator for <sort xml:lang={0}";
  }
  
  public static final int WG_FUNCTIONS_SHOULD_USE_URL = 9;
  static {contents[WG_FUNCTIONS_SHOULD_USE_URL + MAX_CODE][1] 
            = "Old syntax: the functions instruction should use a url of {0}";
  }
  
  public static final int WG_ENCODING_NOT_SUPPORTED_USING_UTF8 = 10;
  static {contents[WG_ENCODING_NOT_SUPPORTED_USING_UTF8 + MAX_CODE][1] 
            = "encoding not supported: {0}, using UTF-8";
  }
  
  public static final int WG_ENCODING_NOT_SUPPORTED_USING_JAVA = 11;
  static {contents[WG_ENCODING_NOT_SUPPORTED_USING_JAVA + MAX_CODE][1] 
            = "encoding not supported: {0}, using Java {1}";
  }
  
  public static final int WG_SPECIFICITY_CONFLICTS = 12;
  static {contents[WG_SPECIFICITY_CONFLICTS + MAX_CODE][1] 
            = "Specificity conflicts found: {0} Last found in stylesheet will 
be used.";
  }
  
  public static final int WG_PARSING_AND_PREPARING = 13;
  static {contents[WG_PARSING_AND_PREPARING + MAX_CODE][1] 
            = "========= Parsing and preparing {0} ==========";
  }
  
  public static final int WG_ATTR_TEMPLATE = 14;
  static {contents[WG_ATTR_TEMPLATE + MAX_CODE][1] 
            = "Attr Template, {0}";
  }
  
  public static final int 
WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESPACE = 15;
  static {contents[WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESPACE + 
MAX_CODE][1] 
            = "Match conflict between xsl:strip-space and xsl:preserve-space";
  }
  
  public static final int WG_ATTRIB_NOT_HANDLED = 16;
  static {contents[WG_ATTRIB_NOT_HANDLED + MAX_CODE][1] 
            = "Xalan does not yet handle the {0} attribute!";
  }
  
  public static final int WG_NO_DECIMALFORMAT_DECLARATION = 17;
  static {contents[WG_NO_DECIMALFORMAT_DECLARATION + MAX_CODE][1] 
            = "No declaration found for decimal format: {0}";
  }
  
  public static final int WG_OLD_XSLT_NS = 18;
  static {contents[WG_OLD_XSLT_NS + MAX_CODE][1] 
            = "Old XSLT Namespace: {0}";
  }
  
  public static final int WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED = 19;
  static {contents[WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED + MAX_CODE][1] 
            = "Only one default xsl:decimal-format declaration is allowed. The 
last one will be used.";
  }
  
  public static final int WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE = 20;
  static {contents[WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE + MAX_CODE][1] 
            = "xsl:decimal-format names must be unique. The last one will be 
used.";
  }
  
  public static final int WG_ILLEGAL_ATTRIBUTE = 21;
  static {contents[WG_ILLEGAL_ATTRIBUTE + MAX_CODE][1] 
            = "{0} has an illegal attribute: {1}";
  }
  
  public static final int WG_COULD_NOT_RESOLVE_PREFIX = 22;
  static {contents[WG_COULD_NOT_RESOLVE_PREFIX + MAX_CODE][1] 
            = "Could not resolve namespace prefix: {0}. The attribute will be 
ignored.";
  }
  
  public static final int WG_STYLESHEET_REQUIRES_VERSION_ATTRIB = 23;
  static {contents[WG_STYLESHEET_REQUIRES_VERSION_ATTRIB + MAX_CODE][1] 
            = "xsl:stylesheet requires a 'version' attribute!";
  }
  
  public static final int WG_ILLEGAL_ATTRIBUTE_NAME = 24;
  static {contents[WG_ILLEGAL_ATTRIBUTE_NAME + MAX_CODE][1] 
            = "Illegal attribute name: {0}";
  }
  
  public static final int WG_ILLEGAL_ATTRIBUTE_VALUE = 25;
  static {contents[WG_ILLEGAL_ATTRIBUTE_VALUE + MAX_CODE][1] 
            = "Illegal value used for attribute {0}: {1}";
  }
  
  
  
  // Other miscellaneous text used inside the code...
  
  static  {
           
           contents[MAX_MESSAGES][0] = "ui_language";
           contents[MAX_MESSAGES][1] = "en";
           
           contents[MAX_MESSAGES + 1][0] = "help_language";
           contents[MAX_MESSAGES + 1][1] = "en";
           
           contents[MAX_MESSAGES + 2][0] = "language";
           contents[MAX_MESSAGES + 2][1] = "en";
           
           contents[MAX_MESSAGES + 3][0] = "BAD_CODE";
           contents[MAX_MESSAGES + 3][1] = "Parameter to createMessage was out 
of bounds";
    
           contents[MAX_MESSAGES + 4][0] = "FORMAT_FAILED";
           contents[MAX_MESSAGES + 4][1] = "Exception thrown during 
messageFormat call";
           
           contents[MAX_MESSAGES + 5][0] = "version";
           contents[MAX_MESSAGES + 5][1] = ">>>>>>> Xalan Version ";
           
           contents[MAX_MESSAGES + 6][0] = "version2";
           contents[MAX_MESSAGES + 6][1] = "<<<<<<<";
           
           contents[MAX_MESSAGES + 7][0] = "yes";
           contents[MAX_MESSAGES + 7][1] = "yes";
           
           contents[MAX_MESSAGES + 8][0] = "line";
           contents[MAX_MESSAGES + 8][1] = "Line #";
           
           contents[MAX_MESSAGES + 9][0] = "column";
           contents[MAX_MESSAGES + 9][1] = "Column #";
           
           contents[MAX_MESSAGES + 10][0] = "xsldone";
           contents[MAX_MESSAGES + 10][1] = "XSLProcessor: done";
           
           contents[MAX_MESSAGES + 11][0] = "xslProc_option";
           contents[MAX_MESSAGES + 11][1] = "=xslproc options:";
           
           contents[MAX_MESSAGES + 12][0] = "optionIN";
           contents[MAX_MESSAGES + 12][1] = "    -IN inputXMLURL";
           
           contents[MAX_MESSAGES + 13][0] = "optionXSL";
           contents[MAX_MESSAGES + 13][1] = "   [-XSL XSLTransformationURL]";
           
           contents[MAX_MESSAGES + 14][0] = "optionOUT";
           contents[MAX_MESSAGES + 14][1] = "   [-XSL XSLTransformationURL]";
           
           contents[MAX_MESSAGES + 15][0] = "optionLXCIN";
           contents[MAX_MESSAGES + 15][1] = "   [-LXCIN 
compiledStylesheetFileNameIn]";
           
           contents[MAX_MESSAGES + 16][0] = "optionLXCOUT";
           contents[MAX_MESSAGES + 16][1] = "   [-LXCOUT 
compiledStylesheetFileNameOutOut]";
           
           contents[MAX_MESSAGES + 17][0] = "optionPARSER";
           contents[MAX_MESSAGES + 17][1] = "   [-PARSER fully qualified class 
name of parser liaison]";
           
           contents[MAX_MESSAGES + 18][0] = "optionE";
           contents[MAX_MESSAGES + 18][1] = "   [-E (Do not expand entity 
refs)]";
           
           contents[MAX_MESSAGES + 19][0] = "optionV";
           contents[MAX_MESSAGES + 19][1] = "   [-E (Do not expand entity 
refs)]";
           
           contents[MAX_MESSAGES + 20][0] = "optionQC";
           contents[MAX_MESSAGES + 20][1] = "   [-QC (Quiet Pattern Conflicts 
Warnings)]";
           
           contents[MAX_MESSAGES + 21][0] = "optionQ";
           contents[MAX_MESSAGES + 21][1] = "   [-Q  (Quiet Mode)]";
           
           contents[MAX_MESSAGES + 22][0] = "optionLF";
           contents[MAX_MESSAGES + 22][1] = "   [-LF (Use linefeeds only on 
output {default is CR/LF})]";
           
           contents[MAX_MESSAGES + 23][0] = "optionCR";
           contents[MAX_MESSAGES + 23][1] = "   [-CR (Use carriage returns only 
on output {default is CR/LF})]";
           
           contents[MAX_MESSAGES + 24][0] = "optionESCAPE";
           contents[MAX_MESSAGES + 24][1] = "   [-ESCAPE (Which characters to 
escape {default is <>&\"\'\\r\\n}]";
  
           contents[MAX_MESSAGES + 25][0] = "optionINDENT";
           contents[MAX_MESSAGES + 25][1] = "   [-INDENT (Control how many 
spaces to indent {default is 0})]";
  
           contents[MAX_MESSAGES + 26][0] = "optionTT";
           contents[MAX_MESSAGES + 26][1] = "   [-TT (Trace the templates as 
they are being called.)]";
  
           contents[MAX_MESSAGES + 27][0] = "optionTG";
           contents[MAX_MESSAGES + 27][1] = "   [-TG (Trace each generation 
event.)]";
  
           contents[MAX_MESSAGES + 28][0] = "optionTS";
           contents[MAX_MESSAGES + 28][1] = "   [-TS (Trace each selection 
event.)]";
  
           contents[MAX_MESSAGES + 29][0] = "optionTTC";
           contents[MAX_MESSAGES + 29][1] = "   [-TTC (Trace the template 
children as they are being processed.)]";
  
           contents[MAX_MESSAGES + 30][0] = "optionTCLASS";
           contents[MAX_MESSAGES + 30][1] = "   [-TCLASS (TraceListener class 
for trace extensions.)]";
  
           contents[MAX_MESSAGES + 31][0] = "optionVALIDATE"; 
           contents[MAX_MESSAGES + 31][1] = "   [-VALIDATE (Set whether 
validation occurs.  Validation is off by default.)]";
           
           contents[MAX_MESSAGES + 32][0] = "optionEDUMP";
           contents[MAX_MESSAGES + 32][1] = "   [-EDUMP {optional filename} (Do 
stackdump on error.)]";
           
           contents[MAX_MESSAGES + 33][0] = "optionXML";
           contents[MAX_MESSAGES + 33][1] = "   [-XML (Use XML formatter and 
add XML header.)]";
           
           contents[MAX_MESSAGES + 34][0] = "optionTEXT";
           contents[MAX_MESSAGES + 34][1] = "   [-TEXT (Use simple Text 
formatter.)]";
           
           contents[MAX_MESSAGES + 35][0] = "optionHTML";
           contents[MAX_MESSAGES + 35][1] = "   [-HTML (Use HTML formatter.)]";
           
           contents[MAX_MESSAGES + 36][0] = "optionPARAM";
           contents[MAX_MESSAGES + 36][1] = "   [-PARAM name expression (Set a 
stylesheet parameter)]";
  
           contents[MAX_MESSAGES + 37][0] = "noParsermsg1";
           contents[MAX_MESSAGES + 37][1] = "XSL Process was not successful.";
           
           contents[MAX_MESSAGES + 38][0] = "noParsermsg2";
           contents[MAX_MESSAGES + 38][1] = "** Could not find parser **";
           
           contents[MAX_MESSAGES + 39][0] = "noParsermsg3";
           contents[MAX_MESSAGES + 39][1] = "Please check your classpath.";
           
           contents[MAX_MESSAGES + 40][0] = "noParsermsg4";
           contents[MAX_MESSAGES + 40][1] = "If you don't have IBM's XML Parser 
for Java, you can download it from";
           
           contents[MAX_MESSAGES + 41][0] = "noParsermsg5";
           contents[MAX_MESSAGES + 41][1] = "IBM's AlphaWorks: 
http://www.alphaworks.ibm.com/formula/xml";;         
    }
  
    // ================= INFRASTRUCTURE ======================
  
    public static final String BAD_CODE = "BAD_CODE";
    public static final String FORMAT_FAILED = "FORMAT_FAILED";
  
    public static final String ERROR_STRING = "#error";
    public static final String ERROR_HEADER = "Error: ";
    public static final String WARNING_HEADER = "Warning: ";
    public static final String XSL_HEADER = "XSL ";
    public static final String XML_HEADER = "XML ";
    public static final String QUERY_HEADER = "PATTERN ";
  
    
    public Object[][] getContents()
    {
      return contents;
    }
  
  /**
     * Return a named ResourceBundle for a particular locale.  This method 
mimics the behavior
     * of ResourceBundle.getBundle(). 
     *
     * @param res the name of the resource to load. 
     * @param locale the locale to prefer when searching for the bundle
     * @return the ResourceBundle
     * @throws MissingResourceException  
     */
    public static final XSLTErrorResources loadResourceBundle (String 
className) 
          throws MissingResourceException
    {
        Locale locale = Locale.getDefault();
        String suffix = getResourceSuffix(locale);  
      try
      {         
                                                             // first try with 
the given locale
        return (XSLTErrorResources)ResourceBundle.getBundle (className + 
suffix, locale);
      }
      catch (MissingResourceException e)
      {
        try                                                  // try to fall 
back to en_US if we can't load
        {
                                                             // Since we can't 
find the localized property file,
                                                             // fall back to 
en_US.
          return (XSLTErrorResources)ResourceBundle.getBundle (className, new 
Locale ("en", "US"));
        }
        catch (MissingResourceException e2)
        {
                                                                // Now we are 
really in trouble.
                                                                // very bad, 
definitely very bad...not going to get very far
          throw new MissingResourceException ("Could not load any resource 
bundles.", className, "");
        }
      }
    }
    
    /**
     * Return the resource file suffic for the indicated locale
     * For most locales, this will be based the language code.  However
     * for Chinese, we do distinguish between Taiwan and PRC
     *
     * @param locale the locale
     * @return an String suffix which canbe appended to a resource name
     */        
    private static final String getResourceSuffix(Locale locale)
    {
          String suffix = "_" + locale.getLanguage();
          
          String country = locale.getCountry();        
          
          if (country.equals("TW"))
              suffix += "_" + country;
  
          return suffix;
    }
    
    
    /**
     * Get the error string associated with the error code
     */ 
    public String getMessageKey(int errorCode)
    {
          if (errorCode > MAX_CODE)
        return null;
      else
      {
        DecimalFormat df = new DecimalFormat("0000");
        return ERROR_SUFFIX + df.format(errorCode);     
      }  
    }
    
    /**
     * Get the error string associated with the error code
     */ 
    public String getWarningKey(int errorCode)
    {
          if (errorCode > MAX_WARNING)
        return null;
          else 
                {
        DecimalFormat df = new DecimalFormat("0000");
        return WARNING_SUFFIX + df.format(errorCode);   
      }
    }
    
    /**
     * Get the error string associated with the error code
     */ 
    public static String getMKey(int errorCode)
    {
          if (errorCode > MAX_CODE)
        return null;
      else
      {
        DecimalFormat df = new DecimalFormat("0000");
        return ERROR_SUFFIX + df.format(errorCode);     
      }  
    }
    
    /**
     * Get the error string associated with the error code
     */ 
    public static String getWKey(int errorCode)
    {
          if (errorCode > MAX_WARNING)
        return null;
          else 
                {
        DecimalFormat df = new DecimalFormat("0000");
        return WARNING_SUFFIX + df.format(errorCode);   
      }
    }
  }    
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTErrorResources_en.java
  
  Index: XSLTErrorResources_en.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTErrorResources_en extends XSLTErrorResources 
  {
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTInfo.properties
  
  Index: XSLTInfo.properties
  ===================================================================
  #
  #  XSLT Resource File
  #
  
  version=2.0.d1
  vendor=Apache Software Foundation
  vendor-url=http://xml.apache.org/xalan
  
  # The TRaX Stylesheet processor
  trax.processor.xslt=org.apache.xalan.processor.StylesheetProcessor
  
  # The XML Parser for SAX2
  org.xml.sax.driver=org.apache.xerces.parsers.SAXParser
  
  # Use this property for backwards compatibility with Xerces Liaison.
  # org.apache.xalan.source.liaison=org.apache.xalan.xpath.dtm.DTMLiaison
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResourceBundle.java
  
  Index: XSLTResourceBundle.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  import org.apache.xalan.templates.Constants;
  //
  //  LotusXSLResourceBundle 
  //
  public class XSLTResourceBundle extends ListResourceBundle 
  {
        
  /**
     * Return a named ResourceBundle for a particular locale.  This method 
mimics the behavior
     * of ResourceBundle.getBundle(). 
     *
     * @param res the name of the resource to load. 
     * @param locale the locale to prefer when searching for the bundle
     * @return the ResourceBundle
     * @throws MissingResourceException  
     */
    public static final XSLTResourceBundle loadResourceBundle (String 
className, Locale locale) 
          throws MissingResourceException
    {
        String suffix = getResourceSuffix(locale); 
        //System.out.println("resource " + className + suffix);
      try
      {         
                                                             // first try with 
the given locale
        return (XSLTResourceBundle)ResourceBundle.getBundle (className + 
suffix, locale);
      }
      catch (MissingResourceException e)
      {
        try                                                  // try to fall 
back to en_US if we can't load
        {
                                                             // Since we can't 
find the localized property file,
                                                             // fall back to 
en_US.
          return (XSLTResourceBundle)ResourceBundle.getBundle 
(Constants.XSLT_RESOURCE, new Locale ("en", "US"));
        }
        catch (MissingResourceException e2)
        {
                                                                // Now we are 
really in trouble.
                                                                // very bad, 
definitely very bad...not going to get very far
          throw new MissingResourceException ("Could not load any resource 
bundles.", className, "");
        }
      }
    }
    
    /**
     * Return the resource file suffic for the indicated locale
     * For most locales, this will be based the language code.  However
     * for Chinese, we do distinguish between Taiwan and PRC
     *
     * @param locale the locale
     * @return an String suffix which canbe appended to a resource name
     */        
    private static final String getResourceSuffix(Locale locale)
    {
          String lang = locale.getLanguage();        
          String country = locale.getCountry();
                String variant = locale.getVariant();
          
                String suffix = "_" + locale.getLanguage();
          if (lang.equals("zh"))
              suffix += "_" + country;
                if (country.equals("JP"))
              suffix += "_" + country + "_" + variant;
  
          return suffix;
    }           
        
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","en"},
  {"help_language", "en"},
  {"language", "en"},
     
  {"alphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "additive"},
  
  };
  
  
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_cy.java
  
  Index: XSLTResources_cy.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_cy extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","cy"},
  {"help_language", "cy"},
  {"language", "cy"},
  
   
  {"alphabet", new 
char[]{0x0430,0x0432,0x0433,0x0434,0x0435,0x0437,0x0438,0x0439,0x04A9,0x0457,0x043A,0x043B,0x043C,0x043D,0x046F,0x043E,0x043F,0x0447,0x0440,0x0441,0x0442,0x0443,0x0444,0x0445,0x0470,0x0460,0x0446}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "LeftToRight"},
  
  //language numbering 
  //{"numbering", "additive"},
  {"numbering", "multiplicative-additive"},
  {"multiplierOrder", "precedes"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer(10000000000)},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{100, 10, 1}},
  //These only used for mutiplicative-additive numbering
  {"multiplier", new int[] {1000}},
  {"multiplierChar", new char[] {0x03D9}},
  // chinese only??
  {"zero", new char[0]},
  //{"digits", new char[]{'a','b','c','d','e','f','g','h','i'}},
  {"digits", new 
char[]{0x0430,0x0432,0x0433,0x0434,0x0435,0x0437,0x0438,0x0439,0x04A9}},
  {"tens", new 
char[]{0x0457,0x043A,0x043B,0x043C,0x043D,0x046F,0x043E,0x043F,0x0447}},  
  {"hundreds", new 
char[]{0x0440,0x0441,0x0442,0x0443,0x0444,0x0445,0x0470,0x0460,0x0446}},
  
  
  {"tables", new String[]{"hundreds", "tens", "digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_el.java
  
  Index: XSLTResources_el.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_el extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","el"},
  {"help_language", "el"},
  {"language", "el"},
  
   
  {"alphabet", new 
char[]{0x03b1,0x03b2,0x03b3,0x03b4,0x03b5,0x03b6,0x03b7,0x03b8,0x03b9,0x03ba,0x03bb,0x03bc,0x03bd,0x03be,0x03bf,0x03c0,0x03c1,0x03c2,0x03c3,0x03c4,0x03c5,0x03c6,0x03c7,0x03c8,0x03c9}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "LeftToRight"},
  
  //language numbering 
  //{"numbering", "additive"},
  {"numbering", "multiplicative-additive"},
  {"multiplierOrder", "precedes"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer()},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{100, 10, 1}},
  //These only used for mutiplicative-additive numbering
  {"multiplier", new int[]{1000}},
  {"multiplierChar", new char[]{0x03d9}},
  // chinese only??
  {"zero", new char[0]},
  //{"digits", new char[]{'a','b','c','d','e','f','g','h','i'}},
  {"digits", new char[]{0x03b1,0x03b2,0x03b3,0x03b4,0x03b5,0x03db, 
0x03b6,0x03b7,0x03b8}},
  {"tens", new 
char[]{0x03b9,0x03ba,0x03bb,0x03bc,0x03bd,0x03be,0x03bf,0x03c0,0x03df}},  
  {"hundreds", new 
char[]{0x03c1,0x03c2,0x03c4,0x03c5,0x03c6,0x03c7,0x03c8,0x03c9,0x03e1}},
  //{"thousands", new 
char[]{0x10D9,0x10DA,0x10DB,0x10DC,0x10DD,0x10DE,0x10DF,0x10E0,0x10E1}},  
  
  //hundreds, etc...
  {"tables", new String[]{"hundreds", "tens", "digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_en.java
  
  Index: XSLTResources_en.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_en extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","en"},
  {"help_language", "en"},
  {"language", "en"},
  
   
  {"alphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "additive"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer()},
  
  //These would not be used for EN. Only used for traditional numbering   
  //{"numberGroups", new int[]{10,1}},
  //These only used for mutiplicative-additive numbering
  //{"multiplier", "10"},
  //{"multiplierChar", "M"}, 
  //{"digits", new char[]{'a','b','c','d','e','f','g','h','i'}},
  //{"digits", new 
char[]{0x10D0,0x10D1,0x10D2,0x10D3,0x10D4,0x10D5,0x10D6,0x10D7,0x10D8}},
  //{"tens", new 
char[]{0x10D9,0x10DA,0x10DB,0x10DC,0x10DD,0x10DE,0x10DF,0x10E0,0x10E1}},  
  //hundreds, etc...
  //{"tables", new String[]{"tens", "digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_he.java
  
  Index: XSLTResources_he.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_he extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","he"},
  {"help_language", "he"},
  {"language", "he"},
  
   
  {"alphabet", new 
char[]{0x05D0,0x05D1,0x05D2,0x05D3,0x05D4,0x05D5,0x05D6,0x05D7,0x05D8,0x05D9,0x05DA,0x05DB,0x05DC,0x05DD,0x05DE,0x05DF,0x05E0,0x05E1}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "RightToLeft"},
  
  //language numbering   
  {"numbering", "additive"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer()},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{10,1}},
  //These only used for mutiplicative-additive numbering
  //{"multiplier", "10"},
  //{"multiplierChar", "M"}, 
  //{"digits", new char[]{'a','b','c','d','e','f','g','h','i'}},
  {"digits", new 
char[]{0x05D0,0x05D1,0x05D2,0x05D3,0x05D4,0x05D5,0x05D6,0x05D7,0x05D8}},
  {"tens", new 
char[]{0x05D9,0x05DA,0x05DB,0x05DC,0x05DD,0x05DE,0x05DF,0x05E0,0x05E1}},  
  //hundreds, etc...
  {"tables", new String[]{"tens", "digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_hy.java
  
  Index: XSLTResources_hy.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_hy extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","hy"},
  {"help_language", "hy"},
  {"language", "hy"},
  
   
  {"alphabet", new 
char[]{0x0561,0x0562,0x0563,0x0564,0x0565,0x0566,0x0567,0x0568,0x0569,0x056A,0x056B,0x056C,0x056D,0x056E,0x056F,0x0567,0x0568,0x0572,0x0573,0x0574,0x0575,0x0576,0x0577,0x0578,0x0579,0x057A,0x057B,0x057C,0x057D,0x057E,0x057F,0x0580,0x0581,0x0582,0x0583,0x0584}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "additive"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer()},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{1000,100,10,1}},
  //These only used for mutiplicative-additive numbering
  //{"multiplier", "10"},
  //{"multiplierChar", "M"}, 
  //{"digits", new char[]{'a','b','c','d','e','f','g','h','i'}},
  {"digits", new 
char[]{0x0561,0x0562,0x0563,0x0564,0x0565,0x0566,0x0567,0x0568,0x0569}},
  {"tens", new 
char[]{0x056A,0x056B,0x056C,0x056D,0x056E,0x056F,0x0567,0x0568,0x0572}},  
  {"hundreds", new 
char[]{0x0573,0x0574,0x0575,0x0576,0x0577,0x0578,0x0579,0x057A,0x057B}},
  {"thousands", new 
char[]{0x057C,0x057D,0x057E,0x057F,0x0580,0x0581,0x0582,0x0583,0x0584}},
  
  {"tables", new String[]{"thousands","hundreds","tens", "digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_ja_JP_A.java
  
  Index: XSLTResources_ja_JP_A.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_ja_JP_A extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","ja"},
  {"help_language", "ja"},
  {"language", "ja"},
  
  
  {"alphabet", new 
char[]{0x30a2,0x30a4,0x30a6,0x30a8,0x30aa,0x30ab,0x30ad,0x30af,0x30b1,0x30b3,0x30b5,0x30b7,0x30b9,0x30bb,0x30bd,0x30bf,0x30c1,0x30c4,0x30c6,0x30c8,0x30ca,0x30cb,0x30cc,0x30cd,0x30ce,0x30cf,0x30d2,0x30d5,0x30d8,0x30db,0x30de,0x30df,0x30e0,0x30e1,0x30e2,0x30e4,0x30e6,0x30e8,0x30e9,0x30ea,0x30eb,0x30ec,0x30ed,0x30ef,0x30f0,0x30f1,0x30f2,0x30f3}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation 
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "multiplicative-additive"},
  {"multiplierOrder", "follows"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer(10000000000)},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{1}},
  //These only used for mutiplicative-additive numbering
  {"multiplier", new int [] {1000000000,100000000,10000,1000,100,10}},
  {"multiplierChar", new 
char[]{0x4EAC,0x5146,0x5104,0x4E07,0x5343,0x767e,0x5341}}, 
  // chinese only? 
  {"zero", new char[0]},
  {"digits", new 
char[]{0x4E00,0x4E8C,0x4E09,0x56DB,0x4E94,0x516D,0x4E03,0x516B,0x4E5D}},
  {"tables", new String[]{"digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_ja_JP_HA.java
  
  Index: XSLTResources_ja_JP_HA.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_ja_JP_HA extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","ja"},
  {"help_language", "ja"},
  {"language", "ja"},
  
  
  {"alphabet", new 
char[]{0x3042,0x3044,0x3046,0x3048,0x304a,0x304b,0x304d,0x304f,0x3051,0x3053,0x3055,0x3057,0x3059,0x305b,0x305d,0x305f,0x3061,0x3064,0x3066,0x3068,0x306a,0x306b,0x306c,0x306d,0x306e,0x306f,0x3072,0x3075,0x3078,0x307b,0x307e,0x307f,0x3080,0x3081,0x3082,0x3084,0x3086,0x3088,0x3089,0x308a,0x308b,0x308c,0x308d,0x308f,0x3090,0x3091,0x3092,0x3093}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation 
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "multiplicative-additive"},
  {"multiplierOrder", "follows"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer(10000000000)},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{1}},
  //These only used for mutiplicative-additive numbering
  {"multiplier", new int [] {1000000000,100000000,10000,1000,100,10}},
  {"multiplierChar", new 
char[]{0x4EAC,0x5146,0x5104,0x4E07,0x5343,0x767e,0x5341}}, 
  // chinese only? 
  {"zero", new char[0]},
  {"digits", new 
char[]{0x4E00,0x4E8C,0x4E09,0x56DB,0x4E94,0x516D,0x4E03,0x516B,0x4E5D}},
  {"tables", new String[]{"digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_ja_JP_HI.java
  
  Index: XSLTResources_ja_JP_HI.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_ja_JP_HI extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","ja"},
  {"help_language", "ja"},
  {"language", "ja"},
  
   
  {"alphabet", new 
char[]{0x3044,0x308d,0x306f,0x306b,0x307b,0x3078,0x3068,0x3061,0x308a,0x306c,0x308b,0x3092,0x308f,0x304b,0x3088,0x305f,0x308c,0x305d,0x3064,0x306d,0x306a,0x3089,0x3080,0x3046,0x3090,0x306e,0x304a,0x304f,0x3084,0x307e,0x3051,0x3075,0x3053,0x3048,0x3066,0x3042,0x3055,0x304d,0x3086,0x3081,0x307f,0x3057,0x3091,0x3072,0x3082,0x305b,0x3059}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "multiplicative-additive"},
  {"multiplierOrder", "follows"},
  
  // largest numerical value 
  //{"MaxNumericalValue", new Integer(10000000000)},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{1}},
  //These only used for mutiplicative-additive numbering
  {"multiplier", new int [] {1000000000,100000000,10000,1000,100,10}},
  {"multiplierChar", new 
char[]{0x4EAC,0x5146,0x5104,0x4E07,0x5343,0x767e,0x5341}}, 
  // chinese only??
  {"zero", new char[0]},
  {"digits", new 
char[]{0x4E00,0x4E8C,0x4E09,0x56DB,0x4E94,0x516D,0x4E03,0x516B,0x4E5D}},
  {"tables", new String[]{"digits"}}
  };    
  }
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_ja_JP_I.java
  
  Index: XSLTResources_ja_JP_I.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_ja_JP_I extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","ja"},
  {"help_language", "ja"},
  {"language", "ja"},
  
   
  {"alphabet", new 
char[]{0x30a4,0x30ed,0x30cf,0x30cb,0x30db,0x30d8,0x30c8,0x30c1,0x30ea,0x30cc,0x30eb,0x30f2,0x30ef,0x30ab,0x30e8,0x30bf,0x30ec,0x30bd,0x30c4,0x30cd,0x30ca,0x30e9,0x30e0,0x30a6,0x30f0,0x30ce,0x30aa,0x30af,0x30e4,0x30de,0x30b1,0x30d5,0x30b3,0x30a8,0x30c6,0x30a2,0x30b5,0x30ad,0x30e6,0x30e1,0x30df,0x30b7,0x30f1,0x30d2,0x30e2,0x30bb,0x30b9}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "multiplicative-additive"},
  {"multiplierOrder", "follows"},
  
  // largest numerical value 
  //{"MaxNumericalValue", new Integer(10000000000)},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{1}},
  //These only used for mutiplicative-additive numbering
  {"multiplier", new int [] {1000000000,100000000,10000,1000,100,10}},
  {"multiplierChar", new 
char[]{0x4EAC,0x5146,0x5104,0x4E07,0x5343,0x767e,0x5341}}, 
  // chinese only??
  {"zero", new char[0]},
  {"digits", new 
char[]{0x4E00,0x4E8C,0x4E09,0x56DB,0x4E94,0x516D,0x4E03,0x516B,0x4E5D}},
  {"tables", new String[]{"digits"}}
  };    
  }
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_ka.java
  
  Index: XSLTResources_ka.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_ka extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","ka"},
  {"help_language", "ka"},
  {"language", "ka"},
  
   
  {"alphabet", new 
char[]{0x10D0,0x10D1,0x10D2,0x10D3,0x10D4,0x10D5,0x10D6,0x10f1,0x10D7,0x10D8,0x10D9,0x10DA,0x10DB,0x10DC,0x10f2,0x10DD,0x10DE,0x10DF,0x10E0,0x10E1,0x10E2,0x10E3,0x10E4,0x10E5,0x10E6,0x10E7,0x10E8,0x10E9,0x10EA,0x10EB,0x10EC,0x10ED,0x10EE,0x10F4,0x10EF,0x10F0}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "additive"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer(10000000000)},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{1000,100,10,1}},
  //These used for additive numbering
  {"digits", new 
char[]{0x10D0,0x10D1,0x10D2,0x10D3,0x10D4,0x10D5,0x10D6,0x10f1,0x10D7}},
  {"tens", new 
char[]{0x10D8,0x10D9,0x10DA,0x10DB,0x10DC,0x10f2,0x10DD,0x10DE,0x10DF}},  
  {"hundreds", new 
char[]{0x10E0,0x10E1,0x10E2,0x10E3,0x10E4,0x10E5,0x10E6,0x10E7,0x10E8}},
  {"thousands", new 
char[]{0x10E9,0x10EA,0x10EB,0x10EC,0x10ED,0x10EE,0x10F4,0x10EF,0x10F0}},
  
  {"tables", new String[]{"thousands","hundreds","tens", "digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_zh_CN.java
  
  Index: XSLTResources_zh_CN.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_zh_CN extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","zh"},
  {"help_language", "zh"},
  {"language", "zh"},
  
   
  {"alphabet", new 
char[]{0xff21,0xff22,0xff23,0xff24,0xff25,0xff26,0xff27,0xff28,0xff29,0xff2a,0xff2b,0xff2c,0xff2d,0xff2e,0xff2f,0xff30,0xff31,0xff32,0xff33,0xff34,0xff35,0xff36,0xff37,0xff38,0xff39,0xff3a}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation 
  {"orientation", "LeftToRight"},
  
  //language numbering   
  {"numbering", "multiplicative-additive"},
  {"multiplierOrder", "follows"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer(100000000)},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{1}},
  // simplified chinese  
  {"zero", new char[]{0x96f6}}, 
  //These only used for mutiplicative-additive numbering
  {"multiplier", new int [] {100000000,10000,1000,100,10}},
  {"multiplierChar", new char[]{0x4ebf,0x4e07,0x5343,0x767e,0x5341}}, 
  {"digits", new 
char[]{0x4e00,0x4e8c,0x4e09,0x56db,0x4e94,0x516d,0x4e03,0x516b,0x4e5d}},
  {"tables", new String[]{"digits"}}
  };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/res/XSLTResources_zh_TW.java
  
  Index: XSLTResources_zh_TW.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.res;
  import java.util.*;
  //
  //  LangResources_en.properties
  //
  public class XSLTResources_zh_TW extends XSLTResourceBundle 
  {
  public Object[][] getContents()
  {
        return contents;
  }     
  
  static final Object[][] contents = {
  
  {"ui_language","zh"},
  {"help_language", "zh"},
  {"language", "zh"},
  
  {"alphabet", new 
char[]{0xff21,0xff22,0xff23,0xff24,0xff25,0xff26,0xff27,0xff28,0xff29,0xff2a,0xff2b,0xff2c,0xff2d,0xff2e,0xff2f,0xff30,0xff31,0xff32,0xff33,0xff34,0xff35,0xff36,0xff37,0xff38,0xff39,0xff3a}},
  {"tradAlphabet", new 
char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}},
  
  //language orientation 
  {"orientation", "LeftToRight"},
  
  //language numbering    
  {"numbering", "multiplicative-additive"},
  {"multiplierOrder", "follows"},
  
  // largest numerical value
  //{"MaxNumericalValue", new Integer(100000000)},
  
  //These would not be used for EN. Only used for traditional numbering   
  {"numberGroups", new int[]{1}},
  // simplified chinese 
  {"zero", new char[]{0x96f6}},
  
  //These only used for mutiplicative-additive numbering 
  {"multiplier", new int [] {100000000,10000,1000,100,10}},
  {"multiplierChar", new char[]{0x5104,0x842c,0x4edf,0x4f70,0x62fe}}, 
  {"digits", new 
char[]{0x58f9,0x8cb3,0x53c3,0x8086,0x4f0d,0x9678,0x67d2,0x634c,0x7396}},
  {"tables", new String[]{"digits"}}
  };    
  }  
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/stree/AttrImpl.java
  
  Index: AttrImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Attr;
  import org.w3c.dom.Element;
  import org.xml.sax.Attributes;
  import org.w3c.dom.DOMException;
  
  public class AttrImpl extends Child implements Attr
  {
    private String m_name;
    private String m_value;
    private boolean m_specified = true;
    
    AttrImpl(String name, String value)
    {
      m_name = name;
      m_value = value;
    }
    
    /**
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() 
    {
      return Node.ATTRIBUTE_NODE;
    }
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return m_name;
    }
    
    /**
     * The namespace URI of this node, or <code>null</code> if it is 
     * unspecified.
     * <br>This is not a computed value that is the result of a namespace 
     * lookup based on an examination of the namespace declarations in scope. 
     * It is merely the namespace URI given at creation time.
     * <br>For nodes of any type other than <code>ELEMENT_NODE</code> and 
     * <code>ATTRIBUTE_NODE</code> and nodes created with a DOM Level 1 
     * method, such as <code>createElement</code> from the 
     * <code>Document</code> interface, this is always <code>null</code>.Per 
     * the Namespaces in XML Specification  an attribute does not inherit its 
     * namespace from the element it is attached to. If an attribute is not 
     * explicitly given a namespace, it simply has no namespace.
     */
    public String       getNamespaceURI()
    {
      return null;
    }
    
    /**
     * The namespace prefix of this node, or <code>null</code> if it is 
     * unspecified.
     * @since DOM Level 2
     */
    public String       getPrefix()
  {
    return null;
    }
  
  /**
     * Returns the local part of the qualified name of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public String       getLocalName()
    {
      return m_name;
    }
    
    /**
     * Returns the value of this attribute node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public String getValue ()
    {      
      return m_value;
    } 
    
    /** Same as getValue(). */
    public String getNodeValue()
      throws DOMException
    {
      return m_value;
    }
    
    /**
     * Sets the value of this attribute node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public void setValue (String value) throws DOMException
    {      
      m_value = value;
    }
    
    /**
       *  If this attribute was explicitly given a value in the original 
       * document, this is <code>true</code> ; otherwise, it is 
       * <code>false</code> . Note that the implementation is in charge of this 
       * attribute, not the user. If the user changes the value of the 
       * attribute (even if it ends up having the same value as the default 
       * value) then the <code>specified</code> flag is automatically flipped 
       * to <code>true</code> .  To re-specify the attribute as the default 
       * value from the DTD, the user must delete the attribute. The 
       * implementation will then make a new attribute available with 
       * <code>specified</code> set to <code>false</code> and the default value 
       * (if one exists).
       * <br> In summary: If the attribute has an assigned value in the 
document 
       * then  <code>specified</code> is <code>true</code> , and the value is 
       * the  assigned value. If the attribute has no assigned value in the 
       * document and has  a default value in the DTD, then 
       * <code>specified</code> is <code>false</code> ,  and the value is the 
       * default value in the DTD. If the attribute has no assigned value in 
       * the document and has  a value of #IMPLIED in the DTD, then the  
       * attribute does not appear  in the structure model of the document.
       */
      public boolean getSpecified()
      {
        return m_specified;
      }
      
     /**
       *  The <code>Element</code> node this attribute is attached to or 
       * <code>null</code> if this attribute is not in use.
       * @since DOM Level 2
       */
      public Element getOwnerElement()
      {
        return (Element)getParentNode();
      }
      
      public String getName()
      {
        return m_name;
      }  
      
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/stree/AttrImplNS.java
  
  Index: AttrImplNS.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.xml.sax.Attributes;
  
  public class AttrImplNS extends AttrImpl
  {
    private String m_namespaceURI;                  // attribute index
    
    
    AttrImplNS(String uri, String name, String value)
    {
      super(name, value);
      m_namespaceURI = uri;
    }
    
     
    
    /**
     * The namespace URI of this node, or <code>null</code> if it is 
     * unspecified.
     * <br>This is not a computed value that is the result of a namespace 
     * lookup based on an examination of the namespace declarations in scope. 
     * It is merely the namespace URI given at creation time.
     * <br>For nodes of any type other than <code>ELEMENT_NODE</code> and 
     * <code>ATTRIBUTE_NODE</code> and nodes created with a DOM Level 1 
     * method, such as <code>createElement</code> from the 
     * <code>Document</code> interface, this is always <code>null</code>.Per 
     * the Namespaces in XML Specification  an attribute does not inherit its 
     * namespace from the element it is attached to. If an attribute is not 
     * explicitly given a namespace, it simply has no namespace.
     */
    public String       getNamespaceURI()
    {
      return m_namespaceURI;    
    }
    
    /**
     * The namespace prefix of this node, or <code>null</code> if it is 
     * unspecified.
     * @since DOM Level 2
     */
    public String       getPrefix()
  {
      String m_name = getNodeName();
      int indexOfNSSep = m_name.indexOf(':');
      return (indexOfNSSep >= 0) 
                      ? m_name.substring(0, indexOfNSSep) : null;
    }
  
  /**
     * Returns the local part of the qualified name of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public String       getLocalName()
    {
      String m_name = getNodeName();
      int indexOfNSSep = m_name.indexOf(':');
      return (indexOfNSSep > 0) 
                      ? m_name.substring(indexOfNSSep+1) : m_name;
    }
    
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/CDATASectionImpl.java
  
  Index: CDATASectionImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.CDATASection;
  
  public class CDATASectionImpl extends TextImpl implements CDATASection
  {
    public CDATASectionImpl (String data)
    {
      super(data);
    }
  
    public CDATASectionImpl (char ch[], int start, int length)
    {
      super(ch, start, length);
    }
  
    /** Returns the node type. */
    public short getNodeType() 
    {
      return Node.CDATA_SECTION_NODE;
    }
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return "#cdata-section";
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/stree/Child.java
  
  Index: Child.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.apache.xalan.utils.UnImplNode;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import org.w3c.dom.DOMException;
  import org.w3c.dom.NamedNodeMap;
  
  public class Child extends UnImplNode
  {
    private Parent m_parent;
    private short m_level;
    
    /**
     * Set the parent of the node.
     */
    protected void setParent(Parent parent)
    {
      m_parent = parent;
    }
    
    /**
     * Return if this node has had all it's children added, i.e. 
     * if a endElement event has occured.  An atomic node always 
     * returns true.
     */
    public boolean isComplete()
    {
      // Atomic nodes are always complete.
      return true;
    }
    
    /**
     * The position in the parent's list.
     */
    private int m_childPos;
    
    /**
     * <meta name="usage" content="internal"/>
     * Set the position of the child of an element in the parent 
     * array.
     */
    protected void SetChildPosition(int pos)
    {
      m_childPos = (short)pos;
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the position of the child of an element in the parent 
     * array.
     */
    public int getChildPosition()
    {
      return m_childPos;
    }
    
    /**
     * The UID (document order index).
     */
    private int m_uid;
    
    /**
     * Set the UID (document order index).
     */
    protected void setUid(int kIndex)
    {
      m_uid = kIndex;
    }
    
    /**
     * Get the UID (document order index).
     */
    public int getUid()
    {
      return m_uid;
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the depth level of this node in the tree.
     */
    public short getLevel()
    {
      return m_level;
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the depth level of this node in the tree.
     */
    public void setLevel(short level)
    {
      m_level = level;
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the value of K.  K is the maximum width of the tree.
     */
    public int getK()
    {
      return getDocumentImpl().getK();
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the value of Y.  Y is the maximum depth of the tree.
     * Needed to calculate depth-first (document order) numbering.
     */
    public int getY()
    {
      return getDocumentImpl().getY();
    }
  
    /**
     * Get the root Document Implementation.
     */
    DocumentImpl getDocumentImpl()
    {
    Child n = this;
    while(n.getUid() > 1)
        n = (Child)n.getParentNode(); 
      return (DocumentImpl)n;
    }
  
    
    // ================ Node interface implementation ==============
        
    /**
     * The parent of this node. All nodes, except <code>Attr</code>, 
     * <code>Document</code>, <code>DocumentFragment</code>, 
     * <code>Entity</code>, and <code>Notation</code> may have a parent. 
     * However, if a    node has just been created and not yet added to the 
     * tree, or if it has been removed from the tree, this is 
     * <code>null</code>.
     */
    public Node         getParentNode()
  {
      return this.m_parent;
  }
  
    /**
     * The first child of this node. If there is no such node, this returns 
     * <code>null</code>.
     */
    public Node         getFirstChild()
    {
    return null;
    }
  
    /**
     * The last child of this node. If there is no such node, this returns 
     * <code>null</code>.
     */
    public Node         getLastChild()
    {
    return null;
    }
  
    /**
     * The node immediately preceding this node. If there is no such node, 
     * this returns <code>null</code>.
     */
    public Node         getPreviousSibling()
    {
      if (m_parent!= null)
      {
        try{
        return m_parent.getChild(getChildPosition()-1);
        }
        catch(Exception e)
        {}
      }  
      return null;
    }
  
    /**
     * The node immediately following this node. If there is no such node, 
     * this returns <code>null</code>.
     */
    public Node         getNextSibling()
    {
      if (m_parent!= null)
      {
        try
        {
          return m_parent.getChild(getChildPosition()+1);
        }
        catch(Exception e)
        {}
      }  
      return null;
    }
        
    /**
     * The <code>Document</code> object associated with this node. This is 
     * also the <code>Document</code> object used to create new nodes. When 
     * this node is a <code>Document</code> or a <code>DocumentType</code> 
     * which is not used with any <code>Document</code> yet, this is 
     * <code>null</code>.
     * @version DOM Level 2
     */
    public Document     getOwnerDocument()
  {
    return getDocumentImpl();
    }
  
    /**
     *  This is a convenience method to allow easy determination of whether a 
     * node has any children.
     * @return  <code>true</code> if the node has any children, 
     *   <code>false</code> if the node has no children.
     */
    public boolean      hasChildNodes()
  {
      return false;
  }
  
    /**
     * Tests whether the DOM implementation implements a specific feature and 
     * that feature is supported by this node.
     * @since DOM Level 2
     * @param feature The string of the feature to test. This is the same name 
     *   that which can be passed to the method <code>hasFeature</code> on 
     *   <code>DOMImplementation</code>.
     * @param version This is the version number of the feature to test. In 
     *   Level 2, version 1, this is the string "2.0". If the version is not 
     *   specified, supporting any version of the feature will cause the 
     *   method to return <code>true</code>.
     * @return Returns <code>true</code> if the specified feature is supported 
     *   on this node, <code>false</code> otherwise.
     */
    public boolean      supports(String feature, 
                                 String version)
  {
      return false;
  }
  
    /**
     * The namespace URI of this node, or <code>null</code> if it is 
     * unspecified.
      */
    public String       getNamespaceURI()
    {
      return null;
    }
    
    /**
     * The namespace prefix of this node, or <code>null</code> if it is 
     * unspecified.
     * @since DOM Level 2
     */
    public String       getPrefix()
  {
    return null;
    }
  
  /**
     * Returns the local part of the qualified name of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public String       getLocalName()
    {
      return null;
    }
    
    /** UnImplemented. */
    public String getTagName()
    {
      return null;
    }
    
    /** Unimplemented. */
    public NamedNodeMap       getAttributes()
    {
      return null;
    }
    
    /** Unimplemented. */
    public void               setAttribute(String name,
                                           String value)
      throws DOMException
    {    
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/CommentImpl.java
  
  Index: CommentImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Comment;
  
  public class CommentImpl extends TextImpl implements Comment
  {
    public CommentImpl (String data)
    {
      super(data);
    }
  
    public CommentImpl (char ch[], int start, int length)
    {
      super(ch, start, length);
    }
  
    /** 
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() 
    {
      return Node.COMMENT_NODE;
    }
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return "#comment";
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/DOMImplementationImpl.java
  
  Index: DOMImplementationImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Document;
  import org.w3c.dom.DocumentType;
  import org.w3c.dom.DOMImplementation;
  import org.w3c.dom.DOMException;
  import org.apache.xalan.utils.UnImplNode;
  
  public class DOMImplementationImpl extends UnImplNode implements 
DOMImplementation
  {
    //
    // Data
    //
  
    // static
  
    /** Dom implementation singleton. */
    static DOMImplementationImpl singleton = new DOMImplementationImpl();
  
    //
    // DOMImplementation methods
    //
  
    /** 
     * Test if the DOM implementation supports a specific "feature" --
     * currently meaning language and level thereof.
     * 
     * @param feature      The package name of the feature to test.
     * In Level 1, supported values are "HTML" and "XML" (case-insensitive).
     * At this writing, org.apache.xerces.dom supports only XML.
     *
     * @param version      The version number of the feature being tested.
     * This is interpreted as "Version of the DOM API supported for the
     * specified Feature", and in Level 1 should be "1.0"
     *
     * @returns    true iff this implementation is compatable with the
     * specified feature and version.
     */
    public boolean hasFeature(String feature, String version) {
  
      // Currently, we support only XML Level 1 version 1.0
      return 
        (feature.equalsIgnoreCase("XML") 
         && (version == null
             || version.equals("1.0")
             || version.equals("2.0")))
        || (feature.equalsIgnoreCase("Events") 
            && (version == null
                || version.equals("2.0")))
        || (feature.equalsIgnoreCase("MutationEvents") 
            && (version == null
                || version.equals("2.0")))
        || (feature.equalsIgnoreCase("Traversal") 
            && (version == null
                || version.equals("2.0")))
        ;
  
    } // hasFeature(String,String):boolean
  
    //
    // Public methods
    //
  
    /** NON-DOM: Obtain and return the single shared object */
    public static DOMImplementation getDOMImplementation() {
      return singleton;
    }  
    
    /**
     * Introduced in DOM Level 2. <p>
     * 
     * Creates an empty DocumentType node.
     *
     * @param qualifiedName The qualified name of the document type to be 
created. 
     * @param publicID The document type public identifier.
     * @param systemID The document type system identifier.
     * @since WD-DOM-Level-2-19990923
     */
    public DocumentType       createDocumentType(String qualifiedName, 
                                                 String publicID, 
                                                 String systemID)
    {
      // return new DocumentTypeImpl(null, qualifiedName, publicID, systemID);
      return null;
    }
    
    /**
     * Introduced in DOM Level 2. <p>
     * 
     * Creates an XML Document object of the specified type with its document
     * element.
     *
     * @param namespaceURI     The namespace URI of the document
     *                         element to create, or null. 
     * @param qualifiedName    The qualified name of the document
     *                         element to create, or null. 
     * @param doctype          The type of document to be created or null.<p>
     *
     *                         When doctype is not null, its
     *                         Node.ownerDocument attribute is set to
     *                         the document being created.
     * @return Document        A new Document object.
     * @throws DOMException    WRONG_DOCUMENT_ERR: Raised if doctype has
     *                         already been used with a different document.
     * @since WD-DOM-Level-2-19990923
     */
    public Document           createDocument(String namespaceURI, 
                                             String qualifiedName, 
                                             DocumentType doctype)
      throws DOMException
    {
      if (doctype != null && doctype.getOwnerDocument() != null) {
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, 
          "DOM005 Wrong document");
      }
      DocumentImpl doc = new DocumentImpl(doctype);
      return doc;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/DocumentFragmentImpl.java
  
  Index: DocumentFragmentImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DocumentFragment;
  
  public class DocumentFragmentImpl extends Parent implements DocumentFragment
  {
    /** 
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() 
    {
      return Node.DOCUMENT_FRAGMENT_NODE;
    }
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return "#document-fragment";
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/DocumentImpl.java
  
  Index: DocumentImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.ProcessingInstruction;
  import org.w3c.dom.CDATASection;
  import org.w3c.dom.Text;
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.Comment;
  import org.w3c.dom.Attr;
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.DocumentType;
  import org.w3c.dom.DOMException;
  
  public class DocumentImpl extends Parent
  {
    DocumentImpl()
    {
          m_bUpIndexer = new LevelIndexer();
    }
  
    DocumentImpl(DocumentType doctype)
    {
      if(null != doctype)
        m_docType = (DocumentTypeImpl)doctype;
          m_bUpIndexer = new LevelIndexer();
    }
    
    private SourceTreeHandler m_sourceTreeHandler;
    SourceTreeHandler getSourceTreeHandler()
    {
      return m_sourceTreeHandler;
    }
    
    void setSourceTreeHandler(SourceTreeHandler h)
    {
      m_sourceTreeHandler = h;
    }
    
    private boolean indexedLookup = false;   // for now
      
    /**
     * 
     */
    private LevelIndexer m_bUpIndexer ;
   
    /**
     * 
     */
    public LevelIndexer getLevelIndexer()
    {
      return m_bUpIndexer;
    }
    
    DocumentTypeImpl m_docType;
    
    private int m_docOrderCount = 1;
  
    /**
     * Increment the document order count.  Needs to be called 
     * when a child is added.
     */
    protected void incrementDocOrderCount()
    {
      m_docOrderCount++;
    }
    
    /**
     * Increment the document order count.  Needs to be called 
     * when a child is added.
     */
    protected int getDocOrderCount()
    {
      return m_docOrderCount;
    }  
  
    /**
     * For XML, this provides access to the Document Type Definition.
     * For HTML documents, and XML documents which don't specify a DTD,
     * it will be null.
     */
    public DocumentType getDoctype() 
    {
      return m_docType;
    }
    
    /**
     * The document element.
     */
    ElementImpl m_docElement;
    
    /**
     * Convenience method, allowing direct access to the child node
     * which is considered the root of the actual document content.
     */
    public Element getDocumentElement() 
    {
      return m_docElement;
    }
    
    /**
     * Append a child to the child list.
     * @param newChild Must be a org.apache.xalan.stree.Child.
     * @exception ClassCastException if the newChild isn't a 
org.apache.xalan.stree.Child.
     */
    public Node appendChild(Node newChild)
      throws DOMException
    {
      int type = newChild.getNodeType();
      if (type == Node.ELEMENT_NODE) 
      {
        if(null != m_docElement)
          throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
            "DOM006 Hierarchy request error");
        
        m_docElement = (ElementImpl)newChild;
      }
      else if (type == Node.DOCUMENT_TYPE_NODE) 
      {
        m_docType = (DocumentTypeImpl)newChild;
      }
      return super.appendChild(newChild);
    }
  
  
    /** Returns the node type. */
    public short getNodeType() 
    {
      return Node.DOCUMENT_NODE;
    }
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return "#document";
    }
    
    /** Unimplemented. */
    public Element            createElement(String tagName)
      throws DOMException
    {
      if (indexedLookup)
        return new IndexedElemImpl(tagName);
      else
        return new ElementImpl(tagName);
    }
  
    /** Create a DocumentFragment. */
    public DocumentFragment   createDocumentFragment()
    {
      return new DocumentFragmentImpl();
    }
  
    /** Create a Text node. */
    public Text               createTextNode(String data)
    {
      return new TextImpl(data);
    }
  
    /** Create a Comment node. */
    public Comment            createComment(String data)
    {
      return new CommentImpl(data);
    }
  
    /** Create a CDATASection node. */
    public CDATASection       createCDATASection(String data)
      throws DOMException
  
    {
      return new CDATASectionImpl(data);
    }
  
    /** Create a ProcessingInstruction node. */
    public ProcessingInstruction createProcessingInstruction(String target,
                                                             String data)
      throws DOMException
  
    {
      return new ProcessingInstructionImpl(target, data);
    }
  
    /** Unimplemented right now, but I should probably implement. */
    public Node               importNode(Node importedNode,
                                         boolean deep)
      throws DOMException
    {
      return super.importNode(importedNode, deep);
    }
  
    /** Unimplemented. */
    public Element            createElementNS(String namespaceURI,
                                              String qualifiedName)
      throws DOMException
    {
      if (indexedLookup)
        return new IndexedElemWithNS(namespaceURI, qualifiedName);
      else
        return new ElementImplWithNS(namespaceURI, qualifiedName);
      //return super.createElementNS(namespaceURI, qualifiedName);
    }
  
    /** Unimplemented. */
    public Attr               createAttributeNS(String namespaceURI,
                                                String qualifiedName)
      throws DOMException
    {
      return super.createAttributeNS(namespaceURI, qualifiedName);
    }
    
    
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/DocumentTypeImpl.java
  
  Index: DocumentTypeImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DocumentType;
  import org.w3c.dom.NamedNodeMap;
  
  public class DocumentTypeImpl extends Child implements DocumentType 
  {
    DocumentTypeImpl(String name)
    {
      m_name = name;
    }
    
    private String m_name;
    private String m_publicID;
    private String m_systemID;
    private String m_internalSubset;
    
    /** 
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() 
    {
      return Node.DOCUMENT_TYPE_NODE;
    }
    
    /** Returns the node name. */
    public String getNodeName() 
    {
      return m_name; // I guess I need the name of the document type
    }
    
    /**
     * The name of DTD; i.e., the name immediately following the 
     * <code>DOCTYPE</code> keyword.
     */
    public String       getName()
  {
      return m_name;
  }
  
    
      /**
       * A <code>NamedNodeMap</code> containing the general entities, both 
       * external and internal, declared in the DTD. Parameter entities are not 
       *  contained. Duplicates are discarded. For example in:
       * <pre>
       * &lt;!DOCTYPE ex SYSTEM "ex.dtd" [
       *   &lt;!ENTITY foo "foo"&gt;
       *   &lt;!ENTITY bar "bar"&gt;
       *   &lt;!ENTITY bar "bar2"&gt;
       *   &lt;!ENTITY % baz "baz"&gt;
       * ]&gt;
       * &lt;ex/&gt;</pre>
       *   the interface 
       * provides access to <code>foo</code> and the first declaration of 
       * <code>bar</code> but not the second declaration of  <code>bar</code> 
       * or <code>baz</code>. Every node in this map also implements the 
       * <code>Entity</code> interface.
       * <br>The DOM Level 2 does not support editing entities, therefore 
       * <code>entities</code> cannot be altered in any way.
       */
      public NamedNodeMap getEntities()
    {
        return null;
    }
    
      /**
       * A <code>NamedNodeMap</code> containing  the notations declared in the 
       * DTD. Duplicates are discarded. Every node in this map also implements 
       * the <code>Notation</code> interface.
       * <br>The DOM Level 2 does not support editing notations, therefore 
       * <code>notations</code> cannot be altered in any way.
       */
      public NamedNodeMap getNotations()
    {
        return null;
    }
    
      /**
       * The public identifier of the external subset.
       * @since DOM Level 2
       */
      public String       getPublicId()
    {
        return m_publicID;
    }
    
      /**
       * The system identifier of the external subset.
       * @since DOM Level 2
       */
      public String       getSystemId()
    {
        return m_systemID;
    }
    
      /**
       * The internal subset as a string.
       * @since DOM Level 2
       */
      public String       getInternalSubset()
    {
        return m_internalSubset;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/ElementImpl.java
  
  Index: ElementImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.xml.sax.Attributes;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.Attr;
  import org.w3c.dom.DOMException;
  
  
  public class ElementImpl extends Parent implements Attributes, NamedNodeMap
    
  {
    private String m_name;
    private short attrsEnd;
    
    ElementImpl (String name)
    {
      m_name = name;    
    }
  
    ElementImpl (String name, Attributes atts)
    {
      m_name = name;
      setAttributes(atts);
    }
  
    /** 
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() {
      return Node.ELEMENT_NODE;
    }
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return m_name;
    }
    
    /**
     * Returns the local part of the qualified name of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public String       getLocalName()
    {
      return m_name;
    }
    
    /**
     * Returns the tag name of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public String getTagName()
    {
      return m_name;
    }
    
    /**
     * The first child of this node. If there is no such node, this returns
     * Factor in any existing attribute nodes. 
     * <code>null</code>.
     */
    public Node         getFirstChild()
    {
      return (getChildCount() == 0) ? null : getChild(getLength());
    }
        
    /**
     * Get the nth attribute child.
     * @param i the index of the child.
     * @exception ArrayIndexOutOfBoundsException if the index is out of bounds.
     * @exception NullPointerException if there are no children.
     */
    public AttrImpl getChildAttribute(int i)
      throws ArrayIndexOutOfBoundsException, NullPointerException
    {
      // wait?
      if (i < getLength()) 
        return (AttrImpl)m_children[i];
      else
        return null;
    }
    
    /**
     * Get the number of children this node currently contains.
     * Factor in the number of attributes at beginning of list.
     * Note that this will only return the number of children 
     * added so far.  If the isComplete property is false, 
     * it is likely that more children will be added.
     */
    public int getChildCount()
    {
      return (null == m_children) ? 0 : m_children.length - getLength();
    }
    
    
    /**
     * Get attributes of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public NamedNodeMap       getAttributes()
    {
      return this;
    }
    
    /**
     * Set attributes of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public void               setAttribute(String name,
                                           String value)
      throws DOMException
    {
      AttrImpl attr = (AttrImpl)createAttribute(name);
      attr.setValue(value);    
    }
    
    /**
     * Set attributes of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */  
    public void               setAttributeNS(String namespaceURI,
                                             String qualifiedName,
                                             String value)
      throws DOMException
    {
      AttrImplNS attr = (AttrImplNS)createAttributeNS(namespaceURI, 
qualifiedName);
      attr.setValue(value);        
    }
    
    /**
     * Set a list of attributes of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */ 
    public void               setAttributes(Attributes atts)
      throws DOMException
    {
      for(int i=0; i< atts.getLength(); i++)
      {
        String uri = atts.getURI(i);
        String name = atts.getQName(i);
        AttrImpl attr;
        if (null != uri || name.indexOf(':') >0)
          attr = (AttrImplNS)createAttributeNS(uri, name);
        else        
          attr = (AttrImpl)createAttribute(name); 
        
        attr.setValue(atts.getValue(i));             
      }        
    }
    
    /**
     *  Create an attribute node. 
     */
    public Attr               createAttribute(String name)
      throws DOMException
    {
      AttrImpl attrImpl = new AttrImpl(name, "");
      int index = getIndex(name);
      if (index<0)
      {  
        appendChild(attrImpl);
        attrsEnd++;
      }  
      else
        m_children[index] = attrImpl;
      return (Attr)attrImpl;    
    }
    
    /** 
     * Create an attribute node with a namespace . 
     */
    public Attr               createAttributeNS(String namespaceURI,
                                                String qualifiedName)
      throws DOMException
    {
      AttrImplNS attrImpl = new AttrImplNS(namespaceURI, qualifiedName, "");
      int index = getIndex(namespaceURI, qualifiedName);
      if (index<0)
      {  
        appendChild(attrImpl);
        attrsEnd++;
      }  
      else
        m_children[index] = attrImpl;
      return (Attr)attrImpl;    
    }
    
    //
    //implement Attributes Interface
    //
    
      /**
       * Return the number of attributes in the list.
       *
       * @return The number of attributes in the list.
       */
      public int getLength ()
      {
        return attrsEnd;
      }
        
  
  
      /**
       * Look up an attribute's Namespace URI by index.
       *
       * @param index The attribute index (zero-based).
       * @return The Namespace URI, or the empty string if none
       *         is available, or null if the index is out of
       *         range.
       */
      public String getURI (int index)
      {
        AttrImpl attr = getChildAttribute(index);
        return attr.getNamespaceURI();     
      }
  
  
      /**
       * Look up an attribute's local name by index.
       *
       * @param index The attribute index (zero-based).
       * @return The local name, or the empty string if Namespace
       *         processing is not being performed, or null
       *         if the index is out of range.
       */
      public  String getLocalName (int index)
      {
        AttrImpl attr = getChildAttribute(index);
        return attr.getLocalName();
      }  
  
  
      /**
       * Look up an attribute's raw XML 1.0 name by index.
       *
       * @param index The attribute index (zero-based).
       * @return The raw XML 1.0 name, or the empty string
       *         if none is available, or null if the index
       *         is out of range.
       */
      public String getQName (int index)
      {
        AttrImpl attr = getChildAttribute(index);
        return attr.getNodeName();
      }  
  
  
      /**
       * Look up an attribute's type by index.
       *
       * @param index The attribute index (zero-based).
       * @return The attribute's type as a string, or null if the
       *         index is out of range.
       */
      public String getType (int index)
      {
        AttrImpl attr = getChildAttribute(index);
        return Integer.toString(attr.getNodeType());
      } 
  
      /**
       * Look up an attribute's value by index.
       *
       * @param index The attribute index (zero-based).
       * @return The attribute's value as a string, or null if the
       *         index is out of range.
       */
      public String getValue (int index)
      {
        AttrImpl attr = getChildAttribute(index);
        return attr.getValue();
      }
      
      /**
       * Look up an attribute's value by name.
       *
       * @param index The attribute index (zero-based).
       * @return The attribute's value as a string, or null if the
       *         index is out of range.
       */
    public String             getAttribute(String name)
    {
      return getValue(name);
    }
  
  
      ////////////////////////////////////////////////////////////////////
      // Name-based query.
      ////////////////////////////////////////////////////////////////////
  
  
      /**
       * Look up the index of an attribute by Namespace name.
       *
       * @param uri The Namespace URI, or the empty string if
       *        the name has no Namespace URI.
       * @param localName The attribute's local name.
       * @return The index of the attribute, or -1 if it does not
       *         appear in the list.
       */
      public int getIndex (String uri, String localPart)
      {
        for (int i = 0; i < getLength(); i++)
        {
          AttrImplNS attr = (AttrImplNS)getChildAttribute(i);
          if (attr.getLocalName().equals(localPart) &&
              attr.getNamespaceURI().equals(uri))
            return i;
        }
        return -1;
      } 
  
      /**
       * Look up the index of an attribute by raw XML 1.0 name.
       *
       * @param rawName The raw (prefixed) name.
       * @return The index of the attribute, or -1 if it does not
       *         appear in the list.
       */
      public int getIndex (String rawName)
      {
        for (int i = 0; i < getLength(); i++)
        {
          AttrImpl attr = getChildAttribute(i);
          if (attr.getNodeName().equals(rawName))
            return i;
        }
        return -1;
      }  
  
      /**
       * Look up an attribute's type by Namespace name.
       *
       * @param uri The Namespace URI, or the empty String if the
       *        name has no Namespace URI.
       * @param localName The local name of the attribute.
       * @return The attribute type as a string, or null if the
       *         attribute is not in the list or if Namespace
       *         processing is not being performed.
       */
      public String getType (String uri, String localName)
      {
        return getType(getIndex(uri, localName));
      } 
  
      /**
       * Look up an attribute's type by raw XML 1.0 name.
       *
       * @param rawName The raw XML 1.0 name.
       * @return The attribute type as a string, or null if the
       *         attribute is not in the list or if raw names
       *         are not available.
       */
      public String getType (String rawName)
      {
        return getType(getIndex(rawName));
      } 
  
      /**
       * Look up an attribute's value by Namespace name.
       *
       * @param uri The Namespace URI, or the empty String if the
       *        name has no Namespace URI.
       * @param localName The local name of the attribute.
       * @return The attribute value as a string, or null if the
       *         attribute is not in the list.
       */
      public String getValue (String uri, String localName)
      {
        return getValue(getIndex(uri, localName));
      } 
  
      /**
       * Look up an attribute's value by raw XML 1.0 name.
       *
       * @param rawName The raw XML 1.0 name.
       * @return The attribute value as a string, or null if the
       *         attribute is not in the list or if raw names
       *         are not available.
       */
      public String getValue (String rawName)
      {
        return getValue(getIndex(rawName));
      }
      
      //
      // Implement NamedNodeMap
      //
      
      public Node getNamedItem(String name)
      {
        return getChildAttribute(getIndex(name));
      }
  
      /**
       *  Adds a node using its <code>nodeName</code> attribute. If a node with 
       * that name is already present in this map, it is replaced by the new 
       * one.
       * <br> As the <code>nodeName</code> attribute is used to derive the name 
       * which the node must be stored under, multiple nodes of certain types 
       * (those that have a "special" string value) cannot be stored as the 
       * names would clash. This is seen as preferable to allowing nodes to be 
       * aliased.
       * @param arg  A node to store in this map. The node will later be 
       *   accessible using the value of its <code>nodeName</code> attribute.
       * @return  If the new <code>Node</code> replaces an existing node the 
       *   replaced <code>Node</code> is returned, otherwise <code>null</code> 
       *   is returned.
       * @exception DOMException
       *    WRONG_DOCUMENT_ERR: Raised if <code>arg</code> was created from a 
       *   different document than the one that created this map.
       *   <br> NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
       *   <br> INUSE_ATTRIBUTE_ERR: Raised if <code>arg</code> is an 
       *   <code>Attr</code> that is already an attribute of another 
       *   <code>Element</code> object. The DOM user must explicitly clone 
       *   <code>Attr</code> nodes to re-use them in other elements.
       */
      public Node setNamedItem(Node arg)
                               throws DOMException
      {
        setAttribute(((Attr)arg).getName(), ((Attr)arg).getValue());
        return getChildAttribute(getIndex(((Attr)arg).getName()));
      }                                    
  
      /**
       *  Removes a node specified by name. A removed attribute may be known to 
       * have a default value when this map contains the attributes attached to 
       * an element, as returned by the attributes attribute of the 
       * <code>Node</code> interface. If so, an attribute immediately appears 
       * containing the default value as well as the corresponding namespace 
       * URI, local name, and prefix when applicable.
       * @param name  The <code>nodeName</code> of the node to remove.
       * @return  The node removed from this map if a node with such a name 
       *   exists.
       * @exception DOMException
       *    NOT_FOUND_ERR: Raised if there is no node named <code>name</code> 
       *   in this map.
       *   <br> NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
       */
      public Node removeNamedItem(String name)
                                  throws DOMException
      {
        int index = getIndex(name);
        return removeItem(index);
      } 
      
      public Node removeItem(int index)
                                  throws DOMException
      {
        if (index >0)
        {  
          AttrImpl attr = getChildAttribute(index);
          int childCount = m_children.length;
          Child[] newChildren = new Child[childCount-1];
          System.arraycopy(m_children, 0, newChildren, 0, index);
          System.arraycopy(m_children, index+1, newChildren, index, 
childCount-1);
          m_children = newChildren;
          attrsEnd--;  
        
          return attr;  
        }
        else
          return null;
        
      }
  
      /**
       *  Returns the <code>index</code> th item in the map. If 
       * <code>index</code> is greater than or equal to the number of nodes in 
       * this map, this returns <code>null</code> .
       * @param index  Index into this map.
       * @return  The node at the <code>index</code> th position in the map, or 
       *   <code>null</code> if that is not a valid index.
       */
      public Node item(int index)
      {      
        return getChildAttribute(index);             
      } 
      
  
      /**
       *  Retrieves a node specified by local name and namespace URI. HTML-only 
       * DOM implementations do not need to implement this method.
       * @param namespaceURI  The  namespace URI of the node to retrieve.
       * @param localName  The  local name of the node to retrieve.
       * @return  A <code>Node</code> (of any type) with the specified local 
       *   name and namespace URI, or <code>null</code> if they do not identify 
       *   any node in this map.
       * @since DOM Level 2
       */
      public Node getNamedItemNS(String namespaceURI, 
                                 String localName)
      {
        return getChildAttribute(getIndex(namespaceURI, localName));
      }  
  
      /**
       *  Adds a node using its <code>namespaceURI</code> and 
       * <code>localName</code> . If a node with that namespace URI and that 
       * local name is already present in this map, it is replaced by the new 
       * one.
       * <br> HTML-only DOM implementations do not need to implement this 
method.
       * @param arg  A node to store in this map. The node will later be 
       *   accessible using the value of its <code>namespaceURI</code> and 
       *   <code>localName</code> attributes.
       * @return  If the new <code>Node</code> replaces an existing node the 
       *   replaced <code>Node</code> is returned, otherwise <code>null</code> 
       *   is returned.
       * @exception DOMException
       *    WRONG_DOCUMENT_ERR: Raised if <code>arg</code> was created from a 
       *   different document than the one that created this map.
       *   <br> NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
       *   <br> INUSE_ATTRIBUTE_ERR: Raised if <code>arg</code> is an 
       *   <code>Attr</code> that is already an attribute of another 
       *   <code>Element</code> object. The DOM user must explicitly clone 
       *   <code>Attr</code> nodes to re-use them in other elements.
       * @since DOM Level 2
       */
      public Node setNamedItemNS(Node arg)
                                 throws DOMException
      {
        setAttributeNS(((Attr)arg).getNamespaceURI(), ((Attr)arg).getName(), 
((Attr)arg).getValue());
        return getChildAttribute(getIndex(((Attr)arg).getNamespaceURI(), 
((Attr)arg).getName()));
      }                                      
  
      /**
       *  Removes a node specified by local name and namespace URI. A removed 
       * attribute may be known to have a default value when this map contains 
       * the attributes attached to an element, as returned by the attributes 
       * attribute of the <code>Node</code> interface. If so, an attribute 
       * immediately appears containing the default value as well as the 
       * corresponding namespace URI, local name, and prefix when applicable.
       * <br> HTML-only DOM implementations do not need to implement this 
method.
       * @param namespaceURI  The  namespace URI of the node to remove.
       * @param localName  The  local name of the node to remove.
       * @return  The node removed from this map if a node with such a local 
       *   name and namespace URI exists.
       * @exception DOMException
       *    NOT_FOUND_ERR: Raised if there is no node with the specified 
       *   <code>namespaceURI</code> and <code>localName</code> in this map.
       *   <br> NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
       * @since DOM Level 2
       */
      public Node removeNamedItemNS(String namespaceURI, 
                                    String localName)
                                    throws DOMException
      {
        int index = getIndex(namespaceURI, localName);
        return removeItem(index);
      }          
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/ElementImplWithNS.java
  
  Index: ElementImplWithNS.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.xml.sax.Attributes;
  
  public class ElementImplWithNS extends ElementImpl
  {
    private String m_localName;
    private String m_uri;
    
    ElementImplWithNS (String ns, String name)
    {
      super(name);
      int index = name.indexOf(':');
      if (index >0)
        m_localName = name.substring(index+1);
      else
        m_localName = name;
      m_uri = ns;
    }
    
    ElementImplWithNS (String ns, String localName,
                       String name, Attributes atts)
    {
      super(name, atts);
      m_localName = localName;
      m_uri = ns;
    }
    
    /**
     * The namespace URI of this node, or <code>null</code> if it is 
     * unspecified.
      */
    public String       getNamespaceURI()
    {
      return m_uri;
    }
    
    /**
     * The namespace prefix of this node, or <code>null</code> if it is 
     * unspecified.
     * @since DOM Level 2
     */
    public String       getPrefix()
  {
      String rawName = getNodeName();
    int indexOfNSSep = rawName.indexOf(':');
      return (indexOfNSSep >= 0) 
                      ? rawName.substring(0, indexOfNSSep) : null;
    }
  
  /**
     * Returns the local part of the qualified name of this node.
     * <br>For nodes created with a DOM Level 1 method, such as 
     * <code>createElement</code> from the <code>Document</code> interface, 
     * it is <code>null</code>.
     * @since DOM Level 2
     */
    public String       getLocalName()
    {
      return m_localName;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/IndexedDocImpl.java
  
  Index: IndexedDocImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.ProcessingInstruction;
  import org.w3c.dom.CDATASection;
  import org.w3c.dom.Text;
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.Comment;
  import org.w3c.dom.Attr;
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.DocumentType;
  import org.w3c.dom.DOMException;
  
  public class IndexedDocImpl extends DocumentImpl implements IndexedElem
  {
    IndexedDocImpl()
    {
          super();
    }
  
    IndexedDocImpl(DocumentType doctype)
    {
      super(doctype);    
    }
    
    private int m_index;
    
    /** 
     * An integer indicating where this node's children can
     * be found in the indexed nodes list.
     */
    public void setIndex(int anIndex) 
    {
      this.m_index = anIndex;
    }
    
    /** 
     * An integer indicating where this node's children can
     * be found in the indexed nodes list.
     */
    public int getIndex() 
    {
      return m_index;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/IndexedElem.java
  
  Index: IndexedElem.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.xml.sax.Attributes;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.Attr;
  import org.w3c.dom.DOMException;
  
  
  public interface IndexedElem 
    
  {
    
  
    /** 
     * An integer indicating where this node's children can
     * be found in the indexed nodes list.
     */
    public void setIndex(int anIndex);
    
    
    /** 
     * An integer indicating where this node's children can
     * be found in the indexed nodes list.
     */
    public int getIndex();
    
  
  }  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/IndexedElemImpl.java
  
  Index: IndexedElemImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.xml.sax.Attributes;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.Attr;
  import org.w3c.dom.DOMException;
  
  
  public class IndexedElemImpl extends ElementImpl implements IndexedElem
    
  {
    private String m_name;
    private short attrsEnd;
    private int m_index;
    
    IndexedElemImpl (String name)
    {
      super(name);    
    }
  
    IndexedElemImpl (String name, Attributes atts)
    {
      super(name, atts);    
    }
  
    /** 
     * An integer indicating where this node's children can
     * be found in the indexed nodes list.
     */
    public void setIndex(int anIndex) 
    {
      this.m_index = anIndex;
    }
    
    /** 
     * An integer indicating where this node's children can
     * be found in the indexed nodes list.
     */
    public int getIndex() 
    {
      return m_index;
    }
  
  }  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/IndexedElemWithNS.java
  
  Index: IndexedElemWithNS.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.xml.sax.Attributes;
  
  public class IndexedElemWithNS extends ElementImplWithNS implements 
IndexedElem
  {
    private String m_localName;
    private String m_uri;
    private int m_index;
    
    IndexedElemWithNS (String ns, String name)
    {
      super(ns,name);    
    }
    
    IndexedElemWithNS (String ns, String localName,
                       String name, Attributes atts)
    {
      super(ns, localName, name, atts);    
    }
    
    /** 
     * An integer indicating where this node's children can
     * be found in the indexed nodes list.
     */
    public void setIndex(int anIndex) 
    {
      this.m_index = anIndex;
    }
    
    /** 
     * An integer indicating where this node's children can
     * be found in the indexed nodes list.
     */
    public int getIndex() 
    {
      return m_index;
    }
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/IndexedLocPathIterator.java
  
  Index: IndexedLocPathIterator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.stree;
  
  // Java library imports
  import java.util.Vector;
  
  // DOM imports
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  
  // Xalan imports
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.OpCodes;
  import org.apache.xalan.xpath.PsuedoNames;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.LocPathIterator;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This class extends NodeSet, which implements NodeIterator, 
   * and fetches nodes one at a time in document order based on a XPath
   * <a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a>.
   * As each node is iterated via nextNode(), the node is also stored 
   * in the NodeVector, so that previousNode() can easily be done, except in 
   * the case where the IndexedLocPathIterator is "owned" by a 
UnionPathIterator, 
   * in which case the UnionPathIterator will cache the nodes.
   */
  public class IndexedLocPathIterator extends LocPathIterator
  {
    /**
     * Create a IndexedLocPathIterator object.
     */
    public IndexedLocPathIterator(XPath xpath, XPathContext execContext, 
                           Node context, int opPos,
                           StreeLocator locator)
    {
      super(xpath, execContext, context, opPos, locator);
    }  
  }
  
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/IndexedUnionPathIterator.java
  
  Index: IndexedUnionPathIterator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.stree;
  
  // DOM Imports
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  
  // Xalan Imports
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XPathContext;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This class extends NodeSet, which implements NodeIterator, 
   * and fetches nodes one at a time in document order based on a XPath
   * <a href="http://www.w3.org/TR/xpath#NT-UnionExpr";>UnionExpr</a>.
   * As each node is iterated via nextNode(), the node is also stored 
   * in the NodeVector, so that previousNode() can easily be done.
   */
  public class IndexedUnionPathIterator extends NodeSet
  {
    /**
     * Package-private constructor, which takes the 
     * same arguments as XLocator's union() function, plus the 
     * locator reference.
     */
    IndexedUnionPathIterator(XPath xpath, XPathContext execContext, 
                      Node context, int opPos,
                      StreeLocator locator)
    {
      super();
      
      this.m_xpath = xpath;
      this.m_execContext = execContext;
      this.m_context = context;
      this.m_unionOpPos = opPos;
      this.m_locator = locator;
      init();
    }
    
    /**
     * Initialize the location path iterators.
     */
    protected void init()
    {
    }
  
    /**
     *  Returns the next node in the set and advances the position of the 
     * iterator in the set. After a NodeIterator is created, the first call 
     * to nextNode() returns the first node in the set.
     * @return  The next <code>Node</code> in the set being iterated over, or
     *   <code>null</code> if there are no more members in that set.
     * @exception DOMException
     *    INVALID_STATE_ERR: Raised if this method is called after the
     *   <code>detach</code> method was invoked.
     */
    public Node nextNode()
      throws DOMException
    {
      return null;
    }
    
    /**
     * The XPath that contains the union expression.
     */
    protected XPath m_xpath;
    
    /**
     * The execution context for the expression.
     */
    protected XPathContext m_execContext;
    
    /**
     * The node context for the expression.
     */
    protected Node m_context;
    
    /**
     * The op code position of the union path.
     */
    protected int m_unionOpPos;
    
    /**
     * Reference to the FastNodeLocator that created 
     * this instance.
     */
    protected StreeLocator m_locator;
    
    /**
     * The location path iterators, one for each 
     * <a href="http://www.w3.org/TR/xpath#NT-LocationPath";>location 
     * path</a> contained in the union expression.
     */
    protected IndexedLocPathIterator[] m_iterators;
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/LevelIndexIterator.java
  
  Index: LevelIndexIterator.java
  ===================================================================
  package org.apache.xalan.stree;
  
  // DOM imports
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  
  /**
   * The responsibility of this class is to hide the internal workings 
   * of the LevelIndexer from the LocPathIterator, and to return nodes 
   * that:
   * <ol>
   * <li>Belongs to the given parent;</li>
   * <li>match the given node type;</li>
   * <li>match the given namespace;</li>
   * <li>match the given local name;</li>
   * </ol>
   */
  public class LevelIndexIterator
  {
    /**
     */
    public LevelIndexIterator(Node parent, int type, String url, String name)
    {
    }
    
    /**
     *  Returns the next node in the set and advances the position of the 
     * iterator in the set. After a NodeIterator is created, the first call 
     * to nextNode() returns the first node in the set.
     * @return  The next <code>Node</code> in the set being iterated over, or
     *   <code>null</code> if there are no more members in that set.
     * @exception DOMException
     *    INVALID_STATE_ERR: Raised if this method is called after the
     *   <code>detach</code> method was invoked.
     */
    public Node nextNode()
      throws DOMException
    {
      return null;
    }  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/LevelIndexer.java
  
  Index: LevelIndexer.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.stree;
  
  import org.w3c.dom.*;
  import java.util.*;
  import java.io.*;
  import java.lang.Object;
  import org.apache.xalan.utils.IntVector;
  
  
  /**
   * <meta name="usage" content="general"/>
   * The XPath class represents the semantic parse tree of the XPath pattern.
   * It is the representation of the grammar which filters out
   * the choice for replacement order of the production rules.
   * In order to conserve memory and reduce object creation, the
   * tree is represented as an array of integers:
   *    [op code][length][...]
   * where strings are represented within the array as
   * indexes into the token tree.
   */
  public class LevelIndexer
  {
    int lastUsed;
    int m_subtype;
    int m_defaultSize = 3; // this is the default value.
  
    // change this to be new object extending from hashtable...
    //Hashtable
    MultiKeyTable m_elemTypes = new MultiKeyTable();  //array of element types
  
  
    /* Array of levels in the tree.
     * Each element of this array is a nodesList element.
     */
    Object[] m_levelArray;    // array of levels in the tree. These are used
                                              // to build the elemPostings 
table.
  
    /**
     * Create a LevelIndexer object.
     */
    public LevelIndexer()
    {
          m_levelArray = new Object[10];
    }   
  
  
    /**
     * <meta name="usage" content="internal"/>
     * Insert a node in the nodesList by level, by parent and by type.
     */
    public void insertNode(Child child)
    {
      boolean updateParent = true;
      // first assign a subtype to the element and add it to the
      // m_elemTypes table.
      int type = addToTable(child);
  
          int uid = child.getUid();
      int level = child.getLevel();                  
  
      // Nothing there yet
      if (m_levelArray[level]== null)
      {
        Object[] nodesList = new Object[m_defaultSize];
        m_levelArray[level] = nodesList;
  
        nodesList[0] = child;
        ((IndexedElem)child.getParentNode()).setIndex(0);       
      }
      // Add to the existing list
      else
      {
        Object[] nodesList = (Object[])m_levelArray[level];
            int structIndex = 0;
        while (structIndex < nodesList.length
               && (nodesList[structIndex]!= null) )
        {
          structIndex++; 
            }   
            int lastUsed = structIndex-1;
        // TODO: cleanup
        // Need to reallocate?? 2 is the max slots we could
        // need to add plus 1 to indicate end...
        if (nodesList.length < lastUsed + 3)
        {                           
          nodesList  = allocateNewList(nodesList);
          m_levelArray[level] = nodesList;
        }
        
        structIndex = 0;
        while (structIndex < nodesList.length
               && (nodesList[structIndex]!= null))
        {
          int next = structIndex + 1; 
          Child node = (Child)nodesList[structIndex];
          if(child.getParentNode().equals(node.getParentNode()))
          {
            // There is already at least one node with this parent at this 
level        
            // This parent already has a pointer to its children.
            updateParent = false;
            if(getType(node) == type)
            {
              // This parent already has children of this type.
              // Add this child to the end of the list for this type.
              if (nodesList[next] != null)
              {
                // Slide down one
                int i;
                for (i = lastUsed; i >= next; i--)
                {       
                  if (getType((Child)nodesList[i]) != type)
                    nodesList[i+1] = nodesList[i];
                }
                nodesList[i] = child;           
                
              }
              else
              {
                nodesList[next] = child;              
              }
              
              break;
            }
            structIndex = structIndex + 1;
          }
          // Keep looking for this parent and this type
          else
          {
            structIndex = structIndex + 1; 
          }
        }// end while
  
        // First node for this parent of this type at this level
            if (nodesList[structIndex] == null)
            {   
                    nodesList[structIndex] = child;
          if (updateParent)
                      
((IndexedElem)child.getParentNode()).setIndex(structIndex);
            }   
      } //end else add to existing list
  
    }
  
  
    /**
     * <meta name="usage" content="internal"/>
     * Get a list of nodes in the level array by level and by type.
     */
    public Object[] getNodesList(int level)
    {
      if (level > m_levelArray.length - 1 || m_levelArray[level]== null)
          return null;
      else
      {
        return (Object[])m_levelArray[level];
      }
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get a list of nodes in the level array by level and by type.
     */
    public Object[] allocateNewList(Object[]nodesList)
    {
      int len = nodesList.length;
      Object[]newlist = new Object[len + m_defaultSize];
      System.arraycopy(nodesList, 0, newlist, 0, len);
      for (int i=len; i< len + m_defaultSize; i++)
        newlist[i] = null;
      return newlist;    
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Get index pointing to nodes of a certain type in the nodeslist.
     */
    public int getIndexForType(Node child, int type, Object[]nodesList )
    {
      int structIndex = 0;
      if (type == TYPEANY)
        return structIndex;
      
      while (structIndex < nodesList.length
             &&  nodesList[structIndex] != null)
      {
        int next = structIndex + 1; 
        Child node = (Child)nodesList[structIndex];
        if (child.getParentNode().equals(node.getParentNode())) 
        {
          if(getType(node) == type)
          {
            return structIndex;
          }
          structIndex = structIndex + 1;
        }
        // Keep looking for this type
        else
        {
          structIndex = structIndex + 1; 
        }
      }
      return -1;    // not found
    }
  
  
    /**
     * <meta name="usage" content="internal"/>
     * Add a node to the types table. Each entry is a (node, type) pair.
     * The type is an assigned integer value. Attribute nodes
     * will have "@::" prepended to the element name. The name
     * is a combination of the URI and the actual element name
     * seperated by a double colon "::"
     * Note that m_subtype is a global variable that gets incremented
     * for the next time it is used.
     * @return return the element subtype
     */
    public int addToTable(Child child)
    {
      String uri = child.getNamespaceURI();
      String name = child.getNodeName(); 
      String prepend = null;
      // Keep track of attribute nodes
      if (child.getNodeType()== Node.ATTRIBUTE_NODE)
            prepend = "@";      
        
      // Only add new types to the table    
      int type = m_elemTypes.get(name, uri, prepend);
      if (type < 0)
      {
        type = m_subtype;
        m_elemTypes.put(name, uri, prepend, type);
        m_subtype++;
      }
      return type;
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Get type.
     */
    public short getType(String name, String namespace, String prepend)
    {
      int type = m_elemTypes.get(name, namespace, prepend);
      return  (new Integer(type).shortValue());
      
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get type.
     */
    public short getType(Node node)
    {
      String uri = node.getNamespaceURI();
      String name = node.getNodeName(); 
      String prepend = null;
      // set up for attribute nodes
      if (node.getNodeType()== Node.ATTRIBUTE_NODE)
        prepend = "@";                   
      return getType(name, uri, prepend);
    }
  
    /**
     * The value to use for "//" and the like, where the level is
     * to the bottom of the tree, but we don't know how many levels
     * the tree is.
     */
    static final int MAXDEPTH = 2000;
    
    static final int TYPEANY = 2000;
    
  
  /**
   * Implement a structure extending from Hashtable that is keyed
   * on multiple keys.
   */
    protected class MultiKeyTable //extends Hashtable
    {
      private MultiKeyTable()
      {
        super();
      }
      
      private Hashtable m_nameTable;
      private Hashtable m_uriTable;
      
      public void put(String name, String namespace, String prepend, int value)
      {
        IntVector nameList, uriList;
        
        if (prepend != null)
          name = prepend + "::" + name;
        
        if (name != null)
        {
          if (m_nameTable == null)
            m_nameTable = new Hashtable();
          nameList = (IntVector)m_nameTable.get(name);
          if (nameList == null)
            nameList = new IntVector();
          nameList.addElement(value);
          m_nameTable.put(name, nameList);
        }
        
        if (namespace == null)
          namespace = "";      
        if (m_uriTable == null)
          m_uriTable = new Hashtable();
        uriList =(IntVector) m_uriTable.get(namespace);      
        if (uriList == null)
          uriList = new IntVector();
        uriList.addElement(value);
        m_uriTable.put(namespace, uriList);
                   
      }
  
      public int get(String name, String namespace, String prepend)     
      {
        IntVector nameList, uriList = null;
        if (m_nameTable == null)
          return -1;
        
        if (prepend != null)
          name = prepend + "::" + name;
        
        nameList = (IntVector)m_nameTable.get(name);      
        if (nameList == null)
          return -1;
        
        if (namespace == null)
          namespace = "";
        if ( m_uriTable != null)
        {  
          uriList = (IntVector)m_uriTable.get(namespace);
          if (uriList == null)
            return -1;
        }       
        
        // Return the element that is common to both lists 
        for (int i=0; i< nameList.size(); i++)
        {
          for(int j=0; j< uriList.size(); j++)
          {
            if (nameList.elementAt(i) == uriList.elementAt(j))
              return nameList.elementAt(i);
          }
        }
        // Not found.
        return -1;        
       
      }         
    }  
  
  
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/NotationImpl.java
  
  Index: NotationImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  
  public class NotationImpl
  {
    private String m_name;
  
    /** Public identifier. */
    private String m_publicId;
  
    /** System identifier. */
    private String m_systemId;
  
    /** 
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() 
    {
      return Node.NOTATION_NODE;
    }
    
    /**
     * The Public Identifier for this Notation. If no public identifier
     * was specified, this will be null.  
     */
    public String getPublicId() 
    {
      return m_publicId;
  
    } // getPublicId():String
  
    /**
     * The System Identifier for this Notation. If no system identifier
     * was specified, this will be null.  
     */
    public String getSystemId() 
    {
      return m_systemId;
    } // getSystemId():String
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return m_name;
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/stree/Parent.java
  
  Index: Parent.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  import org.w3c.dom.Element;
  
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.templates.StylesheetRoot;
  import org.apache.xalan.templates.WhiteSpaceInfo;
  
  import org.xml.sax.SAXException;
  
  public class Parent extends Child
  {
    /**
     * The list of children.  For space conservation reasons, 
     * this list is resized everytime a child is added, and is 
     * always exactly the size of the child count.  This is 
     * certainly subject to review, but I thought I'd give it 
     * a try and see how it works.  The alternative is to 
     * keep an extra int around which tells us the first free 
     * member in the list, etc. 
     */
    protected Child[] m_children;   
    
    /**
     * Get the number of children this node currently contains.
     * Note that this will only return the number of children 
     * added so far.  If the isComplete property is false, 
     * it is likely that more children will be added.
     */
    public int getChildCount()
    {
      return (null == m_children) ? 0 : m_children.length;
    }
    
    /**
     *  This is a convenience method to allow easy determination of whether a 
     * node has any children.
     * @return  <code>true</code> if the node has any children, 
     *   <code>false</code> if the node has no children.
     */
    public boolean      hasChildNodes()
  {
      return (getChildCount() == 0) ? false : true;
  }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the position of the child of an element in the document.
     * Note that this is assuming an index starting at 1
     */
    public int getChildUID(int pos)
    {        
      Child child = getChild(pos);
      return (null != child) ? child.getUid() : -1;
    }
    
    /**
     * Get the nth child.
     * @param i the index of the child.
     * @exception ArrayIndexOutOfBoundsException if the index is out of bounds.
     * @exception NullPointerException if there are no children.
     */
    public Child getChild(int i)
      throws ArrayIndexOutOfBoundsException, NullPointerException
    {
      // wait?
      return ((null != m_children) && (i >= 0) && i < m_children.length) ?
             m_children[i] : null;
    }
    
    /**
     * The first child of this node. If there is no such node, this returns 
     * <code>null</code>.
     */
    public Node         getFirstChild()
    {
      if (getChildCount() == 0)
        return null;
      else        
      return getChild(0);
    }
  
    /**
     * The last child of this node. If there is no such node, this returns 
     * <code>null</code>.
     */
    public Node         getLastChild()
    {
      try
      {
      return getChild(getChildCount()-1);
      }
      catch(Exception e)
      {
        return null;
      }  
    }
    
    /**
     * Append a child to the child list.
     * @param newChild Must be a org.apache.xalan.stree.Child.
     * @exception ClassCastException if the newChild isn't a 
org.apache.xalan.stree.Child.
     */
    public Node appendChild(Node newChild)
      throws DOMException
    {
      int childCount;
      if(null == m_children)
      {
        m_children = new Child[1];
        childCount = 0;
      }
      else
      {
        childCount = m_children.length;
        Child[] newChildren = new Child[childCount+1];
        System.arraycopy(m_children, 0, newChildren, 0, childCount);
        // Child prevChild = m_children[childCount-1];
        m_children = newChildren;
      }
      
      Child child = (Child)newChild;
      m_children[childCount] = child;
      child.SetChildPosition(childCount);
  
      DocumentImpl doc = (DocumentImpl)this.getOwnerDocument();
      doc.incrementDocOrderCount();
      child.setUid(doc.getDocOrderCount());
      child.setParent(this);
      child.setLevel((short)(getLevel() + 1));
          // getDocumentImpl().getLevelIndexer().insertNode(child);
      
      if(Node.ELEMENT_NODE == child.getNodeType())
      {
        SourceTreeHandler sh = doc.getSourceTreeHandler();
        TransformerImpl transformer = sh.getTransformer();
        if(null != transformer)
        {
          StylesheetRoot stylesheet= transformer.getStylesheet();
          try
          {
            ElementImpl elem = (ElementImpl)child;
            WhiteSpaceInfo info 
              = stylesheet.getWhiteSpaceInfo(transformer.getXPathContext(), 
elem);
            boolean shouldStrip;
            if(null == info)
            {
              shouldStrip = sh.getShouldStripWhitespace();
            }
            else
            {
              shouldStrip = info.getShouldStripSpace();
            }
            sh.setShouldStripWhitespace(shouldStrip);
          }
          catch(SAXException se)
          {
            // TODO: Diagnostics
          }
        }
  
      }
      
      return newChild;
    }  
  
    
    /**
     * Flag that tells if this node is complete.
     */
    private boolean m_isComplete = false;
    
    /**
     * Return if this node has had all it's children added, i.e. 
     * if a endElement event has occured.
     */
    public boolean isComplete()
    {
      return m_isComplete;
    }
  
    /**
     * Set that this node's child list is complete, i.e. 
     * an endElement event has occured.
     */
    public void setComplete(boolean isComplete)
    {
      m_isComplete = isComplete;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/ProcessingInstructionImpl.java
  
  Index: ProcessingInstructionImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.ProcessingInstruction;
  
  public class ProcessingInstructionImpl extends Child 
    implements ProcessingInstruction
  {
    private String m_name;
    private String m_data;
    
    /**
     * Implement the processingInstruction event.
     */
    ProcessingInstructionImpl(String target, String data)
    {
      m_name = target;
      m_data = data;
    }
    
    /** Get the PI name. */
    public String getNodeName()
    {
      return m_name;
    }
    
    /**
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() 
    {
      return Node.PROCESSING_INSTRUCTION_NODE;
    }
    
    /**
     * A PI's "target" states what processor channel the PI's data
     * should be directed to. It is defined differently in HTML and XML.
     * <p>
     * In XML, a PI's "target" is the first (whitespace-delimited) token
     * following the "<?" token that begins the PI.
     * <p>
     * In HTML, target is always null.
     * <p>
     * Note that getNodeName is aliased to getTarget.
     */
    public String getTarget() 
    {
      return m_name;
    } // getTarget():String
  
    /**
     * The content of this processing instruction. This is from the first non 
     * white space character after the target to the character immediately 
     * preceding the <code>?&gt;</code>.
     * @exception DOMException
     *   NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
     */
    public String       getData()
    {
      return m_data;
    }
    
    public String getNodeValue() 
    {
      return m_data;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/SourceTreeHandler.java
  
  Index: SourceTreeHandler.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.xml.sax.ContentHandler;
  import org.apache.xalan.utils.DOMBuilder;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.templates.StylesheetRoot;
  import org.apache.xalan.templates.WhiteSpaceInfo;
  import org.w3c.dom.Document;
  import org.xml.sax.Attributes;
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.ext.LexicalHandler;
  import org.xml.sax.Locator;
  import org.xml.sax.SAXException;
  import org.xml.sax.ContentHandler;
  import trax.Transformer;
  
  /**
   * This class handles SAX2 parse events to create a source 
   * tree for transformation.
   */
  public class SourceTreeHandler implements ContentHandler, LexicalHandler
  {
    /**
     * Create a SourceTreeHandler that will start a transformation as 
     * soon as a startDocument occurs.
     */
    public SourceTreeHandler(TransformerImpl transformer)
    {
      m_transformer = transformer;
      XPathContext xctxt = ((TransformerImpl)transformer).getXPathContext();
      xctxt.setDOMHelper(new StreeDOMHelper());
    }
  
    /**
     * Create a SourceTreeHandler.
     */
    public SourceTreeHandler()
    {
    }
    
    private TransformerImpl m_transformer;
    public TransformerImpl getTransformer()
    {
      return m_transformer;
    }
  
    private DOMBuilder m_sourceTreeHandler;
    
    private Document m_root; // Normally a Document
    
    /**
     * Get the root document of tree that is being or will be created.
     */
    public Node getRoot()
    {
      return m_root;
    }
  
    /**
     * Set the root document of tree will be created.
     */
    public void setRoot(Document root)
    {
      m_root = root;    
    }
  
    /**
     * Implement the setDocumentLocator event.
     */
    public void setDocumentLocator (Locator locator)
    {
    }
    
    private boolean m_useMultiThreading = false;
    
    private boolean indexedLookup = false;      // for now   
    
    /**
     * Implement the startDocument event.
     */
    public void startDocument ()
      throws SAXException
    {    
      if(null == m_root)
      {
        if (indexedLookup)
          m_root = new IndexedDocImpl();
        else
          m_root = new DocumentImpl();      
      }
      ((DocumentImpl)m_root).setSourceTreeHandler(this);
      ((DocumentImpl)m_root).setUid(1);
      ((DocumentImpl)m_root).setLevel(new Integer(1).shortValue());
      m_sourceTreeHandler = new DOMBuilder(m_root);
      setShouldStripWhitespace(false);
      
      if(m_useMultiThreading && (null != m_transformer))
      {
        m_transformer.transformNode(m_root);
      }
  
      m_sourceTreeHandler.startDocument();
    }
    
    
  
    /**
     * Implement the endDocument event.
     */
    public void endDocument ()
      throws SAXException
    {
      m_sourceTreeHandler.endDocument();
      
      if(!m_useMultiThreading && (null != m_transformer))
      {
        m_transformer.transformNode(m_root);
      }
    }
  
    /**
     * Implement the startElement event.
     */
    public void startElement (String ns, String localName,
                              String name, Attributes atts)
      throws SAXException
    {
      m_sourceTreeHandler.startElement(ns, localName, name, atts);
    }
  
    /**
     * Implement the endElement event.
     */
    public void endElement (String ns, String localName,
                            String name)
      throws SAXException
    {
      m_sourceTreeHandler.endElement(ns, localName, name);
    }
  
    private boolean m_isCData = false;
    
    /**
     * Report the start of a CDATA section.
     *
     * <p>The contents of the CDATA section will be reported through
     * the regular [EMAIL PROTECTED] org.xml.sax.ContentHandler#characters
     * characters} event.</p>
     *
     * @exception SAXException The application may raise an exception.
     * @see #endCDATA
     */
    public void startCDATA ()
      throws SAXException
    {
      m_isCData = true;
    }
    
    /**
     * Report the end of a CDATA section.
     *
     * @exception SAXException The application may raise an exception.
     * @see #startCDATA
     */
    public void endCDATA ()
      throws SAXException
    {
      m_isCData = false;
    }
    
    /**
     * Tell if the given character array is whitespace.
     */
    private boolean isWhitespaceArray(char ch[], int start, int length)
    {
      int n = start+length;
      for(int i = start; i < n; i++)
      {
        if(!Character.isWhitespace(ch[i]))
           return false;
      }
      return true;
    }
  
    /**
     * Implement the characters event.
     */
    public void characters (char ch[], int start, int length)
      throws SAXException
    {
      if(isWhitespaceArray(ch, start, length) && getShouldStripWhitespace())
        return;
      
      if(m_isCData)
        m_sourceTreeHandler.cdata(ch, start, length);
      else
        m_sourceTreeHandler.characters(ch, start, length);
    }
  
    /**
     * Implement the characters event.
     */
    public void charactersRaw (char ch[], int start, int length)
      throws SAXException
    {
      m_sourceTreeHandler.charactersRaw(ch, start, length);
    }
  
    /**
     * Implement the ignorableWhitespace event.
     */
    public void ignorableWhitespace (char ch[], int start, int length)
      throws SAXException
    {
      m_sourceTreeHandler.charactersRaw(ch, start, length);
    }
  
    /**
     * Implement the processingInstruction event.
     */
    public void processingInstruction (String target, String data)
      throws SAXException
    {
      m_sourceTreeHandler.processingInstruction(target, data);
    }
  
    /**
     * Report an XML comment anywhere in the document.
     *
     * <p>This callback will be used for comments inside or outside the
     * document element, including comments in the external DTD
     * subset (if read).</p>
     *
     * @param ch An array holding the characters in the comment.
     * @param start The starting position in the array.
     * @param length The number of characters to use from the array.
     * @exception SAXException The application may raise an exception.
     */
    public void comment (char ch[], int start, int length)
      throws SAXException
    {
      m_sourceTreeHandler.comment(ch, start, length);
    }
    
    /**
     * Report the beginning of an entity.
     *
     * <p>The start and end of the document entity are not reported.
     * The start and end of the external DTD subset are reported
     * using the pseudo-name "[dtd]".  All other events must be
     * properly nested within start/end entity events.</p>
     *
     * <p>Note that skipped entities will be reported through the
     * [EMAIL PROTECTED] org.xml.sax.ContentHandler#skippedEntity skippedEntity}
     * event, which is part of the ContentHandler interface.</p>
     *
     * @param name The name of the entity.  If it is a parameter
     *        entity, the name will begin with '%'.
     * @exception SAXException The application may raise an exception.
     * @see #endEntity
     * @see org.xml.sax.ext.DeclHandler#internalEntityDecl
     * @see org.xml.sax.ext.DeclHandler#externalEntityDecl
     */
    public void startEntity (String name)
      throws SAXException
    {
      m_sourceTreeHandler.startEntity(name);
    }
  
    /**
     * Report the end of an entity.
     *
     * @param name The name of the entity that is ending.
     * @exception SAXException The application may raise an exception.
     * @see #startEntity
     */
    public void endEntity (String name)
      throws SAXException
    {
      m_sourceTreeHandler.endEntity(name);
    }
    
    /**
     * Report the start of DTD declarations, if any.
     *
     * <p>Any declarations are assumed to be in the internal subset
     * unless otherwise indicated by a [EMAIL PROTECTED] #startEntity 
startEntity}
     * event.</p>
     *
     * @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.
     * @exception SAXException The application may raise an
     *            exception.
     * @see #endDTD
     * @see #startEntity
     */
    public void startDTD (String name, String publicId,
                          String systemId)
      throws SAXException
    {
    }
  
  
    /**
     * Report the end of DTD declarations.
     *
     * @exception SAXException The application may raise an exception.
     * @see #startDTD
     */
    public void endDTD ()
      throws SAXException
    {
    }
  
    /**
     * Begin the scope of a prefix-URI Namespace mapping.
     *
     * <p>The information from this event is not necessary for
     * normal Namespace processing: the SAX XML reader will 
     * automatically replace prefixes for element and attribute
     * names when the http://xml.org/sax/features/namespaces
     * feature is true (the default).</p>
     *
     * <p>There are cases, however, when applications need to
     * use prefixes in character data or in attribute values,
     * where they cannot safely be expanded automatically; the
     * start/endPrefixMapping event supplies the information
     * to the application to expand prefixes in those contexts
     * itself, if necessary.</p>
     *
     * <p>Note that start/endPrefixMapping events are not
     * guaranteed to be properly nested relative to each-other:
     * all startPrefixMapping events will occur before the
     * corresponding startElement event, and all endPrefixMapping
     * events will occur after the corresponding endElement event,
     * but their order is not guaranteed.</p>
     *
     * @param prefix The Namespace prefix being declared.
     * @param uri The Namespace URI the prefix is mapped to.
     * @exception org.xml.sax.SAXException The client may throw
     *            an exception during processing.
     * @see #endPrefixMapping
     * @see #startElement
     */
    public void startPrefixMapping (String prefix, String uri)
      throws SAXException
    {
      // System.out.println("DOMBuilder.startPrefixMapping("+prefix+", 
"+uri+");");
    }
  
    /**
     * End the scope of a prefix-URI mapping.
     *
     * <p>See startPrefixMapping for details.  This event will
     * always occur after the corresponding endElement event,
     * but the order of endPrefixMapping events is not otherwise
     * guaranteed.</p>
     *
     * @param prefix The prefix that was being mapping.
     * @exception org.xml.sax.SAXException The client may throw
     *            an exception during processing.
     * @see #startPrefixMapping
     * @see #endElement
     */
    public void endPrefixMapping (String prefix)
      throws SAXException
    {
    }
    
    /**
     * Receive notification of a skipped entity.
     *
     * <p>The Parser will invoke this method once for each entity
     * skipped.  Non-validating processors may skip entities if they
     * have not seen the declarations (because, for example, the
     * entity was declared in an external DTD subset).  All processors
     * may skip external entities, depending on the values of the
     * http://xml.org/sax/features/external-general-entities and the
     * http://xml.org/sax/features/external-parameter-entities
     * properties.</p>
     *
     * @param name The name of the skipped entity.  If it is a 
     *        parameter entity, the name will begin with '%'.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void skippedEntity (String name)
      throws SAXException
    {
    }
    
    private boolean m_shouldStripWhitespace = false;
    
    boolean getShouldStripWhitespace()
    {
      return m_shouldStripWhitespace;
    }
    
    void setShouldStripWhitespace(boolean shouldStrip)
    {
      m_shouldStripWhitespace = shouldStrip;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/StreeDOMHelper.java
  
  Index: StreeDOMHelper.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.apache.xalan.xpath.DOM2Helper;
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  
  public class StreeDOMHelper extends DOM2Helper
  {
    /**
     * Create an empty DOM Document.  Mainly used for RTFs.
     */
    public Document createDocument()
    {
      return new DocumentImpl();
    }
  
    /**
     * Figure out if node2 should be placed after node1 when 
     * placing nodes in a list that is to be sorted in 
     * document order.
     * NOTE: Make sure this does the right thing with attribute nodes!!!
     * @return true if node2 should be placed 
     * after node1, and false if node2 should be placed 
     * before node1.
     */
    public boolean isNodeAfter(Node node1, Node node2)
    {
      // Assume first that the nodes are DTM nodes, since discovering node 
      // order is massivly faster for the DTM.
      try
      {
        int index1 = ((Child)node1).getUid();
        int index2 = ((Child)node2).getUid();
        return index1 <= index2;
      }
      catch(ClassCastException cce)
      {
        // isNodeAfter will return true if node is after countedNode 
        // in document order. isDOMNodeAfter is sloooow (relativly).
        return super.isNodeAfter(node1, node2);
      }
    }   
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the depth level of this node in the tree.
     */
    public short getLevel(Node node1)
    {
      return ((Child)node1).getLevel();
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/stree/StreeLocator.java
  
  Index: StreeLocator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.stree;
  
  import java.util.*;
  import java.io.*;
  import org.w3c.dom.*;
  
  // XPath imports
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XLocator;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XNodeSet;
  import org.apache.xalan.xpath.XPathFactory;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.OpCodes;
  
  /**
   * <meta name="usage" content="advanced"/>
   * SimpleNodeLocator implements a search of one or more DOM trees.
   * By using the connect function as an extension, the user may 
   * specify a directory and a filter specification for XML files 
   * that will be searched.
   * This is a singleton class.
   */
  public class StreeLocator extends SimpleNodeLocator
  {  
    /**
     * Create a StreeLocator object.
     */
    public StreeLocator()
    {
      super();
    }
    
    /**
     * The singleton instance of this class.
     */
    private static StreeLocator m_locater = null;
     
    /**
     * The the default locator.
     */
    public static XLocator getDefaultLocator()
    {
      m_locater = (null == m_locater) ? new StreeLocator() : m_locater;
      return m_locater;
    }
    
    /**
     * Execute the proprietary connect() function, which returns an 
     * instance of XLocator.  When the XPath object sees a return type 
     * of XLocator, it will call the locationPath function that passes 
     * in the connectArgs.  The opPos and args params are not used 
     * by this function.  This really is just a factory function 
     * for the XLocator instance, but this fact is hidden from the 
     * user.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param args The function args.
     * @returns A node set of Document nodes.
     */
    public static XLocator query(String path, String fileSpec) 
    {    
      m_locater = (null == m_locater) ? new StreeLocator() : m_locater;
      return m_locater;
    }
    
    /**
     * (Same as query for the moment).
     * @param opPos The current position in the xpath.m_opMap array.
     * @param args The function args.
     * @returns A node set of Document nodes.
     */
    public static XLocator connect(String path, String fileSpec) 
    {    
      m_locater = (null == m_locater) ? new StreeLocator() : m_locater;
      return m_locater;
    }
      
  
    /**
     * Computes the union of its operands which must be node-sets.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns the union of node-set operands, or an empty set if 
     * callback methods are used.
     */
    public XNodeSet union(XPath xpath, XPathContext execContext, 
                          Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      return new XNodeSet(new IndexedUnionPathIterator(xpath, execContext, 
                                   context, opPos, this));
    } 
    
    /**
     * Execute a location path.  Normally, this method simply 
     * moves past the OP_LOCATIONPATH and it's length member, 
     * and calls the Step function, which will recursivly process 
     * the rest of the LocationPath, and then wraps the NodeList result
     * in an XNodeSet object.
     * @param xpath The xpath that is executing.
     * @param xctxt The execution context.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param callback Interface that implements the processLocatedNode method.
     * @param callbackInfo Object that will be passed to the processLocatedNode 
method.
     * @returns the result of the query in an XNodeSet object.
     */
    public XNodeSet locationPath(XPath xpath, XPathContext xctxt, 
                                 Node context, int opPos) 
      throws org.xml.sax.SAXException
    {    
      return new XNodeSet(new IndexedLocPathIterator(xpath, xctxt, 
                                   context, opPos, this));
    }
    
    
    /**
     * Create an XPathFactory for this XLocator.
     */
    public static XPathFactory factory() 
    {
      return new StreeLocatorFactory();
    }
  
  }
  
  /**
   * Override the createXLocatorHandler method.
   */
  class FNLDOMXPath extends XPath
  {
    public FNLDOMXPath()
    {
      super();
    }
    
    /**
     * getXLocatorHandler.
     */
    public XLocator createXLocatorHandler(XPath xpath)
    {
      return new StreeLocator();
    }
  }
  
  /**
   * Implement an XPath factory.
   */
  class StreeLocatorFactory implements XPathFactory
  {
    public XPath create()
    {
      return new FNLDOMXPath();
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/stree/TextImpl.java
  
  Index: TextImpl.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Text;
  
  public class TextImpl extends Child implements Text
  {
    private String m_data;
   
    public TextImpl (String data)
    {
      m_data = data;
    }
  
    public TextImpl (char ch[], int start, int length)
    {
      m_data = new String(ch, start, start+length);
    }
    
    /** 
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() 
    {
      return Node.TEXT_NODE;
    }
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return "#text";
    }
    
    /**
     * Retrieve character data currently stored in this node.
     * 
     * @throws DOMExcpetion(DOMSTRING_SIZE_ERR) In some implementations,
     * the stored data may exceed the permitted length of strings. If so,
     * getData() will throw this DOMException advising the user to
     * instead retrieve the data in chunks via the substring() operation.  
     */
    public String getData() 
    {
      return m_data;
    }
  
    /** 
     * Report number of characters currently stored in this node's
     * data. It may be 0, meaning that the value is an empty string. 
     */
    public int getLength() 
    {   
      return m_data.length();
    }  
    
    public String getNodeValue() 
    {
      return m_data;
    } // getNodeValue():String
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/stree/WhiteSpace.java
  
  Index: WhiteSpace.java
  ===================================================================
  package org.apache.xalan.stree;
  
  import org.w3c.dom.Node;
  
  /**
   * Right now this is the same as TextImpl.  Not sure what I 
   * want to do with this, but it certainly seems like there 
   * should be some way to optimize the storage of whitespace 
   * nodes.
   */
  public class WhiteSpace extends Child
  {
    String m_data;
    
    public WhiteSpace (char ch[], int start, int length)
    {
      m_data = new String(ch, start, start+length);
    }
    
    /** 
     * A short integer indicating what type of node this is. The named
     * constants for this value are defined in the org.w3c.dom.Node interface.
     */
    public short getNodeType() 
    {
      return Node.TEXT_NODE;
    }
  
    /** Returns the node name. */
    public String getNodeName() 
    {
      return "#text";
    }
    
    /**
     * Retrieve character data currently stored in this node.
     * 
     * @throws DOMExcpetion(DOMSTRING_SIZE_ERR) In some implementations,
     * the stored data may exceed the permitted length of strings. If so,
     * getData() will throw this DOMException advising the user to
     * instead retrieve the data in chunks via the substring() operation.  
     */
    public String getData() 
    {
      return m_data;
    }
  
    /** 
     * Report number of characters currently stored in this node's
     * data. It may be 0, meaning that the value is an empty string. 
     */
    public int getLength() 
    {   
      return m_data.length();
    }  
    
    public String getNodeValue() 
    {
      return m_data;
    } // getNodeValue():String
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/templates/AVT.java
  
  Index: AVT.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import java.util.StringTokenizer;
  import org.xml.sax.SAXException;
  import org.xml.sax.ErrorHandler;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.processor.StylesheetHandler;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Class to hold an Attribute Value Template.
   */
  public class AVT implements java.io.Serializable
  {
    /**
     * If the AVT is not complex, just hold the simple string.
     */
    private String m_simpleString = null;
    
    /**
     * If the AVT is complex, hold a Vector of AVTParts.
     */
    private Vector m_parts = null;
    
    /**
     * The name of the attribute.
     */
    private String m_rawName;
    
    /**
     * Get the raw name of the attribute, with the prefix unprocessed.
     */
    String getRawName()
    {
      return m_rawName;
    }
    
    /**
     * The name of the attribute.
     */
    private String m_name;
    
    /**
     * Get the local name of the attribute.
     */
    String getName()
    {
      return m_name;
    }
  
    /**
     * The name of the attribute.
     */
    private String m_uri;
    
    /**
     * Get the namespace URI of the attribute.
     */
    String getURI()
    {
      return m_uri;
    }
  
    /**
     * Construct an AVT by parsing the string, and either 
     * constructing a vector of AVTParts, or simply hold 
     * on to the string if the AVT is simple.
     */
    public AVT(StylesheetHandler handler, 
               String uri, 
               String name,
               String rawName,
               String stringedValue)
      throws org.xml.sax.SAXException
    {
      m_uri = uri;
      m_name = name;
      m_rawName = rawName;
      StringTokenizer tokenizer = new StringTokenizer(stringedValue, "{}\"\'", 
true);
      int nTokens = tokenizer.countTokens();
      if(nTokens < 2)
      {
        m_simpleString = stringedValue; // then do the simple thing
      }
      else
      {
        m_parts = new Vector(nTokens+1);
        StringBuffer buffer = new StringBuffer(32);
        StringBuffer exprBuffer = new StringBuffer(32);
        String t = null; // base token
        String lookahead= null; // next token
        String error = null; // if non-null, break from loop
        while(tokenizer.hasMoreTokens())
        {
          if( lookahead != null )
          {
            t = lookahead;
            lookahead = null;
          }
          else t = tokenizer.nextToken();
          
          if(t.length() == 1)
          {
            switch(t.charAt(0))
            {
            case('\"'):
            case('\''):
              {
                // just keep on going, since we're not in an attribute template
                buffer.append(t);
                break;
              }
            case('{'):
              {
                // Attribute Value Template start
                lookahead = tokenizer.nextToken();
                if(lookahead.equals("{"))
                {
                  // Double curlys mean escape to show curly
                  buffer.append(lookahead);
                  lookahead = null;
                  break; // from switch
                }
                /*
                else if(lookahead.equals("\"") || lookahead.equals("\'"))
                {
                // Error. Expressions can not begin with quotes.
                error = "Expressions can not begin with quotes.";
                break; // from switch
                }
                */
                else
                {
                  if(buffer.length() > 0)
                  {
                    m_parts.addElement(new AVTPartSimple(buffer.toString()));
                    buffer.setLength(0);
                  }
  
                  exprBuffer.setLength(0);
                  while(null != lookahead)
                  {
                    if(lookahead.length() == 1)
                    {
                      switch(lookahead.charAt(0))
                      {
                      case '\'':
                      case '\"':
                        {
                          // String start
                          exprBuffer.append(lookahead);
                          String quote = lookahead;
                          // Consume stuff 'till next quote
                          lookahead = tokenizer.nextToken();
                          while(!lookahead.equals(quote))
                          {
                            exprBuffer.append(lookahead);
                            lookahead = tokenizer.nextToken();
                          }
                          exprBuffer.append(lookahead);
                          lookahead = tokenizer.nextToken();
                          break;
                        }
                      case '{':
                        {
                          // What's another curly doing here?
                          error = 
XSLMessages.createMessage(XSLTErrorResources.ER_NO_CURLYBRACE, null); //"Error: 
Can not have \"{\" within expression.";
                          break;
                        }
                      case '}':
                        {
                          // Proper close of attribute template.
                          // Evaluate the expression.
                          buffer.setLength(0);
                          
                          XPath xpath = 
handler.createXPath(exprBuffer.toString());
                          m_parts.addElement(new AVTPartXPath(xpath));
                          
                          lookahead = null; // breaks out of inner while loop
                          break;
                        }
                      default:
                        {
                          // part of the template stuff, just add it.
                          exprBuffer.append(lookahead);
                          lookahead = tokenizer.nextToken();
                        }
                      } // end inner switch
                    } // end if lookahead length == 1
                    else
                    {
                      // part of the template stuff, just add it.
                      exprBuffer.append(lookahead);
                      lookahead = tokenizer.nextToken();
                    }
                  } // end while(!lookahead.equals("}"))
                  if(error != null)
                  {
                    break; // from inner while loop
                  }
                }
                break;
              }
            case('}'):
              {
                lookahead = tokenizer.nextToken();
                if(lookahead.equals("}"))
                {
                  // Double curlys mean escape to show curly
                  buffer.append(lookahead);
                  lookahead = null; // swallow
                }
                else
                {
                  // Illegal, I think...
                  handler.warn(XSLTErrorResources.WG_FOUND_CURLYBRACE, null); 
//"Found \"}\" but no attribute template open!");
                  buffer.append("}");
                  // leave the lookahead to be processed by the next round.
                }
                break;
              }
            default:
              {
                // Anything else just add to string.
                buffer.append(t);
              }
            } // end switch t
          } // end if length == 1
          else
          {
            // Anything else just add to string.
            buffer.append(t);
          }
          if(null != error)
          {
            handler.warn(XSLTErrorResources.WG_ATTR_TEMPLATE, new Object[] 
{error}); //"Attr Template, "+error);
            break;
          }
        } // end while(tokenizer.hasMoreTokens())
        
        if(buffer.length() > 0)
        {
          m_parts.addElement(new AVTPartSimple(buffer.toString()));
          buffer.setLength(0);
        }
              
      } // end else nTokens > 1
      
      if(null == m_parts && (null == m_simpleString))
      {
        // Error?
        m_simpleString = "";
      }
    }
    
    /**
     * Evaluate the AVT and return a String.
     * @param context The current source tree context.
     * @param nsNode The current namespace context (stylesheet tree context).
     * @param NodeList The current Context Node List.
     */
    public String evaluate(XPathContext xctxt, Node context, 
                    org.apache.xalan.utils.PrefixResolver nsNode, 
                    StringBuffer buf)
      throws org.xml.sax.SAXException
    {
      if(null != m_simpleString)
      {
        return m_simpleString;
      }
      else if(null != m_parts)
      {
        buf.setLength(0);
        int n = m_parts.size();
        for(int i = 0; i < n; i++)
        {
          AVTPart part = (AVTPart)m_parts.elementAt(i);
          part.evaluate(xctxt, buf, context, nsNode);
        }
        return buf.toString();
      }
      else
      {
        return "";
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/AVTPart.java
  
  Index: AVTPart.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.apache.xalan.xpath.XPathContext;
  
  /**
   * <meta name="usage" content="internal"/>
   * Class to hold a part, either a string or XPath, 
   * of an Attribute Value Template.
   */
  public abstract class AVTPart implements java.io.Serializable
  {
    /**
     * Construct a part.
     */
    public AVTPart()
    {
    }
    
    /**
     * Write the evaluated value into the given 
     * string buffer.
     * @param buf Buffer to write into.
     * @param context The current source tree context.
     * @param nsNode The current namespace context (stylesheet tree context).
     * @param NodeList The current Context Node List.
     */
    public abstract void evaluate(XPathContext xctxt, StringBuffer buf, Node 
context, 
                                  org.apache.xalan.utils.PrefixResolver nsNode)
      throws org.xml.sax.SAXException;
    
    /**
     * Set the XPath support.
     */
    public void setXPathSupport(XPathContext support)
    {
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/AVTPartSimple.java
  
  Index: AVTPartSimple.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.apache.xalan.xpath.XPathContext;
  
  /**
   * <meta name="usage" content="internal"/>
   * Simple string part of a complex AVT.
   */
  public class AVTPartSimple extends AVTPart
  {
    /**
     * Simple string value;
     */
    private String m_val;
    
    /**
     * Construct a simple AVT part.
     * @param val A pure string section of an AVT.
     */
    public AVTPartSimple(String val)
    {
      m_val = val;
    }
    
    /**
     * Write the value into the buffer.
     * @param buf Buffer to write into.
     * @param context The current source tree context.
     * @param nsNode The current namespace context (stylesheet tree context).
     * @param NodeList The current Context Node List.
     */
    public void evaluate(XPathContext xctxt, StringBuffer buf, Node context, 
                                  org.apache.xalan.utils.PrefixResolver nsNode)
    {
      buf.append(m_val);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/AVTPartXPath.java
  
  Index: AVTPartXPath.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.*;
  
  /**
   * <meta name="usage" content="internal"/>
   * Simple string part of a complex AVT.
   */
  public class AVTPartXPath extends AVTPart
  {
    /**
     * Simple string value;
     */
    private XPath m_xpath;
    
    /**
     * Construct a simple AVT part.
     * @param val A pure string section of an AVT.
     */
    public AVTPartXPath(XPath xpath)
    {
      m_xpath = xpath;
    }
    
    /**
     * Construct a simple AVT part.
     * @param val A pure string section of an AVT.
     */
    public AVTPartXPath(String val, org.apache.xalan.utils.PrefixResolver 
nsNode, 
                        XPathParser xpathProcessor, 
                        XPathFactory factory, XPathContext liaison)
      throws org.xml.sax.SAXException
    {
      m_xpath = factory.create();
  
      xpathProcessor.initMatchPattern(m_xpath, val, nsNode);
      // m_xpath.shrink();
    }
    
    /**
     * Write the value into the buffer.
     * @param buf Buffer to write into.
     * @param context The current source tree context.
     * @param nsNode The current namespace context (stylesheet tree context).
     * @param NodeList The current Context Node List.
     */
    public void evaluate(XPathContext xctxt, StringBuffer buf, Node context, 
                                  org.apache.xalan.utils.PrefixResolver nsNode)
      throws org.xml.sax.SAXException
    {
      XObject xobj = m_xpath.execute(xctxt, context, nsNode);
      if(null != xobj)
      {
        buf.append(xobj.str());
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/Constants.java
  
  Index: Constants.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
   
  /**
   * <meta name="usage" content="advanced"/>
   * Primary constants used in the TransformerImpl classes.
   */
  public class Constants
  {
    public static final String 
      S_XMLNAMESPACEURI = "http://www.w3.org/XML/1998/namespace";,
      S_XSLNAMESPACEURL = "http://www.w3.org/1999/XSL/Transform";,
      S_OLDXSLNAMESPACEURL = "http://www.w3.org/XSL/Transform/1.0";,
      S_XPATHNAMESPACEURL = "http://www.w3.org/XSL/Transform";,
      S_XPATHNAMESPACEVERSION = "1.0",
      S_VENDOR = "Apache Software Foundation",
      S_VENDORURL =  "http://xml.apache.org";,
      
      /*
      * Special apache namespace for built-in extensions.
      */
      S_BUILTIN_EXTENSIONS_URL = "http://xml.apache.org/xslt";,
  
      PARSER_PATH = "com/ibm/xml/parser/Parser",
      //  LIAISON_CLASS = "org.apache.xalan.xpath.DOM2Helper";
      LIAISON_CLASS = "org.apache.xalan.dtm.DTMLiaison";
    
    /**
     * The minimum version of XSLT supported.
     */
    static final double XSLTVERSUPPORTED = 1.0;
  
    /**
     * IDs for XSL element types. These are associated 
     * with the string literals in the TransformerImpl class.
     * Don't change the numbers.
     */
    public static final int 
      ELEMNAME_UNDEFINED = -1,
      ELEMNAME_WITHPARAM = 2,
      ELEMNAME_ADDATTRIBUTE = 4,
      ELEMNAME_ANCHOR = 22,
      //  ELEMNAME_ANCHOR_PATTERN = 23,
      ELEMNAME_APPLY_TEMPLATES = 50,
      ELEMNAME_USE = 34,
      ELEMNAME_CHILDREN = 6,
      ELEMNAME_CHOOSE = 37,
      ELEMNAME_COMMENT = 59, // my own
      ELEMNAME_CONSTRUCT = 7, // my own
      ELEMNAME_CONTENTS = 8,
      ELEMNAME_COPY = 9,
      ELEMNAME_COPY_OF = 74,
      ELEMNAME_DECIMALFORMAT = 83,
      ELEMNAME_DEFINEATTRIBUTESET = 40,
      //  ELEMNAME_DEFINECONSTANT = 29,
      //  ELEMNAME_DEFINEMACRO = 10,
      ELEMNAME_DEFINESCRIPT = 11,
      ELEMNAME_DISPLAYIF = 12, // my own
      ELEMNAME_EMPTY = 14,
      ELEMNAME_EVAL = 15,
      ELEMNAME_EXPECTEDCHILDREN = 16,
      ELEMNAME_EXTENSION = 54,
      ELEMNAME_EXTENSIONHANDLER = 63,
      ELEMNAME_FOREACH = 28,
      ELEMNAME_KEY = 31,
      ELEMNAME_IF = 36,
      ELEMNAME_IMPORT = 26,
      ELEMNAME_INCLUDE = 27,
      ELEMNAME_CALLTEMPLATE = 17,
      ELEMNAME_PARAMVARIABLE = 41,
      ELEMNAME_NUMBER = 35,
      ELEMNAME_NSALIAS = 84,
      ELEMNAME_OTHERWISE = 39,
      ELEMNAME_PI = 58,
      ELEMNAME_PRESERVESPACE = 33,
      ELEMNAME_REMOVEATTRIBUTE = 5,
      ELEMNAME_TEMPLATE = 19,
      ELEMNAME_SORT = 64,
      ELEMNAME_STRIPSPACE = 32,
      ELEMNAME_STYLESHEET = 25,
      ELEMNAME_TEXT = 42,
      ELEMNAME_VALUEOF = 30,
      ELEMNAME_WHEN = 38,
      
      // Pattern by example support  
      ELEMNAME_ROOT = 44,
      ELEMNAME_ANY = 45,
      ELEMNAME_ELEMENT = 46,
      ELEMNAME_TARGETELEMENT = 47,
      ELEMNAME_ATTRIBUTE = 48,
      ELEMNAME_TARGETATTRIBUTE = 49,
      ELEMNAME_URL = 52, // my own
  
      ELEMNAME_CALL = 55, // my own
      //  ELEMNAME_WITHPARAM = 56,
      ELEMNAME_FALLBACK = 57, // my own
  
      ELEMNAME_TARGETPI = 60, // my own
      ELEMNAME_TARGETCOMMENT = 61, // my own
      ELEMNAME_TARGETTEXT = 62, // my own
  
      ELEMNAME_CSSSTYLECONVERSION = 65, // my own
  
      ELEMNAME_COUNTER = 66,
      ELEMNAME_COUNTERS = 67,
      ELEMNAME_COUNTERINCREMENT = 68,
      ELEMNAME_COUNTERRESET = 69,
      ELEMNAME_COUNTERSCOPE = 71,
      ELEMNAME_APPLY_IMPORTS = 72,
  
      ELEMNAME_VARIABLE = 73,
      ELEMNAME_MESSAGE = 75,
      ELEMNAME_LOCALE = 76,
  
      ELEMNAME_LITERALRESULT = 77,
      ELEMNAME_TEXTLITERALRESULT = 78,
  
      ELEMNAME_EXTENSIONCALL = 79,
  
      ELEMNAME_OUTPUT = 80,
  
      ELEMNAME_COMPONENT = 81,
      ELEMNAME_SCRIPT = 82;
  
    // Next free number: 85
    
    /**
     * Literals for XSL element names.  Note that there are more
     * names than IDs, because some names map to the same ID.
     */
    public static final String 
      ELEMNAME_COMPONENT_STRING = "component",
      ELEMNAME_SCRIPT_STRING = "script",
      ELEMNAME_ARG_STRING = "arg",
      ELEMNAME_ANCHOR_STRING = "anchor",
      ELEMNAME_ANY_STRING = "any", // pattern-by-example support
      ELEMNAME_APPLY_IMPORTS_STRING = "apply-imports",
      ELEMNAME_APPLY_TEMPLATES_STRING = "apply-templates",
      ELEMNAME_ATTRIBUTESET_STRING = "attribute-set",
      ELEMNAME_ATTRIBUTE_STRING = "attribute", // pattern-by-example support
      ELEMNAME_CALLTEMPLATEARG_STRING = "invoke-arg",
      ELEMNAME_CALLTEMPLATE_STRING = "call-template",
      ELEMNAME_CALL_STRING = "call",
      ELEMNAME_CHILDREN_STRING = "children",
      ELEMNAME_CHOOSE_STRING = "choose",
      ELEMNAME_COMMENT_STRING = "comment",
      ELEMNAME_CONSTRUCT_STRING = "construct", // my own
      ELEMNAME_CONTENTS_STRING = "contents",
      ELEMNAME_COPY_OF_STRING = "copy-of",
      ELEMNAME_COPY_STRING = "copy",
      ELEMNAME_DECIMALFORMAT_STRING = "decimal-format",
      
      ELEMNAME_COUNTERINCREMENT_STRING = "counter-increment",
      ELEMNAME_COUNTERRESET_STRING = "counter-reset",
      ELEMNAME_COUNTERSCOPE_STRING = "counter-scope",
      ELEMNAME_COUNTERS_STRING = "counters",
      ELEMNAME_COUNTER_STRING = "counter",
      ELEMNAME_CSSSTYLECONVERSION_STRING = "css-style-conversion",
      ELEMNAME_DISPLAYIF_STRING = "display-if", // my own
      ELEMNAME_ELEMENT_STRING = "element", // pattern-by-example support
      ELEMNAME_EMPTY_STRING = "empty",
      ELEMNAME_EVAL_STRING = "eval",
      ELEMNAME_EXPECTEDCHILDREN_STRING = "expectedchildren",
      ELEMNAME_EXTENSIONHANDLER_STRING = "code-dispatcher",
      ELEMNAME_EXTENSION_STRING = "functions",
      ELEMNAME_FALLBACK_STRING = "fallback",
      ELEMNAME_FOREACH_STRING = "for-each",
      ELEMNAME_IF_STRING = "if",
      ELEMNAME_IMPORT_STRING = "import",
      ELEMNAME_INCLUDE_STRING = "include",
      ELEMNAME_KEY_STRING = "key",
      ELEMNAME_LOCALE_STRING = "locale",
      ELEMNAME_MESSAGE_STRING = "message",
      ELEMNAME_NUMBER_STRING = "number",
      ELEMNAME_NSALIAS_STRING = "namespace-alias",
      ELEMNAME_OTHERWISE_STRING = "otherwise",
      ELEMNAME_OUTPUT_STRING = "output",
      ELEMNAME_PARAMVARIABLE_STRING = "param",
      ELEMNAME_PI_OLD_STRING = "pi",
      ELEMNAME_PI_STRING = "processing-instruction",
      ELEMNAME_PRESERVESPACE_STRING = "preserve-space",
      ELEMNAME_ROOT_STRING = "root", // pattern-by-example support
      ELEMNAME_SORT_STRING = "sort",
      ELEMNAME_STRIPSPACE_STRING = "strip-space",
      ELEMNAME_STYLESHEET_STRING = "stylesheet",
      ELEMNAME_TARGETATTRIBUTE_STRING = "target-attribute", // 
pattern-by-example support
      ELEMNAME_TARGETCOMMENT_STRING = "target-comment",
      ELEMNAME_TARGETELEMENT_STRING = "target-element", // pattern-by-example 
support
      ELEMNAME_TARGETPI_STRING = "target-pi",
      ELEMNAME_TARGETTEXT_STRING = "target-text",
      ELEMNAME_TEMPLATE_STRING = "template",
      ELEMNAME_TEXT_STRING = "text",
      ELEMNAME_TRANSFORM_STRING = "transform",
      ELEMNAME_URL_STRING = "uri", // pattern-by-example support
      ELEMNAME_USE_STRING = "use",
      ELEMNAME_VALUEOF_STRING = "value-of",
      ELEMNAME_VARIABLE_STRING = "variable",
      ELEMNAME_WHEN_STRING = "when",
      ELEMNAME_WITHPARAM_STRING = "with-param";
    
    public static final String
      ATTRNAME_OUTPUT_METHOD = "method", // qname, 
      ATTRNAME_AMOUNT = "amount",
      ATTRNAME_ANCESTOR = "ancestor",
      ATTRNAME_ARCHIVE = "archive",
      ATTRNAME_ATTRIBUTE = "attribute",
      ATTRNAME_ATTRIBUTE_SET = "attribute-set",
      ATTRNAME_CASEORDER = "case-order",
      ATTRNAME_CLASS = "class",
      ATTRNAME_CLASSID = "classid",
      ATTRNAME_CODEBASE = "codebase",
      ATTRNAME_CODETYPE = "type",
      ATTRNAME_CONDITION = "condition",
      ATTRNAME_COPYTYPE = "copy-type",
      ATTRNAME_COUNT = "count",
      ATTRNAME_DATATYPE = "data-type",
      ATTRNAME_DECIMALSEPARATOR = "decimal-separator",
      ATTRNAME_DEFAULT = "default",
      ATTRNAME_DEFAULTSPACE = "default-space",
      ATTRNAME_DEPTH = "with-children",
      ATTRNAME_DIGIT = "digit",
      ATTRNAME_DIGITGROUPSEP = "digit-group-sep",
      ATTRNAME_DISABLE_OUTPUT_ESCAPING  = "disable-output-escaping",
      ATTRNAME_ELEMENT = "element",
      ATTRNAME_ELEMENTS = "elements",
      ATTRNAME_EXPR = "expr",
      ATTRNAME_EXTENSIONELEMENTPREFIXES = "extension-element-prefixes",
      ATTRNAME_FORMAT = "format",
      ATTRNAME_FROM = "from",
      ATTRNAME_GROUPINGSEPARATOR = "grouping-separator",
      ATTRNAME_GROUPINGSIZE = "grouping-size",
      ATTRNAME_HREF = "href",
      ATTRNAME_ID = "id",
      ATTRNAME_IMPORTANCE = "importance",
      ATTRNAME_INDENTRESULT = "indent-result",
      ATTRNAME_INFINITY = "infinity",
      ATTRNAME_LANG = "lang",
      ATTRNAME_LETTERVALUE = "letter-value",
      ATTRNAME_LEVEL = "level",
      ATTRNAME_MATCH = "match",
      ATTRNAME_METHOD = "calls",
      ATTRNAME_MINUSSIGN = "minus-sign",
      ATTRNAME_MODE = "mode",
      ATTRNAME_NAME = "name",
      ATTRNAME_NAMESPACE = "namespace",
      ATTRNAME_NAN = "NaN",
      ATTRNAME_NDIGITSPERGROUP = "n-digits-per-group",
      ATTRNAME_NS = "ns",
      ATTRNAME_ONLY = "only",
      ATTRNAME_ORDER = "order",
      ATTRNAME_OUTPUT_CDATA_SECTION_ELEMENTS  = "cdata-section-elements",
      ATTRNAME_OUTPUT_DOCTYPE_PUBLIC = "doctype-public",
      ATTRNAME_OUTPUT_DOCTYPE_SYSTEM = "doctype-system",
      ATTRNAME_OUTPUT_ENCODING = "encoding",
      ATTRNAME_OUTPUT_INDENT = "indent",
      ATTRNAME_OUTPUT_MEDIATYPE = "media-type",
      ATTRNAME_OUTPUT_STANDALONE  = "standalone",
      ATTRNAME_OUTPUT_VERSION = "version",
      ATTRNAME_OUTPUT_OMITXMLDECL = "omit-xml-declaration",
      ATTRNAME_PATTERNSEPARATOR = "pattern-separator",
      ATTRNAME_PERCENT = "percent",
      ATTRNAME_PERMILLE = "per-mille",
      ATTRNAME_PRIORITY = "priority",
      ATTRNAME_REFID = "refID",
      ATTRNAME_RESULTNS = "result-ns",
      ATTRNAME_RESULT_PREFIX = "result-prefix",
      ATTRNAME_SELECT = "select",
      ATTRNAME_SEQUENCESRC = "sequence-src",
      ATTRNAME_STYLE = "style",
      ATTRNAME_STYLESHEET_PREFIX = "stylesheet-prefix",
      ATTRNAME_TERMINATE = "terminate", 
      ATTRNAME_TEST = "test",
      ATTRNAME_TOSTRING = "to-string",
      ATTRNAME_TYPE = "type",
      ATTRNAME_USE = "use",
      ATTRNAME_USEATTRIBUTESETS = "use-attribute-sets",
      ATTRNAME_VALUE = "value",
      ATTRNAME_VERSION = "version",
      ATTRNAME_XMLNSDEF = "xmlns",
      ATTRNAME_XMLNS = "xmlns:",
      ATTRNAME_XMLSPACE = "xml:space",
      ATTRNAME_ZERODIGIT = "zero-digit",
      ATTRNAME_EXCLUDE_RESULT_PREFIXES = "exclude-result-prefixes";
    
    public static  final int 
      TATTRNAME_OUTPUT_METHOD = 1,
      TATTRNAME_AMOUNT = 2,
      TATTRNAME_ANCESTOR = 3,
      TATTRNAME_ARCHIVE = 4,
      TATTRNAME_ATTRIBUTE = 5,
      TATTRNAME_ATTRIBUTE_SET = 6,
      TATTRNAME_CASEORDER = 7,
      TATTRNAME_CLASS = 8,
      TATTRNAME_CLASSID = 9,
      TATTRNAME_CODEBASE = 10,
      TATTRNAME_CODETYPE = 11,
      TATTRNAME_CONDITION = 12,
      TATTRNAME_COPYTYPE = 13,
      TATTRNAME_COUNT = 14,
      TATTRNAME_DATATYPE = 15,
      TATTRNAME_DEFAULT = 16,
      TATTRNAME_DEFAULTSPACE = 17,
      TATTRNAME_DEPTH = 18,
      TATTRNAME_DIGITGROUPSEP = 19,
      TATTRNAME_DISABLE_OUTPUT_ESCAPING  = 20,
      TATTRNAME_ELEMENT = 21,
      TATTRNAME_ELEMENTS = 22,
      TATTRNAME_EXPR = 23,
      TATTRNAME_EXTENSIONELEMENTPREFIXES = 24,
      TATTRNAME_FORMAT = 25,
      TATTRNAME_FROM = 26,
      TATTRNAME_GROUPINGSEPARATOR = 27,
      TATTRNAME_GROUPINGSIZE = 28,
      TATTRNAME_HREF = 29,
      TATTRNAME_ID = 30,
      TATTRNAME_IMPORTANCE = 31,
      TATTRNAME_INDENTRESULT = 32,
      TATTRNAME_LANG = 33,
      TATTRNAME_LETTERVALUE = 34,
      TATTRNAME_LEVEL = 35,
      TATTRNAME_MATCH = 36,
      TATTRNAME_METHOD = 37,
      TATTRNAME_MODE = 38,
      TATTRNAME_NAME = 39,
      TATTRNAME_NAMESPACE = 40,
      TATTRNAME_NDIGITSPERGROUP = 41,
      TATTRNAME_NS = 42,
      TATTRNAME_ONLY = 43,
      TATTRNAME_ORDER = 44,
      TATTRNAME_OUTPUT_CDATA_SECTION_ELEMENTS  = 45,
      TATTRNAME_OUTPUT_DOCTYPE_PUBLIC = 46,
      TATTRNAME_OUTPUT_DOCTYPE_SYSTEM = 47,
      TATTRNAME_OUTPUT_ENCODING = 48,
      TATTRNAME_OUTPUT_INDENT = 49,
      TATTRNAME_OUTPUT_MEDIATYPE = 50,
      TATTRNAME_OUTPUT_STANDALONE  = 51,
      TATTRNAME_OUTPUT_VERSION = 52,
      TATTRNAME_OUTPUT_OMITXMLDECL = 53,
      TATTRNAME_PRIORITY = 54,
      TATTRNAME_REFID = 55,
      TATTRNAME_RESULTNS = 56,
      TATTRNAME_SELECT = 57,
      TATTRNAME_SEQUENCESRC = 58,
      TATTRNAME_STYLE = 59,  
      TATTRNAME_TEST = 60,
      TATTRNAME_TOSTRING = 61,
      TATTRNAME_TYPE = 62,
      TATTRNAME_USE = 63,
      TATTRNAME_USEATTRIBUTESETS = 64,
      TATTRNAME_VALUE = 65,
      TATTRNAME_XMLNSDEF = 66,
      TATTRNAME_XMLNS = 67,
      TATTRNAME_XMLSPACE = 68,
      TATTRNAME_EXCLUDE_RESULT_PREFIXES = 69
      ;
    
    public static final String 
      ATTRVAL_OUTPUT_METHOD_HTML = "html",
      ATTRVAL_OUTPUT_METHOD_XML = "xml",
      ATTRVAL_OUTPUT_METHOD_TEXT = "text";
    
    // For space-att
    public static final int 
      ATTRVAL_PRESERVE = 1,
      ATTRVAL_STRIP = 2;
    
    // For indent-result
    public static final boolean 
      ATTRVAL_YES = true,
      ATTRVAL_NO = false;
    
    // For letter-value attribute (part of conversion attributes).
    public static final String 
      ATTRVAL_ALPHABETIC = "alphabetic",
      ATTRVAL_OTHER = "other",
      ATTRVAL_TRADITIONAL = "traditional";
    
    // For level attribute in xsl:number.
    public static final String 
      ATTRVAL_SINGLE = "single",
      ATTRVAL_MULTI = "multiple",
      ATTRVAL_ANY = "any";
    
    // For Stylesheet-prefix and result-prefix in xsl:namespace-alias 
    public static final String ATTRVAL_DEFAULT_PREFIX = "#default";
    
    // Integer equivelents for above
    public static final int 
      NUMBERLEVEL_SINGLE = 1,
      NUMBERLEVEL_MULTI = 2,
      NUMBERLEVEL_ANY = 3,
  
      MAX_MULTI_COUNTING_DEPTH = 32;
    
    // some stuff for my patterns-by-example
    public static final String 
      ATTRVAL_THIS = ".",
      ATTRVAL_PARENT = "..",
      ATTRVAL_ANCESTOR = "ancestor",
      ATTRVAL_ID = "id";
    
    // Stuff for sorting
    public static final String 
      ATTRVAL_DATATYPE_TEXT = "text",
      ATTRVAL_DATATYPE_NUMBER = "number",
      
      ATTRVAL_ORDER_ASCENDING = "ascending",
      ATTRVAL_ORDER_DESCENDING = "descending",
  
      ATTRVAL_CASEORDER_UPPER = "upper-first",
      ATTRVAL_CASEORDER_LOWER = "lower-first";
    
    // some stuff for Decimal-format
    public static final String 
      ATTRVAL_INFINITY = "Infinity",
      ATTRVAL_NAN = "NaN",
      DEFAULT_DECIMAL_FORMAT = "#default";
  
    // temp dummy 
    public static final String ATTRNAME_XXXX = "XXXX";
  
    public static final String 
      ERROR_RESOURCES = "org.apache.xalan.res.XSLTErrorResources",
      XSLT_RESOURCE = "org.apache.xalan.res.XSLTResourceBundle",
      LANG_BUNDLE_NAME = "org.apache.xalan.res.XSLTResources",
      MULT_ORDER = "multiplierOrder",
      MULT_PRECEDES = "precedes",
      MULT_FOLLOWS = "follows",
      LANG_ORIENTATION = "orientation",
      LANG_RIGHTTOLEFT = "rightToLeft",
      LANG_LEFTTORIGHT = "leftToRight",
      LANG_NUMBERING = "numbering",
      LANG_ADDITIVE = "additive",
      LANG_MULT_ADD = "multiplicative-additive",
      LANG_MULTIPLIER = "multiplier",
      LANG_MULTIPLIER_CHAR  = "multiplierChar",
      LANG_NUMBERGROUPS = "numberGroups",
      LANG_NUM_TABLES = "tables",
      LANG_ALPHABET = "alphabet",
      LANG_TRAD_ALPHABET = "tradAlphabet";
  
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/DecimalFormatProperties.java
  
  Index: DecimalFormatProperties.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import java.util.*;
  import java.text.NumberFormat;
  import java.text.DecimalFormat;
  import java.text.DecimalFormatSymbols;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.*;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:decimal-format.
   * <pre>
   * <!ELEMENT xsl:decimal-format EMPTY>
   * <!ATTLIST xsl:decimal-format
   *   name %qname; #IMPLIED
   *   decimal-separator %char; "."
   *   grouping-separator %char; ","
   *   infinity CDATA "Infinity"
   *   minus-sign %char; "-"
   *   NaN CDATA "NaN"
   *   percent %char; "%"
   *   per-mille %char; "&#x2030;"
   *   zero-digit %char; "0"
   *   digit %char; "#"
   *   pattern-separator %char; ";"
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#format-number";>format-number in 
XSLT Specification</a>
   */
  public class DecimalFormatProperties
  {  
    DecimalFormatSymbols m_dfs = new java.text.DecimalFormatSymbols();
    
    /**
     * Return the decimal format Symbols for this element.
     * <p>The xsl:decimal-format element declares a decimal-format, 
     * which controls the interpretation of a format pattern used by 
     * the format-number function. If there is a name attribute, then 
     * the element declares a named decimal-format; otherwise, it 
     * declares the default decimal-format. The value of the name 
     * attribute is a QName, which is expanded as described in [2.4 Qualified 
Names]. 
     * It is an error to declare either the default decimal-format or a 
     * decimal-format with a given name more than once (even with different 
     * import precedence), unless it is declared every time with the same 
     * value for all attributes (taking into account any default values).</p>
     * <p>The other attributes on xsl:decimal-format correspond to the 
     * methods on the JDK 1.1 DecimalFormatSymbols class. For each get/set 
     * method pair there is an attribute defined for the xsl:decimal-format 
     * element.</p>
     */
    public DecimalFormatSymbols getDecimalFormatSymbols()
    {
      return m_dfs;
    }
  
    /**
     * If there is a name attribute, then the element declares a named 
     * decimal-format; otherwise, it declares the default decimal-format. 
     */
    private QName m_qname = null;
    
    /**
     * Set the "name" attribute. 
     * If there is a name attribute, then the element declares a named 
     * decimal-format; otherwise, it declares the default decimal-format. 
     */
    public void setName(QName qname)
    {
      m_qname = qname;
    }
  
    /**
     * Get the "name" attribute. 
     * If there is a name attribute, then the element declares a named 
     * decimal-format; otherwise, it declares the default decimal-format. 
     */
    public QName getName()
    {
      return m_qname;
    }
    
    /**
     * Set the "decimal-separator" attribute. 
     * decimal-separator specifies the character used for the decimal sign; 
     * the default value is the period character (.).
     */
    public void setDecimalSeparator(char ds)
    {
      m_dfs.setDecimalSeparator(ds);
    }
  
    /**
     * Get the "decimal-separator" attribute. 
     * decimal-separator specifies the character used for the decimal sign; 
     * the default value is the period character (.).
     */
    public char getDecimalSeparator()
    {
      return m_dfs.getDecimalSeparator();
    }
    
    /**
     * Set the "grouping-separator" attribute. 
     * grouping-separator specifies the character used as a grouping 
     * (e.g. thousands) separator; the default value is the comma character (,).
     */
    public void setGroupingSeparator(char gs)
    {
      m_dfs.setGroupingSeparator(gs);
    }
  
    /**
     * Get the "grouping-separator" attribute. 
     * grouping-separator specifies the character used as a grouping 
     * (e.g. thousands) separator; the default value is the comma character (,).
     */
    public char getGroupingSeparator()
    {
      return m_dfs.getGroupingSeparator();
    }
    
    /**
     * Set the "infinity" attribute. 
     * infinity specifies the string used to represent infinity; 
     * the default value is the string Infinity.
     */
    public void setInfinity(String inf)
    {
      m_dfs.setInfinity(inf);
    }
  
    /**
     * Get the "infinity" attribute. 
     * infinity specifies the string used to represent infinity; 
     * the default value is the string Infinity.
     */
    public String getInfinity()
    {
      return m_dfs.getInfinity();
    }
    
    /**
     * Set the "minus-sign" attribute. 
     * minus-sign specifies the character used as the default minus sign; the 
     * default value is the hyphen-minus character (-, #x2D).
     */
    public void setMinusSign(char v)
    {
      m_dfs.setMinusSign(v);
    }
  
    /**
     * Get the "minus-sign" attribute. 
     * minus-sign specifies the character used as the default minus sign; the 
     * default value is the hyphen-minus character (-, #x2D).
     */
    public char getMinusSign()
    {
      return m_dfs.getMinusSign();
    }
    
    /**
     * Set the "NaN" attribute. 
     * NaN specifies the string used to represent the NaN value; 
     * the default value is the string NaN.
     */
    public void setNaN(String v)
    {
      m_dfs.setNaN(v);
    }
  
    /**
     * Get the "NaN" attribute. 
     * NaN specifies the string used to represent the NaN value; 
     * the default value is the string NaN.
     */
    public String getNaN()
    {
      return m_dfs.getNaN();
    }
      
    /**
     * Set the "percent" attribute. 
     * percent specifies the character used as a percent sign; the default 
     * value is the percent character (%).
     */
    public void setPercent(char v)
    {
      m_dfs.setPercent(v);
    }
  
    /**
     * Get the "percent" attribute. 
     * percent specifies the character used as a percent sign; the default 
     * value is the percent character (%).
     */
    public char getPercent()
    {
      return m_dfs.getPercent();
    }
      
    /**
     * Set the "per-mille" attribute. 
     * per-mille specifies the character used as a per mille sign; the default 
     * value is the Unicode per-mille character (#x2030).
     */
    public void setPerMille(char v)
    {
      m_dfs.setPerMill(v);
    }
  
    /**
     * Get the "per-mille" attribute. 
     * per-mille specifies the character used as a per mille sign; the default 
     * value is the Unicode per-mille character (#x2030).
     */
    public char getPerMille()
    {
      return m_dfs.getPerMill();
    }
      
    /**
     * Set the "zero-digit" attribute. 
     * zero-digit specifies the character used as the digit zero; the default 
     * value is the digit zero (0).
     */
    public void setZeroDigit(char v)
    {
      m_dfs.setZeroDigit(v);
    }
  
    /**
     * Get the "zero-digit" attribute. 
     * zero-digit specifies the character used as the digit zero; the default 
     * value is the digit zero (0).
     */
    public char getZeroDigit()
    {
      return m_dfs.getZeroDigit();
    }
    
    /**
     * Set the "digit" attribute. 
     * digit specifies the character used for a digit in the format pattern; 
     * the default value is the number sign character (#).
     */
    public void setDigit(char v)
    {
      m_dfs.setDigit(v);
    }
  
    /**
     * Get the "digit" attribute. 
     * digit specifies the character used for a digit in the format pattern; 
     * the default value is the number sign character (#).
     */
    public char getDigit()
    {
      return m_dfs.getDigit();
    }
      
    /**
     * Set the "pattern-separator" attribute. 
     * pattern-separator specifies the character used to separate positive 
     * and negative sub patterns in a pattern; the default value is the 
     * semi-colon character (;).
     */
    public void setPatternSeparator(char v)
    {
      m_dfs.setPatternSeparator(v);
    }
  
    /**
     * Get the "pattern-separator" attribute. 
     * pattern-separator specifies the character used to separate positive 
     * and negative sub patterns in a pattern; the default value is the 
     * semi-colon character (;).
     */
    public char getPatternSeparator()
    {
      return m_dfs.getPatternSeparator();
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemApplyImport.java
  
  Index: ElemApplyImport.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  import org.xml.sax.SAXException;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.utils.QName;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:apply-imports.
   * <pre>
   * <!ELEMENT xsl:apply-imports EMPTY>
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#apply-imports";>apply-imports in 
XSLT Specification</a>
   */
  public class ElemApplyImport extends ElemTemplateElement
  {
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_APPLY_IMPORTS;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_APPLY_IMPORTS_STRING;
    }
      
    /**
     * Execute the xsl:apply-imports transformation.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      if (transformer.currentTemplateRuleIsNull())
      {
        
transformer.getMsgMgr().error(XSLTErrorResources.ER_NO_APPLY_IMPORT_IN_FOR_EACH);
 //"xsl:apply-imports not allowed in a xsl:for-each");
      }
  
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
      
      if(null != sourceNode)
      {
        // This will have to change to current template, (which will have 
        // to be the top of a current template stack).
        
        transformer.transformNode(null, null, sourceNode, mode);
      }
      else // if(null == sourceNode)
      {
        
transformer.getMsgMgr().error(XSLTErrorResources.ER_NULL_SOURCENODE_APPLYIMPORTS);
 //"sourceNode is null in xsl:apply-imports!");
      }
    }
    
    /**
     * Add a child to the child list.
     * <!ELEMENT xsl:apply-imports EMPTY>
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
      //" to " + this.m_elemName);
      return null;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemApplyTemplates.java
  
  Index: ElemApplyTemplates.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import java.util.Vector;
  import org.apache.xalan.trace.TracerEvent;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.xpath.VariableStack;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:apply-templates.
   * <pre>
   * &amp;!ELEMENT xsl:apply-templates (xsl:sort|xsl:with-param)*>
   * &amp;!ATTLIST xsl:apply-templates
   *   select %expr; "node()"
   *   mode %qname; #IMPLIED
   * &amp;
   * </pre> 
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Applying-Template-Rules";>section-Applying-Template-Rules
 in XSLT Specification</a>
   */
  public class ElemApplyTemplates extends ElemForEach
  {
    /**
     * mode %qname; #IMPLIED
     */
    private QName m_mode = null;
    
    /**
     * Set the mode attribute for this element.
     */
    public void setMode(QName mode)
    {
      m_mode = mode;
    }
  
    /**
     * Get the mode attribute for this element.
     */
    public QName getMode()
    {
      return m_mode;
    }
  
    /**
     * Tells if this belongs to a default template, 
     * in which case it will act different with 
     * regard to processing modes.
     * @see <a href="http://www.w3.org/TR/xslt#built-in-rule";>built-in-rule in 
XSLT Specification</a>
     */
    private boolean m_isDefaultTemplate = false;
    
    /**
     * Set if this belongs to a default template, 
     * in which case it will act different with 
     * regard to processing modes.
     * @see <a href="http://www.w3.org/TR/xslt#built-in-rule";>built-in-rule in 
XSLT Specification</a>
     */
    public void setIsDefaultTemplate(boolean b)
    {
      m_isDefaultTemplate = b;
    }
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_APPLY_TEMPLATES;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_APPLY_TEMPLATES_STRING;
    }
  
    /**
     * Apply the context node to the matching templates.
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Applying-Template-Rules";>section-Applying-Template-Rules
 in XSLT Specification</a>
     */
    public void execute(TransformerImpl transformer,
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {    
      transformer.pushCurrentTemplateRuleIsNull(false);
  
      try
      {
        if(TransformerImpl.S_DEBUG)
          transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
        
        if(null != sourceNode)
        {      
          // boolean needToTurnOffInfiniteLoopCheck = false;
          
          if(!m_isDefaultTemplate)
          {
            mode = m_mode;
          }
  
          // Dragons here.  Push the params & stack frame, but then 
          // execute the select statement inside transformSelectedNodes, 
          // which must be executed in the stack frame before the 
          // new stack frame.  Because of depth-first searching, this 
          // gets worse.
          VariableStack vars = transformer.getXPathContext().getVarStack();
          int selectStackFrameIndex = vars.getCurrentStackFrameIndex();
          
          vars.pushContextMarker();
          vars.setCurrentStackFrameIndex(selectStackFrameIndex);
          transformer.pushParams(getStylesheet(), 
                          this, 
                          sourceNode, mode);
          vars.setCurrentStackFrameIndex(vars.size());
  
          try
          {
            transformer.transformSelectedNodes(getStylesheetComposed(), 
                                      this,
                                      null, 
                                      sourceNode, mode,
                                      getSelect(), 
                                      selectStackFrameIndex);
          }
          finally
          {
            vars.popCurrentContext();
            vars.setCurrentStackFrameIndex(selectStackFrameIndex);
          }
        }
        else // if(null == sourceNode)
        {
          
transformer.getMsgMgr().error(XSLTErrorResources.ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES);//"sourceNode
 is null in handleApplyTemplatesInstruction!");
        }
      }
  
      finally
      {
        transformer.popCurrentTemplateRuleIsNull();
      }
  
    }  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemAttribute.java
  
  Index: ElemAttribute.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  import org.xml.sax.SAXException;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.transformer.ResultTreeHandler;
  import org.apache.xalan.xpath.XPathContext;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:attribute.
   * <pre>
   * &amp;!ELEMENT xsl:attribute %char-template;>
   * &amp;!ATTLIST xsl:attribute 
   *   name %avt; #REQUIRED
   *   namespace %avt; #IMPLIED
   *   %space-att;
   * &amp;
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#creating-attributes";>creating-attributes in 
XSLT Specification</a> 
   */
  public class ElemAttribute extends ElemTemplateElement
  {
    /**
     * The local name which should be used.
     */
    public AVT m_name_avt = null;
    
    /**
     * The namespace which should be used.
     */
    public AVT m_namespace_avt = null;
    
    /**
     * Set the "name" attribute.
     */
    public void setName(AVT name)
    {
      m_name_avt = name;
    }
  
    /**
     * Get the "name" attribute.
     */
    public AVT getName()
    {
      return m_name_avt;
    }
  
    /**
     * Set the "namespace" attribute.
     */
    public void setNamespace(AVT name)
    {
      m_namespace_avt = name;
    }
  
    /**
     * Get the "namespace" attribute.
     */
    public AVT getNamespace()
    {
      return m_namespace_avt;
    }
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_ATTRIBUTE;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_ATTRIBUTE_STRING;
    }
    
    /**
     * Create an attribute in the result tree.
     * @see <a 
href="http://www.w3.org/TR/xslt#creating-attributes";>creating-attributes in 
XSLT Specification</a>
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
      
      ResultTreeHandler rhandler = transformer.getResultTreeHandler();
      XPathContext xctxt = transformer.getXPathContext();
      
      // The attribute name has to be evaluated as an AVT.
      String attrName = m_name_avt.evaluate(xctxt, sourceNode, this,
                                            new StringBuffer());
      String origAttrName = attrName;      // save original attribute name
      
      // Get the children of the xsl:attribute element as the string value.
      String val = transformer.transformToString(this, sourceNode, mode);
  
      // If they are trying to add an attribute when there isn't an 
      // element pending, it is an error.
      if(null == rhandler.getPendingElementName())
      {
        
transformer.getMsgMgr().warn(XSLTErrorResources.WG_ILLEGAL_ATTRIBUTE_NAME, new 
Object[]{origAttrName}); 
        // warn(templateChild, sourceNode, "Trying to add attribute after 
element child has been added, ignoring...");
      }
  
      if(null == attrName)
        return; 
      
      String attrNameSpace = null; // by default
      
      // Did they declare a namespace attribute?
      if(null != m_namespace_avt)
      {
        // The namespace attribute is an AVT also.
        attrNameSpace = m_namespace_avt.evaluate(xctxt, sourceNode, this,
                                                 new StringBuffer());
        if(null != attrNameSpace && attrNameSpace.length()>0)
        {
          // Get the prefix for that attribute in the result namespace.
          String prefix = rhandler.getPrefix(attrNameSpace);
          
          // If we didn't find the prefix mapping, make up a prefix 
          // and have it declared in the result tree.
          if(null == prefix)
          {
            prefix = rhandler.getNewUniqueNSPrefix();
            rhandler.startPrefixMapping(prefix, attrNameSpace);
          }
          // add the prefix to the attribute name.
          attrName = (prefix + ":"+QName.getLocalPart(attrName));       
        }
      }
      // Is the attribute xmlns type?
      else if(QName.isXMLNSDecl(origAttrName))
      {
        // Then just declare the namespace prefix and get out.
        String prefix = QName.getPrefixFromXMLNSDecl(origAttrName);
        String ns = rhandler.getURI(prefix);
        if(null == ns)
          rhandler.startPrefixMapping(prefix, val);
        return;
      }
      // Note we are using original attribute name for these tests. 
      else
      {
        // Does the attribute name have a prefix?
        String nsprefix = QName.getPrefixPart(origAttrName);
        if(null == nsprefix)
          nsprefix = "";
        
        // We're going to claim that this must be resolved in 
        // the result tree namespace.
        try
        {
          attrNameSpace = getNamespaceForPrefix(nsprefix);
          if((null == attrNameSpace) && (nsprefix.length() > 0))
          {
            
transformer.getMsgMgr().warn(XSLTErrorResources.WG_COULD_NOT_RESOLVE_PREFIX, 
new Object[]{nsprefix});            
            return;
          }
        }
        catch(Exception ex) 
        {
          // Could not resolve prefix
          attrNameSpace = null;
          
transformer.getMsgMgr().warn(XSLTErrorResources.WG_COULD_NOT_RESOLVE_PREFIX, 
new Object[]{nsprefix});            
          return;
        }
      }
      
      String localName = QName.getLocalPart(attrName);
      rhandler.addAttribute(attrNameSpace, localName, 
                            attrName, "CDATA", val);
      
    }
    
    /**
     * Add a child to the child list.
     * <!ELEMENT xsl:attribute %char-template;>
     * <!ATTLIST xsl:attribute 
     *   name %avt; #REQUIRED
     *   namespace %avt; #IMPLIED
     *   %space-att;
     * >
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      int type = ((ElemTemplateElement)newChild).getXSLToken();
      switch(type)
      {
        // char-instructions 
      case Constants.ELEMNAME_TEXTLITERALRESULT:
      case Constants.ELEMNAME_APPLY_TEMPLATES:
      case Constants.ELEMNAME_APPLY_IMPORTS:
      case Constants.ELEMNAME_CALLTEMPLATE:
      case Constants.ELEMNAME_FOREACH:
      case Constants.ELEMNAME_VALUEOF:
      case Constants.ELEMNAME_COPY_OF:
      case Constants.ELEMNAME_NUMBER:
      case Constants.ELEMNAME_CHOOSE:
      case Constants.ELEMNAME_IF:
      case Constants.ELEMNAME_TEXT:
      case Constants.ELEMNAME_COPY:
      case Constants.ELEMNAME_VARIABLE:
      case Constants.ELEMNAME_MESSAGE:
        
        // instructions 
        // case Constants.ELEMNAME_PI:
        // case Constants.ELEMNAME_COMMENT:
        // case Constants.ELEMNAME_ELEMENT:
        // case Constants.ELEMNAME_ATTRIBUTE:
  
        break;
        
      default:
          error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
              //" to " + this.m_elemName);
      }
      return super.appendChild(newChild);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemAttributeSet.java
  
  Index: ElemAttributeSet.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  import org.xml.sax.SAXException;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.res.XSLMessages;
  import java.util.Stack;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:attribute-set.
   * <pre>
   * &amp;!ELEMENT xsl:attribute-set (xsl:attribute)*>
   * &amp;!ATTLIST xsl:attribute-set
   *   name %qname; #REQUIRED
   *   use-attribute-sets %qnames; #IMPLIED
   * &amp;
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#attribute-sets";>attribute-sets in 
XSLT Specification</a>
   */
  public class ElemAttributeSet extends ElemUse
  {
    /**
     * The name attribute specifies the name of the attribute set. 
     */
    public QName m_qname = null;
    
    /**
     * Set the "name" attribute. 
     * The name attribute specifies the name of the attribute set. 
     */
    public void setName(QName name)
    {
      m_qname = name;
    }
  
    /**
     * Get the "name" attribute.
     * The name attribute specifies the name of the attribute set. 
     */
    public QName getName()
    {
      return m_qname;
    }
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_DEFINEATTRIBUTESET;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_ATTRIBUTESET_STRING;
    }
  
    
    /**
     * Apply a set of attributes to the element.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      if(transformer.isRecursiveAttrSet(this))
      {
        throw new 
SAXException(XSLMessages.createMessage(XSLTErrorResources.ER_XSLATTRSET_USED_ITSELF,
 new Object[]{m_qname.getLocalPart()})); //"xsl:attribute-set 
'"+m_qname.m_localpart+
      }
      
      transformer.pushElemAttributeSet(this);
      
      super.execute(transformer, sourceNode, mode);
      ElemAttribute attr = (ElemAttribute)getFirstChild();
      while(null != attr)
      {
        attr.execute(transformer, sourceNode, mode);
        attr = (ElemAttribute)attr.getNextSibling();
      }
      transformer.popElemAttributeSet();
    }
    
    /**
     * Add a child to the child list.
     * <!ELEMENT xsl:attribute-set (xsl:attribute)*>
     * <!ATTLIST xsl:attribute-set
     *   name %qname; #REQUIRED
     *   use-attribute-sets %qnames; #IMPLIED
     * >
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      int type = ((ElemTemplateElement)newChild).getXSLToken();
      switch(type)
      {
      case Constants.ELEMNAME_ATTRIBUTE:
        break;
        
      default:
        error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
              //" to " + this.m_elemName);
      }
      return super.appendChild(newChild);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemCallTemplate.java
  
  Index: ElemCallTemplate.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.xpath.VariableStack;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:call-template.
   * <pre>
   * &amp;!ELEMENT xsl:call-template (xsl:with-param)*>
   * &amp;!ATTLIST xsl:call-template
   *   name %qname; #REQUIRED
   * &amp;
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#named-templates";>named-templates 
in XSLT Specification</a>
   */
  public class ElemCallTemplate extends ElemTemplateElement
  {
    /**
     * An xsl:call-template element invokes a template by name; 
     * it has a required name attribute that identifies the template to be 
invoked. 
     */
    public QName m_templateName = null;
    
    /**
     * Set the "name" attribute. 
     * An xsl:call-template element invokes a template by name; 
     * it has a required name attribute that identifies the template to be 
invoked. 
     */
    public void setName(QName name)
    {
      m_templateName = name;
    }
  
    /**
     * Get the "name" attribute.
     * An xsl:call-template element invokes a template by name; 
     * it has a required name attribute that identifies the template to be 
invoked. 
     */
    public QName getName()
    {
      return m_templateName;
    }
  
    /**
     * The template which is named by QName.
     */
    private ElemTemplateElement m_template = null;
      
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_CALLTEMPLATE;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_CALLTEMPLATE_STRING;
    }
  
    /**
     * Invoke a named template.
     * @see <a href="http://www.w3.org/TR/xslt#named-templates";>named-templates 
in XSLT Specification</a>
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
      
      // XPathContext xctxt = transformer.getXPathContext();
      if(null == m_template)
      {
        m_template 
          = this.getStylesheetRoot().getTemplateComposed(m_templateName);
      }
      
      if(null != m_template)
      {
        XPathContext xctxt = transformer.getXPathContext();
        VariableStack vars = xctxt.getVarStack();
        int selectStackFrameIndex = vars.getCurrentStackFrameIndex();
        
        vars.pushContextMarker();
        vars.setCurrentStackFrameIndex(selectStackFrameIndex);
        transformer.pushParams(getStylesheet(), 
                               this, sourceNode, mode);
        vars.setCurrentStackFrameIndex(vars.size());
        Locator savedLocator = xctxt.getSAXLocator();
        try
        {        
          xctxt.setSAXLocator(m_template);
          // template.executeChildTemplates(transformer, sourceNode, mode);
          m_template.execute(transformer, sourceNode, mode);
        }
        finally
        {
          xctxt.setSAXLocator(savedLocator);
          vars.popCurrentContext();
          vars.setCurrentStackFrameIndex(selectStackFrameIndex);
        }
      }
      else
      {
        transformer.getMsgMgr().error(XSLTErrorResources.ER_TEMPLATE_NOT_FOUND, 
new Object[] {m_templateName}); //"Could not find template named: 
'"+templateName+"'");
      }
    }
    
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      int type = ((ElemTemplateElement)newChild).getXSLToken();
      switch(type)
      {
      case Constants.ELEMNAME_WITHPARAM:
        break;
        
      default:
        error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
              //" to " + this.m_elemName);
      }
      return super.appendChild(newChild);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemChoose.java
  
  Index: ElemChoose.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.trace.SelectionEvent;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:choose.
   * <pre>
   * <!ELEMENT xsl:choose (xsl:when+, xsl:otherwise?)>
   * <!ATTLIST xsl:choose %space-att;>
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Conditional-Processing-with-xsl:choose";>XXX
 in XSLT Specification</a>
   */
  public class ElemChoose extends ElemTemplateElement
  {  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_CHOOSE;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_CHOOSE_STRING;
    }
   
    public ElemChoose()
    {
    }
  
    public void execute(TransformerImpl transformer, 
                       Node sourceNode,
                       QName mode)
      throws SAXException
    {    
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
      
      boolean found = false;
      for (ElemTemplateElement childElem = getFirstChildElem(); 
           childElem != null; childElem = childElem.getNextSiblingElem()) 
      {
        int type = childElem.getXSLToken();
        if(Constants.ELEMNAME_WHEN == type)
        {
                    found = true;  
          ElemWhen when = (ElemWhen)childElem;
          // must be xsl:when
          
          XObject test = when.getTest().execute(transformer.getXPathContext(), 
                                             sourceNode, this);
          if(TransformerImpl.S_DEBUG)
            transformer.getTraceManager().fireSelectedEvent(sourceNode,
                                          when, "test", 
                                          when.getTest(), test);
  
          if((null != test) && test.bool())
          {
            transformer.executeChildTemplates(when, sourceNode, mode);
            return;
          }
        }
        else if(Constants.ELEMNAME_OTHERWISE == type)
        {
          found = true;
          // xsl:otherwise              
          transformer.executeChildTemplates(childElem, sourceNode, mode);
          return;
        }
      }
      if(!found)
        
transformer.getMsgMgr().error(XSLTErrorResources.ER_CHOOSE_REQUIRES_WHEN);
    }
    
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      int type = ((ElemTemplateElement)newChild).getXSLToken();
      switch(type)
      {
      case Constants.ELEMNAME_WHEN:
      case Constants.ELEMNAME_OTHERWISE:
        // TODO: Positional checking
        break;
        
      default:
        error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
              //" to " + this.m_elemName);
      }
      return super.appendChild(newChild);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemComment.java
  
  Index: ElemComment.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:comment.
   * <pre>
   * <!ELEMENT xsl:comment %char-template;>
   * <!ATTLIST xsl:comment %space-att;>
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-Comments";>section-Creating-Comments
 in XSLT Specification</a>
   */
  public class ElemComment extends ElemTemplateElement
  {
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_COMMENT;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_COMMENT_STRING;
    }
    
    public void execute(TransformerImpl transformer, 
                       Node sourceNode,
                       QName mode)
      throws SAXException
    {  
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
      
      // Note the content model is:
      // <!ENTITY % instructions "
      // %char-instructions;
      // | xsl:processing-instruction
      // | xsl:comment
      // | xsl:element
      // | xsl:attribute
      // ">
      String data = transformer.transformToString(this, sourceNode, mode);
      transformer.getResultTreeHandler().comment(data);
    }
    
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      int type = ((ElemTemplateElement)newChild).getXSLToken();
      switch(type)
      {
        // char-instructions 
      case Constants.ELEMNAME_TEXTLITERALRESULT:
      case Constants.ELEMNAME_APPLY_TEMPLATES:
      case Constants.ELEMNAME_APPLY_IMPORTS:
      case Constants.ELEMNAME_CALLTEMPLATE:
      case Constants.ELEMNAME_FOREACH:
      case Constants.ELEMNAME_VALUEOF:
      case Constants.ELEMNAME_COPY_OF:
      case Constants.ELEMNAME_NUMBER:
      case Constants.ELEMNAME_CHOOSE:
      case Constants.ELEMNAME_IF:
      case Constants.ELEMNAME_TEXT:
      case Constants.ELEMNAME_COPY:
      case Constants.ELEMNAME_VARIABLE:
      case Constants.ELEMNAME_MESSAGE:
        
        // instructions 
        // case Constants.ELEMNAME_PI:
        // case Constants.ELEMNAME_COMMENT:
        // case Constants.ELEMNAME_ELEMENT:
        // case Constants.ELEMNAME_ATTRIBUTE:
  
        break;
        
      default:
        error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
              //" to " + this.m_elemName);
      }
      return super.appendChild(newChild);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemCopy.java
  
  Index: ElemCopy.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import java.util.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.trace.*;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.transformer.ResultTreeHandler;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:copy.
   * <pre>
   * <!ELEMENT xsl:copy %template;>
   * <!ATTLIST xsl:copy
   *   %space-att;
   *   use-attribute-sets %qnames; #IMPLIED
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#copying";>copying in XSLT 
Specification</a>
   */
  public class ElemCopy extends ElemUse
  {
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_COPY;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_COPY_STRING;
    }
    
    /**
     * The xsl:copy element provides an easy way of copying the current node. 
     * Executing this function creates a copy of the current node into the 
     * result tree. 
     * <p>The namespace nodes of the current node are automatically 
     * copied as well, but the attributes and children of the node are not 
     * automatically copied. The content of the xsl:copy element is a 
     * template for the attributes and children of the created node; 
     * the content is instantiated only for nodes of types that can have 
     * attributes or children (i.e. root nodes and element nodes).</p>
     * <p>The root node is treated specially because the root node of the 
     * result tree is created implicitly. When the current node is the 
     * root node, xsl:copy will not create a root node, but will just use 
     * the content template.</p>
     */
    public void execute(TransformerImpl transformer, 
                       Node sourceNode,
                       QName mode)
      throws SAXException
    {    
      int nodeType = sourceNode.getNodeType();
      if((Node.DOCUMENT_NODE != nodeType))
      {
        ResultTreeHandler rthandler = transformer.getResultTreeHandler();
        
        // TODO: Process the use-attribute-sets stuff
        rthandler.cloneToResultTree( getStylesheet(), sourceNode, false, false, 
false );
        
        if(Node.ELEMENT_NODE == nodeType)
        {
          super.execute(transformer, sourceNode, mode);
          rthandler.processNSDecls(sourceNode);
          transformer.executeChildTemplates(this, sourceNode, mode);
          transformer.getResultTreeHandler().endElement("", "", 
sourceNode.getNodeName());
        }
        else
        {
          if(TransformerImpl.S_DEBUG)
            transformer.getTraceManager().fireTraceEvent(sourceNode, mode, 
this);
        }
      }
      else
      {
        if(TransformerImpl.S_DEBUG)
          transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
        transformer.executeChildTemplates(this, sourceNode, mode);
      }
    }
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemCopyOf.java
  
  Index: ElemCopyOf.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.w3c.dom.traversal.NodeIterator;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.trace.SelectionEvent;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.transformer.TreeWalker2Result;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.transformer.ResultTreeHandler;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:copy-of.
   * <pre>
   * <!ELEMENT xsl:copy-of EMPTY>
   * <!ATTLIST xsl:copy-of select %expr; #REQUIRED>
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#copy-of";>copy-of in XSLT 
Specification</a>
   */
  public class ElemCopyOf extends ElemTemplateElement
  {
    /**
     * The required select attribute contains an expression. 
     */
    public XPath m_selectExpression = null;
    
    /**
     * Set the "select" attribute. 
     * The required select attribute contains an expression. 
     */
    public void setSelect(XPath expr)
    {
      m_selectExpression = expr;
    }
  
    /**
     * Get the "use-attribute-sets" attribute.
     * The required select attribute contains an expression. 
     */
    public XPath getSelect()
    {
      return m_selectExpression;
    }
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_COPY_OF;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_COPY_OF_STRING;
    }
  
    /**
     * The xsl:copy-of element can be used to insert a result tree 
     * fragment into the result tree, without first converting it to 
     * a string as xsl:value-of does (see [7.6.1 Generating Text with 
     * xsl:value-of]). 
     */
    public void execute(TransformerImpl transformer, 
                       Node sourceNode,
                       QName mode)
      throws SAXException
    {    
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      XPathContext xctxt = transformer.getXPathContext();
      XObject value = m_selectExpression.execute(xctxt, sourceNode, this);
      
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireSelectedEvent(sourceNode,
                                      this, "select", m_selectExpression, 
value);
      
      ResultTreeHandler handler = transformer.getResultTreeHandler();
      
      if(null != value)
      {
        int type = value.getType();
        String s;
        switch(type)
        {
        case XObject.CLASS_BOOLEAN:
        case XObject.CLASS_NUMBER:
        case XObject.CLASS_STRING:
          s = value.str();
          handler.characters(s.toCharArray(), 0, s.length());
          break;
          
        case XObject.CLASS_NODESET:
          // System.out.println(value);
          NodeIterator nl = value.nodeset();
          
          // Copy the tree.
          org.apache.xalan.utils.TreeWalker tw 
            = new TreeWalker2Result(transformer, handler, this);
          Node pos;
          while(null != (pos = nl.nextNode()))
          {
            int t = pos.getNodeType();
            // If we just copy the whole document, a startDoc and endDoc get 
            // generated, so we need to only walk the child nodes.
            if(t == Node.DOCUMENT_NODE)
            {
              for(Node child = pos.getFirstChild(); child != null; child = 
child.getNextSibling())
              {
                tw.traverse(child);
              }
            }
            else if(t == Node.ATTRIBUTE_NODE)
            {
              handler.addAttribute((Attr)pos);
            }
            else
            {
              tw.traverse(pos);
            }
          }
          break;
          
        case XObject.CLASS_RTREEFRAG:
          handler.outputResultTreeFragment(value, 
transformer.getXPathContext());
          break;
          
        default:
          s = value.str();
          handler.characters(s.toCharArray(), 0, s.length());
          break;
        }
      }
    }
    
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
            //" to " + this.m_elemName);
      return null;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemElement.java
  
  Index: ElemElement.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.transformer.ResultTreeHandler;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:decimal-format.
   * <pre>
   * <!ELEMENT xsl:element %template;>
   * <!ATTLIST xsl:element 
   *   name %avt; #REQUIRED
   *   namespace %avt; #IMPLIED
   *   use-attribute-sets %qnames; #IMPLIED
   *   %space-att;
   * >
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-Elements-with-xsl:element";>XXX 
in XSLT Specification</a>
   */
  public class ElemElement extends ElemUse
  {
    /**
     * The name attribute is interpreted as an attribute value template. 
     * It is an error if the string that results from instantiating the 
     * attribute value template is not a QName.
     */
    private AVT m_name_avt = null;
    
    /**
     * Set the "name" attribute. 
     * The name attribute is interpreted as an attribute value template. 
     * It is an error if the string that results from instantiating the 
     * attribute value template is not a QName.
     */
    public void setName(AVT v)
    {
      m_name_avt = v;
    }
  
    /**
     * Get the "name" attribute. 
     * The name attribute is interpreted as an attribute value template. 
     * It is an error if the string that results from instantiating the 
     * attribute value template is not a QName.
     */
    public AVT getName()
    {
      return m_name_avt;
    }  
    
    /**
     * If the namespace attribute is present, then it also is interpreted 
     * as an attribute value template. The string that results from 
     * instantiating the attribute value template should be a URI reference. 
     * It is not an error if the string is not a syntactically legal URI 
reference. 
     */
    private AVT m_namespace_avt = null;
    
    /**
     * Set the "namespace" attribute. 
     * If the namespace attribute is present, then it also is interpreted 
     * as an attribute value template. The string that results from 
     * instantiating the attribute value template should be a URI reference. 
     * It is not an error if the string is not a syntactically legal URI 
reference. 
     */
    public void setNamespace(AVT v)
    {
      m_namespace_avt = v;
    }
  
    /**
     * Get the "namespace" attribute. 
     * If the namespace attribute is present, then it also is interpreted 
     * as an attribute value template. The string that results from 
     * instantiating the attribute value template should be a URI reference. 
     * It is not an error if the string is not a syntactically legal URI 
reference. 
     */
    public AVT getNamespace()
    {
      return m_namespace_avt;
    }  
    
    /**
     * Cached prefix value... the use of which is dubious.
     */
    private String m_prefix;
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_ELEMENT;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_ELEMENT_STRING;
    }
  
    /**
     * Create an element in the result tree.
     * The xsl:element element allows an element to be created with a 
     * computed name. The expanded-name of the element to be created 
     * is specified by a required name attribute and an optional namespace 
     * attribute. The content of the xsl:element element is a template 
     * for the attributes and children of the created element.
     */
    public void execute(TransformerImpl transformer,
                       Node sourceNode,
                       QName mode)
      throws SAXException
    {
      ResultTreeHandler rhandler = transformer.getResultTreeHandler();
      XPathContext xctxt = transformer.getXPathContext();
      
      String elemName = m_name_avt.evaluate(xctxt, sourceNode, this,
                                            new StringBuffer());
        // make sure that if a prefix is specified on the attribute name, it is 
valid
      int indexOfNSSep = elemName.indexOf(':');
      String ns ="" ;
      if(indexOfNSSep >= 0)
      {
        String nsprefix = elemName.substring(0, indexOfNSSep);
        // Catch the exception this may cause. We don't want to stop processing.
        try{
          ns = getNamespaceForPrefix(nsprefix);
          // Check if valid QName. Assuming that if the prefix is defined,
          // it is valid.
          if ( indexOfNSSep+1 == elemName.length() ||
             !isValidNCName(elemName.substring(indexOfNSSep + 1)))
          {
            
transformer.getMsgMgr().warn(XSLTErrorResources.WG_ILLEGAL_ATTRIBUTE_NAME, new 
Object[]{elemName});
            elemName = null;
          }
        }
        catch(Exception ex)
        {
          // Could not resolve prefix
          ns = null;
          
transformer.getMsgMgr().warn(XSLTErrorResources.WG_COULD_NOT_RESOLVE_PREFIX, 
new Object[]{nsprefix});
        }
  
      }
      // Check if valid QName
      else if (elemName.length() == 0 || !isValidNCName(elemName))
      {
        
transformer.getMsgMgr().warn(XSLTErrorResources.WG_ILLEGAL_ATTRIBUTE_NAME, new 
Object[]{elemName});
        elemName = null;
      }
      // Only do this if name is valid
      String elemNameSpace = null;
      if(null != elemName && null != ns)
      {
        if(null != m_namespace_avt)
        {
          elemNameSpace = m_namespace_avt.evaluate(xctxt, sourceNode, this,
                                                   new StringBuffer());
  
          if(null != elemNameSpace && elemNameSpace.length()>0)
          {
            // Get the prefix for that attribute in the result namespace.
            String prefix = rhandler.getPrefix(elemNameSpace);
            
            // If we didn't find the prefix mapping, make up a prefix 
            // and have it declared in the result tree.
            if(null == prefix)
            {
              prefix = rhandler.getNewUniqueNSPrefix();
              rhandler.startPrefixMapping(prefix, elemNameSpace);
            }
            // add the prefix to the attribute name.
            elemName = (prefix + ":"+QName.getLocalPart(elemName));       
          }
        }
  
        rhandler.startElement(elemNameSpace, QName.getLocalPart(elemName), 
elemName);
      }
      // Instantiate content of xsl:element. Note that if startElement was not
      // called(ie: if invalid element name, the element's attributes will be
      // excluded because transformer.m_pendingElementName will be null.
      super.execute(transformer, sourceNode, mode);
      
      // Add namespace declarations.
      executeNSDecls(transformer);
  
      transformer.executeChildTemplates(this, sourceNode, mode);
  
      // Now end the element if name was valid
      if(null != elemName && null != ns)
      {
        rhandler.endElement("", "", elemName);
      }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemEmpty.java
  
  Index: ElemEmpty.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="internal"/>
   * Simple empty elem to push on the stack when nothing 
   * else got pushed, so that pop() works correctly.
   */
  public class ElemEmpty extends ElemTemplateElement
  {
    public ElemEmpty()
    {
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemExtensionCall.java
  
  Index: ElemExtensionCall.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import java.io.*;
  import java.util.*;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.xml.sax.helpers.*;
  import java.util.StringTokenizer;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.utils.NameSpace;
  import org.apache.xalan.utils.StringToStringTable;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.utils.MutableAttrListImpl;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.extensions.ExtensionNSHandler;
  import org.apache.xalan.extensions.ExtensionsTable;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement an extension element.
   * @see <a 
href="http://www.w3.org/TR/xslt#extension-element";>extension-element in XSLT 
Specification</a>
   */
  public class ElemExtensionCall extends ElemLiteralResult
  {
    // ExtensionNSHandler nsh;
    String m_extns;
    String m_extHandlerLookup;
    String localPart;
    Attributes m_attrs;
    // public Vector m_avts = null;
    transient boolean isAvailable = false;
    String m_lang;
    String m_srcURL;
    String m_scriptSrc;
    Class m_javaClass = null;
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_EXTENSIONCALL;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      // TODO: Need prefix.
      return localPart;
    }
  
    /**
     * Tell if this extension element is available for execution.
     */
    public boolean elementIsAvailable()
    {
      return isAvailable;
    }
  
    /**
     * Execute an extension.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      try
      {
        transformer.getResultTreeHandler().flushPending();
        XPathContext liaison = ((XPathContext)transformer.getXPathContext());
        ExtensionsTable etable = liaison.getExtensionsTable();
        ExtensionNSHandler nsh = etable.get(m_extns);
  
        if(null == nsh)
        {
          nsh = new ExtensionNSHandler (m_extns);
          nsh.setScript (m_lang, m_srcURL, m_scriptSrc);
          etable.addExtensionElementNamespace(m_extns, nsh);
        }
  
        nsh.processElement (localPart, this,
                            transformer, 
                            getStylesheet(),
                            sourceNode.getOwnerDocument(), 
                            sourceNode, mode, m_javaClass, this);
      }
      catch(Exception e)
      {
        String msg = e.getMessage();
        if(null != msg)
        {
          if(msg.startsWith("Stopping after fatal error:"))
          {
            msg = msg.substring("Stopping after fatal error:".length());
          }
          
transformer.getMsgMgr().message(XSLMessages.createMessage(XSLTErrorResources.ER_CALL_TO_EXT_FAILED,
 new Object[]{msg}), false); //"Call to extension element failed: "+msg);
          // e.printStackTrace();
          // System.exit(-1);
        }
        // transformer.message(msg);
        isAvailable = false; 
        for (ElemTemplateElement child = m_firstChild; child != null; child = 
child.m_nextSibling) 
        {
          if(child.getXSLToken() == Constants.ELEMNAME_FALLBACK)
          {
            child.execute(transformer, sourceNode, mode);
          }
        }
      }
    }
    
    /**
     * Return the raw value of the attribute.
     */
    public String getAttribute(String name)
    {
      String value = m_attrs.getValue(name);  
      return value;
    }
  
    /**
     * Return the value of the attribute interpreted as an Attribute 
     * Value Template (in other words, you can use curly expressions 
     * such as href="http://{website}";.
     */
    public String getAttribute(String rawName, Node sourceNode, TransformerImpl 
transformer)
      throws SAXException
    {
      AVT avt = getLiteralResultAttribute(rawName);
      if(avt.getRawName().equals(rawName))
      {
        XPathContext xctxt = transformer.getXPathContext();
        return avt.evaluate(xctxt, sourceNode, this,
                            new StringBuffer());        
      }
      return null;  
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemFallback.java
  
  Index: ElemFallback.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.trace.SelectionEvent;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:fallback.
   * <pre>
   * <!ELEMENT xsl:fallback %template;>
   * <!ATTLIST xsl:fallback %space-att;>
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#fallback";>fallback in XSLT 
Specification</a>
   */
  public class ElemFallback extends ElemTemplateElement
  {
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_FALLBACK;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_FALLBACK_STRING;
    }
  
    /**
     * Execute the fallback elements.
     * When an XSLT transformer performs fallback for an instruction 
     * element, if the instruction element has one or more xsl:fallback 
     * children, then the content of each of the xsl:fallback children 
     * must be instantiated in sequence; otherwise, an error must 
     * be signaled. The content of an xsl:fallback element is a template.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {    
      if(Constants.ELEMNAME_EXTENSIONCALL == m_parentNode.getXSLToken())
      {
        ElemExtensionCall parent = (ElemExtensionCall)m_parentNode; 
        if(!parent.elementIsAvailable())
        {
          if(TransformerImpl.S_DEBUG)
            transformer.getTraceManager().fireTraceEvent(sourceNode, mode, 
this);
  
          // XPathContext xctxt = transformer.getXPathContext();
          transformer.executeChildTemplates(this, sourceNode, mode);
        }
      }
      else
      {
        // Should never happen
        System.out.println("Error!  parent of xsl:fallback must be an extension 
element!");
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemForEach.java
  
  Index: ElemForEach.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import java.util.Vector;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:for-each.
   * <pre>
   * <!ELEMENT xsl:for-each
   *  (#PCDATA
   *   %instructions;
   *   %result-elements;
   *   | xsl:sort)*
   * >
   * 
   * <!ATTLIST xsl:for-each
   *   select %expr; #REQUIRED
   *   %space-att;
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#for-each";>for-each in XSLT 
Specification</a>
   */
  public class ElemForEach extends ElemTemplateElement
  {
    /**
     * Construct a element representing xsl:for-each.
     */
    public ElemForEach()
    {
    }
  
    /**
     * The "select" expression.
     */
    private XPath m_selectExpression = null;
    
    /**
     * Set the "select" attribute.
     */
    public void setSelect(XPath xpath)
    {
      m_selectExpression = xpath;
    }
  
    /**
     * Set the "select" attribute.
     */
    public XPath getSelect()
    {
      return m_selectExpression;
    }
  
    private Vector m_sortElems = null;
    
    /**
     * Get the count xsl:sort elements associated with this element.
     * @return The number of xsl:sort elements.
     */
    public int getSortElemCount()
    {
      return (m_sortElems == null) ? 0 : m_sortElems.size();
    }
    
    /**
     * Get a xsl:sort element associated with this element.
     */
    public ElemSort getSortElem(int i)
    {
      return (ElemSort)m_sortElems.elementAt(i);
    }
    
    /**
     * Set a xsl:sort element associated with this element.
     */
    public void setSortElem(ElemSort sortElem)
    {
      if(null == m_sortElems)
        m_sortElems = new Vector();
      m_sortElems.addElement(sortElem);
    }
  
    
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_FOREACH;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_FOREACH_STRING;
    }
  
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {    
      transformer.pushCurrentTemplateRuleIsNull(true);
  
      try
      {
        if(TransformerImpl.S_DEBUG)
          transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
        if(null != sourceNode)
        {      
          transformer.transformSelectedNodes(getStylesheetComposed(), 
                                                this,
                                                this,
                                                sourceNode, mode,
                                                m_selectExpression, 
                                                
transformer.getXPathContext().getVarStack().getCurrentStackFrameIndex());
        }
        else // if(null == sourceNode)
        {
          transformer.getMsgMgr().error(this, sourceNode, 
XSLTErrorResources.ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES);
          //"sourceNode is null in handleApplyTemplatesInstruction!");
        }
      }
  
      finally
      {
        transformer.popCurrentTemplateRuleIsNull();
      }
    }
    
    /**
     * Add a child to the child list.
     * <!ELEMENT xsl:apply-templates (xsl:sort|xsl:with-param)*>
     * <!ATTLIST xsl:apply-templates
     *   select %expr; "node()"
     *   mode %qname; #IMPLIED
     * >
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      int type = ((ElemTemplateElement)newChild).getXSLToken();
      if(Constants.ELEMNAME_SORT == type)
      {
        setSortElem((ElemSort)newChild);
      }
  
      return super.appendChild(newChild);
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/templates/ElemIf.java
  
  Index: ElemIf.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.trace.SelectionEvent;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:if.
   * <pre>
   * <!ELEMENT xsl:if %template;>
   * <!ATTLIST xsl:if
   *   test %expr; #REQUIRED
   *   %space-att;
   * >
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Conditional-Processing-with-xsl:if";>XXX 
in XSLT Specification</a>
   */
  public class ElemIf extends ElemTemplateElement
  {
    /**
     * The xsl:if element must have a test attribute, which specifies an 
expression. 
     */
    private XPath m_test = null;
    
    /**
     * Set the "test" attribute. 
     * The xsl:if element must have a test attribute, which specifies an 
expression. 
     */
    public void setTest(XPath v)
    {
      m_test = v;
    }
  
    /**
     * Get the "test" attribute. 
     * The xsl:if element must have a test attribute, which specifies an 
expression. 
     */
    public XPath getTest()
    {
      return m_test;
    }
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_IF;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_IF_STRING;
    }
    
    /**
     * Conditionally execute a sub-template.
     * The expression is evaluated and the resulting object is converted 
     * to a boolean as if by a call to the boolean function. If the result 
     * is true, then the content template is instantiated; otherwise, nothing 
     * is created.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {    
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      XPathContext xctxt = transformer.getXPathContext();
      XObject test = m_test.execute(xctxt, sourceNode, this);
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireSelectedEvent(sourceNode, this, 
"test", m_test, test);
      if(test.bool())
      {
        transformer.executeChildTemplates(this, sourceNode, mode);
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemLiteralResult.java
  
  Index: ElemLiteralResult.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.xml.sax.helpers.*;
  import java.util.StringTokenizer;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.utils.NameSpace;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.utils.StringToStringTable;
  import org.apache.xalan.utils.NameSpace;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.transformer.ResultTreeHandler;
  
  import java.io.*;
  import java.util.*;
  
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement a Literal Result Element.
   * @see <a 
href="http://www.w3.org/TR/xslt#literal-result-element";>literal-result-element 
in XSLT Specification</a>
   */
  public class ElemLiteralResult extends ElemUse
  {
    /**
     * The created element node will have the attribute nodes 
     * that were present on the element node in the stylesheet tree, 
     * other than attributes with names in the XSLT namespace.
     */
    private Vector m_avts = null;
    
    /**
     * Set a literal result attribute.
     */
    public void addLiteralResultAttribute(AVT avt)
    {
      if(null == m_avts)
        m_avts = new Vector();
      m_avts.addElement(avt);
    }
    
    /**
     * Get a literal result attribute by name.
     */
    public AVT getLiteralResultAttribute(String name)
    {
      if(null != m_avts)
      {
        int nAttrs = m_avts.size();
        for(int i = (nAttrs-1); i >= 0; i--)
        {
          AVT avt = (AVT)m_avts.elementAt(i);
          if(avt.getRawName().equals(name))
          {
            return avt;      
          }
        } // end for
      }
      return null;  
    }
    
    /**
     * The namespace of the element to be created.
     */
    private String m_namespace;
    
    /**
     * Set the m_namespace of the LRE.
     */
    public void setNamespace(String ns)
    {
      m_namespace = ns;
    }
  
    /**
     * Get the m_namespace of the Literal Result Element.
     */
    public String getNamespace()
    {
      return m_namespace;
    }
  
    /**
     * The raw name of the element to be created.
     */
    private String m_localName;
    
    /**
     * Set the local name of the LRE.
     */
    public void setLocalName(String localName)
    {
      m_localName = localName;
    }
  
    /**
     * Get the local name of the Literal Result Element.
     */
    public String getLocalName()
    {
      return m_localName;
    }
  
    
    /**
     * The raw name of the element to be created.
     */
    private String m_rawName;
    
    /**
     * Set the raw name of the LRE.
     */
    public void setRawName(String rawName)
    {
      m_rawName = rawName;
    }
  
    /**
     * Get the raw name of the Literal Result Element.
     */
    public String getRawName()
    {
      return m_rawName;
    }
  
    /**
     * Move this to the processer package.
     */
    public String m_extensionElementPrefixes[] = null;
    
    /**
     * This is in support of the exclude-result-prefixes 
     * attribute.  Move this to the processer package.
     */
    protected StringToStringTable m_excludeResultPrefixes = null;
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_LITERALRESULT;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      // TODO: Need prefix.
      return m_rawName;
    }
  
    /**
     * Copy a Literal Result Element into the Result tree, copy the 
     * non-excluded namespace attributes, copy the attributes not 
     * of the XSLT namespace, and execute the children of the LRE.
     * @see <a 
href="http://www.w3.org/TR/xslt#literal-result-element";>literal-result-element 
in XSLT Specification</a>
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      ResultTreeHandler rhandler = transformer.getResultTreeHandler();
      
      rhandler.startElement(getNamespace(), getLocalName(), getRawName());
      
      // Process any possible attributes from xsl:use-attribute-sets first
      super.execute(transformer, sourceNode, mode);
      
      // Add namespace declarations.
      executeNSDecls(transformer);
      
      // Process the list of avts next
      if(null != m_avts)
      {
        int nAttrs = m_avts.size();
        for(int i = (nAttrs-1); i >= 0; i--)
        {
          AVT avt = (AVT)m_avts.elementAt(i);
          XPathContext xctxt = transformer.getXPathContext();
          String stringedValue = avt.evaluate(xctxt, sourceNode, this,
                                              new StringBuffer());
          
          if(null != stringedValue)
          {
            // Important Note: I'm not going to check for excluded namespace 
            // prefixes here.  It seems like it's to expensive, and I'm not 
            // even sure this is right.  But I could be wrong, so this needs 
            // to be tested against other implementations.
            rhandler.addAttribute(avt.getURI(), avt.getName(),
                                  avt.getRawName(), 
                                  "CDATA", stringedValue);
          }
        } // end for
      }        
      
      // Now process all the elements in this subtree
      // TODO: Process m_extensionElementPrefixes && m_attributeSetsNames
      transformer.executeChildTemplates(this, sourceNode, mode);
      rhandler.endElement (getNamespace(), getLocalName(), getRawName());
    }
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemMessage.java
  
  Index: ElemMessage.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:message.
   * <pre>
   * <!ELEMENT xsl:message %template;>
   * <!ATTLIST xsl:message
   *   %space-att;
   *   terminate (yes|no) "no"
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#message";>message in XSLT 
Specification</a>
   */
  public class ElemMessage extends ElemTemplateElement
  {
    /**
     * If the terminate attribute has the value yes, then the 
     * XSLT transformer should terminate processing after sending 
     * the message. The default value is no.
     */
    private boolean m_terminate = Constants.ATTRVAL_NO;  // default value       
    
    /**
     * Set the "terminate" attribute. 
     * If the terminate attribute has the value yes, then the 
     * XSLT transformer should terminate processing after sending 
     * the message. The default value is no.
     */
    public void setTerminate(boolean v)
    {
      m_terminate = v;
    }
  
    /**
     * Get the "terminate" attribute. 
     * If the terminate attribute has the value yes, then the 
     * XSLT transformer should terminate processing after sending 
     * the message. The default value is no.
     */
    public boolean getTerminate()
    {
      return m_terminate;
    }
    
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_MESSAGE;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_MESSAGE_STRING;
    }
  
    
    /**
     * Send a message to diagnostics.
     * The xsl:message instruction sends a message in a way that 
     * is dependent on the XSLT transformer. The content of the xsl:message 
     * instruction is a template. The xsl:message is instantiated by 
     * instantiating the content to create an XML fragment. This XML 
     * fragment is the content of the message.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {    
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      String data = transformer.transformToString(this, sourceNode, mode);
      transformer.getMsgMgr().message(data, m_terminate);    
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemNumber.java
  
  Index: ElemNumber.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.w3c.dom.traversal.NodeIterator;
  import org.xml.sax.*;
  
  import java.util.*;
  import java.text.NumberFormat;
  import java.text.DecimalFormat;
  
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.*;
  import org.apache.xalan.transformer.DecimalToRoman;
  import org.apache.xalan.transformer.CountersTable;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.utils.NodeVector;
  // import org.apache.xalan.dtm.*;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:number.
   * <pre>
   * <!ELEMENT xsl:number EMPTY>
   * <!ATTLIST xsl:number
   *    level (single|multiple|any) "single"
   *    count %pattern; #IMPLIED
   *    from %pattern; #IMPLIED
   *    value %expr; #IMPLIED
   *    format %avt; '1'
   *    lang %avt; #IMPLIED
   *    letter-value %avt; #IMPLIED
   *    grouping-separator %avt; #IMPLIED
   *    grouping-size %avt; #IMPLIED
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#number";>number in XSLT 
Specification</a>
   */
  public class ElemNumber extends ElemTemplateElement
  {
    /**
     * Only nodes are counted that match this pattern.
     */
    private XPath m_countMatchPattern = null;
    
    /**
     * Set the "count" attribute. 
     * The count attribute is a pattern that specifies what nodes 
     * should be counted at those levels. If count attribute is not 
     * specified, then it defaults to the pattern that matches any 
     * node with the same node type as the current node and, if the 
     * current node has an expanded-name, with the same expanded-name 
     * as the current node.
     */
    public void setCount(XPath v)
    {
      m_countMatchPattern = v;
    }
  
    /**
     * Get the "count" attribute. 
     * The count attribute is a pattern that specifies what nodes 
     * should be counted at those levels. If count attribute is not 
     * specified, then it defaults to the pattern that matches any 
     * node with the same node type as the current node and, if the 
     * current node has an expanded-name, with the same expanded-name 
     * as the current node.
     */
    public XPath getCount()
    {
      return m_countMatchPattern;
    }
    
    /**
     * Specifies where to count from.
     * For level="single" or level="multiple":
     * Only ancestors that are searched are 
     * those that are descendants of the nearest ancestor that matches 
     * the from pattern.
     * For level="any:
     * Only nodes after the first node before the 
     * current node that match the from pattern are considered.
     */
    private XPath m_fromMatchPattern = null;
    
    /**
     * Set the "from" attribute. Specifies where to count from.
     * For level="single" or level="multiple":
     * Only ancestors that are searched are 
     * those that are descendants of the nearest ancestor that matches 
     * the from pattern.
     * For level="any:
     * Only nodes after the first node before the 
     * current node that match the from pattern are considered.
     */
    public void setFrom(XPath v)
    {
      m_fromMatchPattern = v;
    }
  
    /**
     * Get the "from" attribute. 
     * For level="single" or level="multiple":
     * Only ancestors that are searched are 
     * those that are descendants of the nearest ancestor that matches 
     * the from pattern.
     * For level="any:
     * Only nodes after the first node before the 
     * current node that match the from pattern are considered.
     */
    public XPath getFrom()
    {
      return m_fromMatchPattern;
    }
    
    /**
     * When level="single", it goes up to the first node in the 
ancestor-or-self axis 
     * that matches the count pattern, and constructs a list of length one 
containing 
     * one plus the number of preceding siblings of that ancestor that match 
the count 
     * pattern. If there is no such ancestor, it constructs an empty list. If 
the from 
     * attribute is specified, then the only ancestors that are searched are 
those 
     * that are descendants of the nearest ancestor that matches the from 
pattern. 
     * Preceding siblings has the same meaning here as with the 
preceding-sibling axis.
     * 
     * When level="multiple", it constructs a list of all ancestors of the 
current node 
     * in document order followed by the element itself; it then selects from 
the list 
     * those nodes that match the count pattern; it then maps each node in the 
list to 
     * one plus the number of preceding siblings of that node that match the 
count pattern. 
     * If the from attribute is specified, then the only ancestors that are 
searched are 
     * those that are descendants of the nearest ancestor that matches the from 
pattern. 
     * Preceding siblings has the same meaning here as with the 
preceding-sibling axis.
     * 
     * When level="any", it constructs a list of length one containing the 
number of 
     * nodes that match the count pattern and belong to the set containing the 
current 
     * node and all nodes at any level of the document that are before the 
current node 
     * in document order, excluding any namespace and attribute nodes (in other 
words 
     * the union of the members of the preceding and ancestor-or-self axes). If 
the 
     * from attribute is specified, then only nodes after the first node before 
the 
     * current node that match the from pattern are considered.
     */
    private int m_level = Constants.NUMBERLEVEL_SINGLE;
    
    /**
     * Set the "level" attribute. 
     * The level attribute specifies what levels of the source tree should 
     * be considered; it has the values single, multiple or any. The default 
     * is single.
     */
    public void setLevel(int v)
    {
      m_level = v;
    }
  
    /**
     * Get the "level" attribute. 
     * The level attribute specifies what levels of the source tree should 
     * be considered; it has the values single, multiple or any. The default 
     * is single.
     */
    public int getLevel()
    {
      return m_level;
    }
  
    /**
     * The value attribute contains an expression. The expression is evaluated 
     * and the resulting object is converted to a number as if by a call to the 
     * number function. 
     */
    private XPath m_valueExpr = null;
    
    /**
     * Set the "value" attribute. 
     * The value attribute contains an expression. The expression is evaluated 
     * and the resulting object is converted to a number as if by a call to the 
     * number function. 
     */
    public void setValue(XPath v)
    {
      m_valueExpr = v;
    }
  
    /**
     * Get the "value" attribute. 
     * The value attribute contains an expression. The expression is evaluated 
     * and the resulting object is converted to a number as if by a call to the 
     * number function. 
     */
    public XPath getValue()
    {
      return m_valueExpr;
    }
    
    /**
     * The "format" attribute is used to control conversion of a list of 
     * numbers into a string. 
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    private AVT m_format_avt = null;
    
    /**
     * Set the "format" attribute. 
     * The "format" attribute is used to control conversion of a list of 
     * numbers into a string. 
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public void setFormat(AVT v)
    {
      m_format_avt = v;
    }
  
    /**
     * Get the "format" attribute. 
     * The "format" attribute is used to control conversion of a list of 
     * numbers into a string. 
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public AVT getFormat()
    {
      return m_format_avt;
    }  
    
    /**
     * When numbering with an alphabetic sequence, the lang attribute 
     * specifies which language's alphabet is to be used.
     */
    private AVT m_lang_avt = null;
    
    /**
     * Set the "lang" attribute. 
     * When numbering with an alphabetic sequence, the lang attribute 
     * specifies which language's alphabet is to be used; it has the same 
     * range of values as xml:lang [XML]; if no lang value is specified, 
     * the language should be determined from the system environment. 
     * Implementers should document for which languages they support numbering.
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public void setLang(AVT v)
    {
      m_lang_avt = v;
    }
  
    /**
     * Get the "lang" attribute. 
     * When numbering with an alphabetic sequence, the lang attribute 
     * specifies which language's alphabet is to be used; it has the same 
     * range of values as xml:lang [XML]; if no lang value is specified, 
     * the language should be determined from the system environment. 
     * Implementers should document for which languages they support numbering.
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public AVT getLang()
    {
      return m_lang_avt;
    }  
    
    /**
     * The letter-value attribute disambiguates between numbering 
     * sequences that use letters. 
     */
    private AVT m_lettervalue_avt = null;
    
    /**
     * Set the "letter-value" attribute. 
     * The letter-value attribute disambiguates between numbering sequences 
     * that use letters.
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public void setLetterValue(AVT v)
    {
      m_lettervalue_avt = v;
    }
  
    /**
     * Get the "letter-value" attribute. 
     * The letter-value attribute disambiguates between numbering sequences 
     * that use letters.
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public AVT getLetterValue()
    {
      return m_lettervalue_avt;
    }  
      
    /**
     * The grouping-separator attribute gives the separator 
     * used as a grouping (e.g. thousands) separator in decimal 
     * numbering sequences.
     */
    private AVT m_groupingSeparator_avt = null;
    
    /**
     * Set the "grouping-separator" attribute. 
     * The grouping-separator attribute gives the separator 
     * used as a grouping (e.g. thousands) separator in decimal 
     * numbering sequences.
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public void setGroupingSeparator(AVT v)
    {
      m_groupingSeparator_avt = v;
    }
  
    /**
     * Get the "grouping-separator" attribute. 
     * The grouping-separator attribute gives the separator 
     * used as a grouping (e.g. thousands) separator in decimal 
     * numbering sequences.
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public AVT getGroupingSeparator()
    {
      return m_groupingSeparator_avt;
    }  
      
    /**
     * The optional grouping-size specifies the size (normally 3) of the 
grouping. 
     */
    private AVT m_groupingSize_avt = null;
    
    /**
     * Set the "grouping-size" attribute. 
     * The optional grouping-size specifies the size (normally 3) of the 
grouping. 
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public void setGroupingSize(AVT v)
    {
      m_groupingSize_avt = v;
    }
  
    /**
     * Get the "grouping-size" attribute. 
     * The optional grouping-size specifies the size (normally 3) of the 
grouping. 
     * @see <a href="http://www.w3.org/TR/xslt#convert";>convert in XSLT 
Specification</a>
     */
    public AVT getGroupingSize()
    {
      return m_groupingSize_avt;
    }  
    
    /**
     * Shouldn't this be in the transformer?  Big worries about threads...
     */
    private XSLTResourceBundle thisBundle;
  
    /**
     * Table to help in converting decimals to roman numerals.
     * @see TransformerImpl#DecimalToRoman
     * @see TransformerImpl#long2roman
     */
    private final static DecimalToRoman m_romanConvertTable[] =
    {
      new DecimalToRoman(1000, "M", 900, "CM"),
      new DecimalToRoman(500, "D", 400, "CD"),
      new DecimalToRoman(100L, "C", 90L, "XC"),
      new DecimalToRoman(50L, "L", 40L, "XL"),
      new DecimalToRoman(10L, "X", 9L, "IX"),
      new DecimalToRoman(5L, "V", 4L, "IV"),
      new DecimalToRoman(1L, "I", 1L, "I")
    };
  
    /**
     * Chars for converting integers into alpha counts.
     * @see TransformerImpl#int2alphaCount
     */
    private static char[] m_alphaCountTable = null;
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_NUMBER;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_NUMBER_STRING;
    }
  
    /**
     * Execute an xsl:number instruction. The xsl:number element is 
     * used to insert a formatted number into the result tree. 
     */
    public void execute(TransformerImpl transformer,
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      String countString = getCountString(transformer, sourceNode);
  
      transformer.getResultTreeHandler().characters(countString.toCharArray(), 
0, countString.length());
    }
  
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
      //" to " + this.m_elemName);
      return null;
    }
  
  
    /**
     * Given a 'from' pattern (ala xsl:number), a match pattern
     * and a context, find the first ancestor that matches the
     * pattern (including the context handed in).
     * @param fromMatchPattern The ancestor must match this pattern.
     * @param countMatchPattern The ancestor must also match this pattern.
     * @param context The node that "." expresses.
     * @param namespaceContext The context in which namespaces in the
     * queries are supposed to be expanded.
     */
    Node findAncestor(XPathContext xctxt, XPath fromMatchPattern, 
                      XPath countMatchPattern,
                      Node context,
                      Element namespaceContext)
      throws org.xml.sax.SAXException
    {
      while(null != context)
      {
        if(null != fromMatchPattern)
        {
          if(fromMatchPattern.getMatchScore(xctxt, context) != 
XPath.MATCH_SCORE_NONE)
          {
            //context = null;
            break;
          }
        }
  
        if(null != countMatchPattern)
        {
          if(countMatchPattern.getMatchScore(xctxt, context) != 
XPath.MATCH_SCORE_NONE)
          {
            break;
          }
        }
  
        context = xctxt.getDOMHelper().getParentOfNode(context);
      }
      return context;    
    }
  
  
    /**
     * Given a 'from' pattern (ala xsl:number), a match pattern
     * and a context, find the first ancestor that matches the
     * pattern (including the context handed in).
     * @param matchPatternString The match pattern.
     * @param node The node that "." expresses.
     * @param namespaceContext The context in which namespaces in the
     * queries are supposed to be expanded.
     */
    private Node findPrecedingOrAncestorOrSelf(XPathContext xctxt, 
                                       XPath fromMatchPattern, 
                                       XPath countMatchPattern,
                                       Node context,
                                       Element namespaceContext)
      throws org.xml.sax.SAXException
    {
      while(null != context)
      {
        if(null != fromMatchPattern)
        {
          if(fromMatchPattern.getMatchScore(xctxt, context) != 
XPath.MATCH_SCORE_NONE)
          {
            context = null;
            break;
          }
        }
  
        if(null != countMatchPattern)
        {
          if(countMatchPattern.getMatchScore(xctxt, context) != 
XPath.MATCH_SCORE_NONE)
          {
            break;
          }
        }
  
        Node prevSibling = context.getPreviousSibling();
        if(null == prevSibling)
        {
          context = xctxt.getDOMHelper().getParentOfNode(context);
        }
        else
        {
          // Now go down the chain of children of this sibling 
          context = prevSibling.getLastChild();
          if (context == null)
            context = prevSibling;
        }
      }
      return context;
    }
    
    /**
     * Get the count match pattern, or a default value.
     */
    XPath getCountMatchPattern(XPathContext support, Node contextNode)
      throws org.xml.sax.SAXException
    {
      XPath countMatchPattern = m_countMatchPattern;
      if(null == countMatchPattern)
      {
        XPathFactory xpathFactory = SimpleNodeLocator.factory();
        XPathParser xpathProcessor = new XPathParser();
        countMatchPattern = xpathFactory.create();
        switch( contextNode.getNodeType())
        {
        case Node.ELEMENT_NODE:
          // countMatchPattern = 
m_stylesheet.createMatchPattern(contextNode.getNodeName(), this);
          xpathProcessor.initMatchPattern(countMatchPattern, 
contextNode.getNodeName(), this);
          break;
        case Node.ATTRIBUTE_NODE:
          // countMatchPattern = 
m_stylesheet.createMatchPattern("@"+contextNode.getNodeName(), this);
          xpathProcessor.initMatchPattern(countMatchPattern, 
"@"+contextNode.getNodeName(), this);
          break;
        case Node.CDATA_SECTION_NODE:
        case Node.TEXT_NODE:
          // countMatchPattern = m_stylesheet.createMatchPattern("text()", 
this);
          xpathProcessor.initMatchPattern(countMatchPattern, "text()", this);
          break;
        case Node.COMMENT_NODE:
          // countMatchPattern = m_stylesheet.createMatchPattern("comment()", 
this);
          xpathProcessor.initMatchPattern(countMatchPattern, "comment()", this);
          break;
        case Node.DOCUMENT_NODE:
          // countMatchPattern = m_stylesheet.createMatchPattern("/", this);
          xpathProcessor.initMatchPattern(countMatchPattern, "/", this);
          break;
        case Node.PROCESSING_INSTRUCTION_NODE:
          // countMatchPattern = 
m_stylesheet.createMatchPattern("pi("+contextNode.getNodeName()+")", this);
          xpathProcessor.initMatchPattern(countMatchPattern, 
"pi("+contextNode.getNodeName()+")", this);
          break;
        default:
          countMatchPattern = null;
        }
      }
      return countMatchPattern;
    }
    
    /**
     * Given an XML source node, get the count according to the
     * parameters set up by the xsl:number attributes.
     * @param transformer The node being counted.
     * @param sourceNode The source node being counted.
     */
    String getCountString(TransformerImpl transformer, Node sourceNode)
      throws SAXException
    {
      int[] list = null;
      XPathContext xctxt = transformer.getXPathContext();
      CountersTable ctable = transformer.getCountersTable();
  
      if(null != m_valueExpr)
      {
        XObject countObj = m_valueExpr.execute(xctxt, sourceNode, this);
        int count = (int)countObj.num();
        list = new int[1];
        list[0] = count;
      }
      else
      {
        if(Constants.NUMBERLEVEL_ANY == m_level)
        {
          list = new int[1];
          list[0] = ctable.countNode(xctxt, this, sourceNode);
        }
        else
        {
          NodeVector ancestors = getMatchingAncestors(xctxt, sourceNode,
                                                    
Constants.NUMBERLEVEL_SINGLE == m_level);
          int lastIndex = ancestors.size() - 1;
          if(lastIndex >= 0)
          {
            list = new int[lastIndex+1];
            for(int i = lastIndex; i >= 0; i--)
            {
              Node target = ancestors.elementAt(i);
              list[lastIndex-i] = ctable.countNode(xctxt, this, target);
            }
          }
        }
      }
      
      return (null != list) ? formatNumberList(transformer, list, sourceNode) : 
"";
    }
    
    /**
     * Get the previous node to be counted.
     */
    public Node getPreviousNode(XPathContext xctxt, Node pos)
      throws SAXException
    {    
      XPath countMatchPattern = getCountMatchPattern(xctxt, pos);
      if(Constants.NUMBERLEVEL_ANY == m_level)
      {
        XPath fromMatchPattern = m_fromMatchPattern;
  
        // Do a backwards document-order walk 'till a node is found that 
matches 
        // the 'from' pattern, or a node is found that matches the 'count' 
pattern, 
        // or the top of the tree is found.
        while(null != pos)
        {            
          // Get the previous sibling, if there is no previous sibling, 
          // then count the parent, but if there is a previous sibling, 
          // dive down to the lowest right-hand (last) child of that sibling.
          Node next = pos.getPreviousSibling();
          if(null == next)
          {
            next = pos.getParentNode();
            if((null != next) && ((((null != fromMatchPattern) &&
                                    (fromMatchPattern.getMatchScore(xctxt, 
next) !=
                                     XPath.MATCH_SCORE_NONE))) || 
                                  (next.getNodeType() == Node.DOCUMENT_NODE)))
            {
              pos = null; // return null from function.
              break; // from while loop
            }
          }
          else
          {
            // dive down to the lowest right child.
            Node child = next;
            while(null != child)
            {
              child = next.getLastChild();
              if(null != child)
                next = child;
            }
          }
          pos = next;
          
          if((null != pos) && ((null == countMatchPattern) ||
                               (countMatchPattern.getMatchScore(xctxt, pos) !=
                                XPath.MATCH_SCORE_NONE)))
          {
            break;
          }
        }
      }
      else // NUMBERLEVEL_MULTI or NUMBERLEVEL_SINGLE
      {
        while(null != pos)
        {            
          pos = pos.getPreviousSibling();
          if((null != pos) && ((null == countMatchPattern) ||
                               (countMatchPattern.getMatchScore(xctxt, pos) !=
                                XPath.MATCH_SCORE_NONE)))
          {
            break;
          }
        }
      }
      return pos;
    }
    
    /**
     * Get the target node that will be counted..
     */
    public Node getTargetNode(XPathContext xctxt, Node sourceNode)
      throws SAXException
    {
      Node target = null;
      XPath countMatchPattern = getCountMatchPattern(xctxt, sourceNode);
      if(Constants.NUMBERLEVEL_ANY == m_level)
      {
        target= findPrecedingOrAncestorOrSelf(xctxt, m_fromMatchPattern, 
                                              countMatchPattern,
                                              sourceNode, this);
        
      }
      else
      {
        target = findAncestor(xctxt, m_fromMatchPattern,
                              countMatchPattern, sourceNode, this);
      }
      return target;
    }
  
  
  
  
    /**
     * Get the ancestors, up to the root, that match the
     * pattern.
     * @param patterns if non-null, count only nodes
     * that match this pattern, if null count all ancestors.
     * @param node Count this node and it's ancestors.
     * @return The number of ancestors that match the pattern.
     */
    NodeVector getMatchingAncestors(XPathContext xctxt, 
                                         Node node, 
                                         boolean stopAtFirstFound)
      throws org.xml.sax.SAXException
    {
      NodeSet ancestors = new NodeSet();
      XPath countMatchPattern = getCountMatchPattern(xctxt, node);
      while( null != node )
      {
        if((null != m_fromMatchPattern) &&
           (m_fromMatchPattern.getMatchScore(xctxt, node) !=
            XPath.MATCH_SCORE_NONE))
        { 
          // The following if statement gives level="single" different 
          // behavior from level="multiple", which seems incorrect according 
          // to the XSLT spec.  For now we are leaving this in to replicate 
          // the same behavior in XT, but, for all intents and purposes we 
          // think this is a bug, or there is something about level="single" 
          // that we still don't understand.
          if(!stopAtFirstFound)
            break;
        }  
        
        if(null == countMatchPattern)
          System.out.println("Programmers error! countMatchPattern should never 
be null!");
        
        if(countMatchPattern.getMatchScore(xctxt, node) !=
           XPath.MATCH_SCORE_NONE)
        {
          ancestors.addElement(node);
          if(stopAtFirstFound)
            break;
        }
        
        node = xctxt.getDOMHelper().getParentOfNode(node);
      }
      return ancestors;
    } // end getMatchingAncestors method
  
  
    /**
     * Get the locale we should be using.
     */
    Locale getLocale(TransformerImpl transformer, Node contextNode)
      throws SAXException
    {
      Locale locale = null;
      if(null != m_lang_avt)
      {
        String langValue = m_lang_avt.evaluate(transformer.getXPathContext(), 
contextNode, this,
                                               new StringBuffer());
        if(null != langValue)
        {
          // Not really sure what to do about the country code, so I use the
          // default from the system.
          // TODO: fix xml:lang handling.
          locale = new Locale(langValue.toUpperCase(),"");
          //Locale.getDefault().getDisplayCountry());
          if(null == locale)
          {
            transformer.getMsgMgr().warn(null, contextNode,
                           XSLTErrorResources.WG_LOCALE_NOT_FOUND, new Object[] 
{langValue}); //"Warning: Could not find locale for xml:lang="+langValue);
            locale = Locale.getDefault();
          }
        }
      }
      else
      {
        locale = Locale.getDefault();
      }
      return locale;
    }
  
    /**
     *
     */
    private DecimalFormat getNumberFormatter(TransformerImpl transformer, Node 
contextNode)
      throws SAXException
    {
      Locale locale = getLocale(transformer, contextNode);
  
      // Helper to format local specific numbers to strings.
      DecimalFormat formatter;
      synchronized(locale)
      {
        formatter = (DecimalFormat)NumberFormat.getNumberInstance(locale);
      }
  
      String digitGroupSepValue = (null != m_groupingSeparator_avt)
                                  ?  
m_groupingSeparator_avt.evaluate(transformer.getXPathContext(),
                                                                      
contextNode, this,
                                                                      new 
StringBuffer())
                                     : null;
  
      String nDigitsPerGroupValue = (null != m_groupingSize_avt)
                                    ?  
m_groupingSize_avt.evaluate(transformer.getXPathContext(),
                                                                   contextNode, 
this,
                                                                   new 
StringBuffer())
                                       : null;
  
      // TODO: Handle digit-group attributes
      if((null != digitGroupSepValue) && (null != nDigitsPerGroupValue))
      {
        try 
        {
          
formatter.setGroupingSize(Integer.valueOf(nDigitsPerGroupValue).intValue());  
          
formatter.getDecimalFormatSymbols().setGroupingSeparator(digitGroupSepValue.charAt(0));
       
          formatter.setGroupingUsed(true);
        }       
        catch(NumberFormatException ex)
        {
          formatter.setGroupingUsed(false);
        }
        
      }
  
      return formatter;
    }
  
    /**
     * Format a vector of numbers into a formatted string.
     * @param xslNumberElement Element that takes %conversion-atts; attributes.
     * @param list Array of one or more integer numbers.
     * @return String that represents list according to
     * %conversion-atts; attributes.
     * TODO: Optimize formatNumberList so that it caches the last count and
     * reuses that info for the next count.
     */
    String formatNumberList(TransformerImpl transformer, int[] list, Node 
contextNode)
      throws SAXException
    {
      StringBuffer formattedNumber = new StringBuffer();
      int nNumbers = list.length, numberWidth = 1;
      char numberType = '1';
      String formatToken, lastSepString = null, formatTokenString = null;
      // If a seperator hasn't been specified, then use "."  
      // as a default separator. 
      // For instance: [2][1][5] with a format value of "1 "
      // should format to "2.1.5 " (I think).
      // Otherwise, use the seperator specified in the format string.
      // For instance: [2][1][5] with a format value of "01-001. "
      // should format to "02-001-005 ".
      String lastSep = ".";                
      boolean isFirstToken = true;        // true if first token  
  
      String formatValue = (null != m_format_avt)
                           ? 
m_format_avt.evaluate(transformer.getXPathContext(), contextNode, this,
                                                   new StringBuffer())
                             : null;
      if(null == formatValue) formatValue = "1";
  
      NumberFormatStringTokenizer formatTokenizer = new 
NumberFormatStringTokenizer(formatValue);
      
      // int sepCount = 0;                  // keep track of seperators
      // Loop through all the numbers in the list.
      for(int i = 0; i < nNumbers; i++)
      {
        // Loop to the next digit, letter, or separator.
        if(formatTokenizer.hasMoreTokens())
        {
          formatToken = formatTokenizer.nextToken();
          
          // If the first character of this token is a character or digit, then 
          // it is a number format directive.
          
if(Character.isLetterOrDigit(formatToken.charAt(formatToken.length()-1)))
          {
            numberWidth = formatToken.length();
            numberType = formatToken.charAt(numberWidth-1);
          }
          // If there is a number format directive ahead, 
          // then append the formatToken.
          else if(formatTokenizer.isLetterOrDigitAhead())
          {          
            formatTokenString = formatToken;
            
            // Append the formatToken string...
            // For instance [2][1][5] with a format value of "1--1. "
            // should format to "2--1--5. " (I guess).
            while(formatTokenizer.nextIsSep())
            {
              formatToken = formatTokenizer.nextToken();
              formatTokenString += formatToken;
            }
            // Record this separator, so it can be used as the 
            // next separator, if the next is the last.
            // For instance: [2][1][5] with a format value of "1-1 "
            // should format to "2-1-5 ".
            if (!isFirstToken)
              lastSep = formatTokenString;
            
            // Since we know the next is a number or digit, we get it now.
            formatToken = formatTokenizer.nextToken();
            numberWidth = formatToken.length();
            numberType = formatToken.charAt(numberWidth-1);
          }
          else // only separators left
          {
            // Set up the string for the trailing characters after 
            // the last number is formatted (i.e. after the loop).
            lastSepString = formatToken;
            
            // And append any remaining characters to the lastSepString.
            while(formatTokenizer.hasMoreTokens())
            {
              formatToken = formatTokenizer.nextToken();
              lastSepString += formatToken;
            }
          } // else
          
        } // end if(formatTokenizer.hasMoreTokens())
        
        // if this is the first token and there was a prefix
        // append the prefix else, append the separator
        // For instance, [2][1][5] with a format value of "(1-1.) "
        // should format to "(2-1-5.) " (I guess).
        if(null != formatTokenString && isFirstToken)
        {
          formattedNumber.append(formatTokenString);
        }  
        else if(null != lastSep && !isFirstToken)
          formattedNumber.append(lastSep);
        
        getFormattedNumber(transformer, contextNode, numberType, numberWidth, 
list[i], formattedNumber);
        isFirstToken = false;              // After the first pass, this should 
be false
        
      } // end for loop
      
  
      // Check to see if we finished up the format string...
      
      // Skip past all remaining letters or digits
      while(formatTokenizer.isLetterOrDigitAhead())
        formatTokenizer.nextToken();
      
      if(lastSepString != null)
        formattedNumber.append(lastSepString);
      
      while(formatTokenizer.hasMoreTokens())
      {
        formatToken = formatTokenizer.nextToken();
        formattedNumber.append(formatToken);
      }
  
      return formattedNumber.toString();
    } // end formatNumberList method
  
    /*
    * Get Formatted number
    */
    private void getFormattedNumber(TransformerImpl transformer,
                                    Node contextNode,
                                    char numberType,
                                    int numberWidth,
                                    int listElement,
                                    StringBuffer formattedNumber)
      throws org.xml.sax.SAXException
    {
      DecimalFormat formatter = getNumberFormatter(transformer, contextNode);
      String padString = formatter.format(0);
      String letterVal = (m_lettervalue_avt != null) ? 
m_lettervalue_avt.evaluate(transformer.getXPathContext(),
                                                                                
  contextNode, this,
                                                                                
  new StringBuffer()) : null;
      switch(numberType)
      {
      case 'A':
        int2alphaCount(listElement, m_alphaCountTable, formattedNumber);
        break;
      case 'a':
        {
          StringBuffer stringBuf = new StringBuffer();
          int2alphaCount(listElement, m_alphaCountTable, stringBuf);
          
formattedNumber.append(stringBuf.toString().toLowerCase(getLocale(transformer, 
contextNode)));
        }
        break;
      case 'I':
        formattedNumber.append( long2roman(listElement, true));
        break;
      case 'i':
        formattedNumber.append( long2roman(listElement, true).toLowerCase( 
getLocale(transformer, contextNode)));
        break;
      case 0x3042:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("ja","JP","HA" ) );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          formattedNumber.append( int2singlealphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET)));                    
        break;
      case 0x3044:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("ja","JP", "HI") );
        if ((letterVal != null) && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          formattedNumber.append( int2singlealphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET)));                    
        break;
      case 0x30A2:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("ja","JP","A" ) );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          formattedNumber.append( int2singlealphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET)));                    
        break;
      case 0x30A4:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("ja","JP", "I") );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          formattedNumber.append( int2singlealphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET)));                    
        break;
      case 0x4E00:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("zh","CN" ) );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
        {
          formattedNumber.append(tradAlphaCount(listElement));
        }       
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          int2alphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET), formattedNumber);
        break;
      case 0x58F9:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("zh","TW") );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          int2alphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET), formattedNumber);        
          
        break;
      case 0x0E51:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("th","") );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          int2alphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET), formattedNumber);  
        break;
      case 0x05D0:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("he","") );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          int2alphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET), formattedNumber);  
        break;
      case 0x10D0:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("ka","") );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          int2alphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET), formattedNumber);  
        break;
      case 0x03B1:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("el","") );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          int2alphaCount(listElement, 
(char[])thisBundle.getObject(Constants.LANG_ALPHABET), formattedNumber);        
  
        break;
      case 0x0430:
        thisBundle = (XSLTResourceBundle)XSLTResourceBundle.loadResourceBundle( 
Constants.LANG_BUNDLE_NAME, new Locale("cy","") );
        if (letterVal != null && 
letterVal.equals(Constants.ATTRVAL_TRADITIONAL))
          formattedNumber.append( tradAlphaCount(listElement));
        else //if (m_lettervalue_avt != null && 
m_lettervalue_avt.equals(Constants.ATTRVAL_ALPHABETIC))
          
int2alphaCount(listElement,(char[])thisBundle.getObject(Constants.LANG_ALPHABET),
 formattedNumber);           
        break;
      default: // "1"
        String numString = formatter.format(listElement);
        int nPadding = numberWidth - numString.length();
        for(int k = 0; k < nPadding; k++)
        {
          formattedNumber.append(padString);
        }
        formattedNumber.append(numString);
      }
      
    }
  
    /**
     * Convert a long integer into alphabetic counting, in other words
     * count using the sequence A B C ... Z.
     * @param val Value to convert -- must be greater than zero.
     * @param table a table containing one character for each digit in the radix
     * @return String representing alpha count of number.
     * @see TransformerImpl#DecimalToRoman
     *
     * Note that the radix of the conversion is inferred from the size
     * of the table.
     */
    protected String int2singlealphaCount(int val, char [] table)
    {
      int radix = table.length;
  
      // TODO:  throw error on out of range input
      if (val > radix)
        return "#E("+val+")";
      else
        return (new Character(table[val-1])).toString();        // index into 
table is off one, starts at 0
      
    }
  
    /**
     * Convert a long integer into alphabetic counting, in other words
     * count using the sequence A B C ... Z AA AB AC.... etc.
     * @param val Value to convert -- must be greater than zero.
     * @param table a table containing one character for each digit in the radix
     * @return String representing alpha count of number.
     * @see TransformerImpl#DecimalToRoman
     *
     * Note that the radix of the conversion is inferred from the size
     * of the table.
     */
    protected void int2alphaCount(int val, char [] aTable, StringBuffer 
stringBuf)
    {
  
      int radix = aTable.length;
      char[] table = new char[aTable.length];
      // start table at 1, add last char at index 0. Reason explained above and 
below.
      int i;
      for (i=0; i<aTable.length-1;i++)          
        table[i+1] = aTable[i];
      table[0] = aTable[i];
  
      // Create a buffer to hold the result
      // TODO:  size of the table can be detereined by computing
      // logs of the radix.  For now, we fake it.
      char buf[] = new char[100];
  
      //some languages go left to right(ie. english), right to left (ie. 
Hebrew),
      //top to bottom (ie.Japanese), etc... Handle them differently
      //String orientation = thisBundle.getString(Constants.LANG_ORIENTATION);
  
      // next character to set in the buffer
      int charPos;
      charPos= buf.length -1 ;    // work backward through buf[]        
      
  
      // index in table of the last character that we stored
      int lookupIndex = 1;  // start off with anything other than zero to make 
correction work
  
      
  
      //                                                Correction number
      //
      //        Correction can take on exactly two values:
      //
      //                0       if the next character is to be emitted is usual
      //
      //      radix - 1
      //                        if the next char to be emitted should be one 
less than
      //                        you would expect
      //                        
      // For example, consider radix 10, where 1="A" and 10="J"
      //
      // In this scheme, we count: A, B, C ...   H, I, J (not A0 and certainly
      // not AJ), A1
      //
      // So, how do we keep from emitting AJ for 10?  After correctly emitting 
the
      // J, lookupIndex is zero.  We now compute a correction number of 9 
(radix-1).
      // In the following line, we'll compute (val+correction) % radix, which 
is,
      // (val+9)/10.  By this time, val is 1, so we compute (1+9) % 10, which
      // is 10 % 10 or zero.  So, we'll prepare to emit "JJ", but then we'll
      // later suppress the leading J as representing zero (in the mod system,
      // it can represent either 10 or zero).  In summary, the correction value 
of
      // "radix-1" acts like "-1" when run through the mod operator, but with 
the
      // desireable characteristic that it never produces a negative number.
  
      int correction = 0;
  
      // TODO:  throw error on out of range input
  
      do
      {
        // most of the correction calculation is explained above,  the reason 
for the
        // term after the "|| " is that it correctly propagates carries across
        // multiple columns.
        correction = ((lookupIndex == 0) ||
                      (correction != 0 && lookupIndex == radix-1 )) ? (radix-1) 
: 0;
  
        // index in "table" of the next char to emit
        lookupIndex  = (val+correction) % radix;
  
        // shift input by one "column"
        val = (val / radix);
  
        // if the next value we'd put out would be a leading zero, we're done.
        if (lookupIndex == 0 && val == 0)
          break;
  
        // put out the next character of output
        buf[charPos--] = table[lookupIndex];  // left to right or top to bottom 
        
      }
        while (val > 0);
      
      stringBuf.append(buf, charPos+1, (buf.length - charPos -1));
    }
  
    /**
     *Convert a long integer into traditional alphabetic counting, in other 
words
     * count using the traditional numbering.
     * @param val Value to convert -- must be greater than zero.
     * @param table a table containing one character for each digit in the radix
     * @return String representing alpha count of number.
     * @see XSLProcessor#DecimalToRoman
     *
     * Note that the radix of the conversion is inferred from the size
     * of the table.
     */
    protected String tradAlphaCount(int val)
    {
      // if this number is larger than the largest number we can represent, 
error!
      //if (val > 
((Integer)thisBundle.getObject("MaxNumericalValue")).intValue())
      //return XSLTErrorResources.ERROR_STRING;
      char[] table = null;
      // index in table of the last character that we stored
      int lookupIndex = 1;  // start off with anything other than zero to make 
correction work
      // Create a buffer to hold the result
      // TODO:  size of the table can be detereined by computing
      // logs of the radix.  For now, we fake it.
      char buf[] = new char[100];
      
      //some languages go left to right(ie. english), right to left (ie. 
Hebrew),
      //top to bottom (ie.Japanese), etc... Handle them differently
      //String orientation = thisBundle.getString(Constants.LANG_ORIENTATION);
  
      // next character to set in the buffer
      int charPos;
      charPos= 0;                  //start at 0
      
      // array of number groups: ie.1000, 100, 10, 1
      int[] groups = (int[])thisBundle.getObject(Constants.LANG_NUMBERGROUPS);  
      
      // array of tables of hundreds, tens, digits...
      String[] tables = 
(String[])(thisBundle.getObject(Constants.LANG_NUM_TABLES));
      
      
      //some languages have additive alphabetical notation,
      //some multiplicative-additive, etc... Handle them differently.
      String numbering = thisBundle.getString(Constants.LANG_NUMBERING);        
      
      // do multiplicative part first
      if (numbering.equals(Constants.LANG_MULT_ADD))
      {
        String mult_order = thisBundle.getString(Constants.MULT_ORDER);
        int[] multiplier = 
(int[])(thisBundle.getObject(Constants.LANG_MULTIPLIER));    
        char[]zeroChar = (char[])thisBundle.getObject("zero");                  
        
        int i= 0;
        // skip to correct multiplier
        while (i < multiplier.length && val < multiplier[i] )
          i++;
        
        do
        {
          if (i >= multiplier.length)
            break;              //number is smaller than multipliers
          
          // some languages (ie chinese) put a zero character (and only one) 
when
          // the multiplier is multiplied by zero. (ie, 1001 is 1X1000 + 0X100 
+ 0X10 + 1)
          // 0X100 is replaced by the zero character, we don't need one for 0X10
          if (val< multiplier[i])
          {
            if (zeroChar.length == 0)
            {
              i++;
            }   
            else
            {
              if (buf[charPos-1]!= zeroChar[0])
                buf[charPos++] = zeroChar[0];
              i++;
            }
          }     
          else if (val>= multiplier[i])
          {     
            int mult = val/multiplier[i];
            val = val % multiplier[i];         // save this.
            
            int k = 0;
            while (k < groups.length)
            {
              lookupIndex = 1;                 // initialize for each table
              if (mult/groups[k]<= 0)                // look for right table
                k++;
              else
              {
                // get the table
                char[] THEletters= (char[]) thisBundle.getObject(tables[k]);    
                                
                table = new char[THEletters.length+1];                          
        
                int j;
                for (j=0; j<THEletters.length;j++)              
                  table[j+1] = THEletters[j];
                table[0] = THEletters[j-1];    // don't need this               
                                                                
                // index in "table" of the next char to emit
                lookupIndex  = mult/ groups[k];
  
                //this should not happen
                if (lookupIndex == 0 && mult == 0)
                  break;
                char multiplierChar = 
((char[])(thisBundle.getObject(Constants.LANG_MULTIPLIER_CHAR)))[i];
                // put out the next character of output 
                if (lookupIndex < table.length)
                {                               
                  if( mult_order.equals(Constants.MULT_PRECEDES))
                  {
                    buf[charPos++] = multiplierChar;                            
                    buf[charPos++] = table[lookupIndex];                        
                                
                  }     
                  else
                  {     
                    // don't put out 1 (ie 1X10 is just 10)
                    if (lookupIndex == 1 && i == multiplier.length -1)
                    {}
                    else
                      buf[charPos++] =  table[lookupIndex];
                    buf[charPos++] =  multiplierChar ;
                  }
                  
                  break;       // all done!
                }
                else
                  return XSLTErrorResources.ERROR_STRING;
              } //end else
            } // end while      
            
            i++;
          } // end else if
        } // end do while
                while ( i < multiplier.length);         
      }
  
      // Now do additive part...
      
      int count = 0;
      String tableName;
      // do this for each table of hundreds, tens, digits...
      while (count < groups.length)
      {
        if (val/groups[count]<= 0)               // look for correct table
          count++;
        else
        {
          char[] theletters= (char[]) thisBundle.getObject(tables[count]);      
                
          table = new char[theletters.length+1];
          int j;
          // need to start filling the table up at index 1
          for (j=0; j<theletters.length;j++)
          {
            table[j+1] = theletters[j];
          }     
          table[0] = theletters[j-1];  // don't need this
          
          // index in "table" of the next char to emit
          lookupIndex  = val / groups[count];
  
          // shift input by one "column"
          val = val % groups[count];
  
          // this should not happen
          if (lookupIndex == 0 && val == 0)
            break;                                      
          
          if (lookupIndex < table.length)
          {
            // put out the next character of output     
            buf[charPos++] = table[lookupIndex];  // left to right or top to 
bottom                                     
          }
          else
            return XSLTErrorResources.ERROR_STRING;
          count++;
        }
      } // end while
  
      // String s = new String(buf, 0, charPos);
      return new String(buf, 0,  charPos);
    }
  
    /**
     * Convert a long integer into roman numerals.
     * @param val Value to convert.
     * @param prefixesAreOK true_ to enable prefix notation (e.g. 4 = "IV"),
     * false_ to disable prefix notation (e.g. 4 = "IIII").
     * @return Roman numeral string.
     * @see DecimalToRoman
     * @see m_romanConvertTable
     */
    protected String long2roman(long val, boolean prefixesAreOK)
    {
      if(val <= 0)
      {
        return "#E("+val+")";
      }
  
      String roman = "";
      int place = 0;
      if (val <= 3999L)
      {
        do
        {
          while (val >= m_romanConvertTable[place].m_postValue)
          {
            roman += m_romanConvertTable[place].m_postLetter;
            val -= m_romanConvertTable[place].m_postValue;
          }
          if (prefixesAreOK)
          {
            if (val >= m_romanConvertTable[place].m_preValue)
            {
              roman += m_romanConvertTable[place].m_preLetter;
              val -= m_romanConvertTable[place].m_preValue;
            }
          }
          place++;
        }
          while (val > 0);
      }
      else
      {
        roman = XSLTErrorResources.ERROR_STRING;
      }
      return roman;
    } // end long2roman
  
  /**
   * This class returns tokens using non-alphanumberic
   * characters as delimiters.
   */
    class NumberFormatStringTokenizer
    {
      private int currentPosition;
      private int maxPosition;
      private String str;
  
      /**
       * Construct a NumberFormatStringTokenizer.
       */
      public NumberFormatStringTokenizer(String str)
      {
        this.str = str;
        maxPosition = str.length();
      }
  
      /**
       * Reset tokenizer so that nextToken() starts from the beginning.
       */
      public void reset()
      {
        currentPosition = 0;
      }
  
      /**
       * Returns the next token from this string tokenizer.
       *
       * @return     the next token from this string tokenizer.
       * @exception  NoSuchElementException  if there are no more tokens in this
       *               tokenizer's string.
       */
      public String nextToken()
      {
        if (currentPosition >= maxPosition)
        {
          throw new NoSuchElementException();
        }
  
        int start = currentPosition;
        while ((currentPosition < maxPosition) &&
               Character.isLetterOrDigit(str.charAt(currentPosition)))
        {
          currentPosition++;
        }
        if ((start == currentPosition) &&
            (!Character.isLetterOrDigit(str.charAt(currentPosition))))
        {
          currentPosition++;
        }
        return str.substring(start, currentPosition);
      }
      
      /**
       * Tells if there is a digit or a letter character ahead.
       *
       * @return     true if there is a number or character ahead.
       */
      public boolean isLetterOrDigitAhead()
      {
        int pos = currentPosition;
  
        while (pos < maxPosition)
        {
          if(Character.isLetterOrDigit(str.charAt(pos)))
            return true;
          pos++;
        }
        return false;
      }
  
      /**
       * Tells if there is a digit or a letter character ahead.
       *
       * @return     true if there is a number or character ahead.
       */
      public boolean nextIsSep()
      {
        if(Character.isLetterOrDigit(str.charAt(currentPosition)))
          return false;
        else
          return true;
      }
  
  
      /**
       * Tells if <code>nextToken</code> will throw an exception
       * if it is called.
       *
       * @return true if <code>nextToken</code> can be called
       * without throwing an exception.
       */
      public boolean hasMoreTokens()
      {
        return (currentPosition >= maxPosition) ? false : true;
      }
  
      /**
       * Calculates the number of times that this tokenizer's
       * <code>nextToken</code> method can be called before it generates an
       * exception.
       *
       * @return  the number of tokens remaining in the string using the current
       *          delimiter set.
       * @see     java.util.StringTokenizer#nextToken()
       */
      public int countTokens()
      {
        int count = 0;
        int currpos = currentPosition;
  
        while (currpos < maxPosition)
        {
          int start = currpos;
          while ((currpos < maxPosition) &&
                 Character.isLetterOrDigit(str.charAt(currpos)))
          {
            currpos++;
          }
          if ((start == currpos) &&
              (Character.isLetterOrDigit(str.charAt(currpos)) == false))
          {
            currpos++;
          }
          count++;
        }
        return count;
      }
  
    } // end NumberFormatStringTokenizer
  }
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemOtherwise.java
  
  Index: ElemOtherwise.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:otherwise.
   * <pre>
   * <!ELEMENT xsl:otherwise %template;>
   * <!ATTLIST xsl:otherwise %space-att;>
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Conditional-Processing-with-xsl:choose";>XXX
 in XSLT Specification</a>
   */
  public class ElemOtherwise extends ElemTemplateElement
  {  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_OTHERWISE;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_OTHERWISE_STRING;
    }
  
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/templates/ElemPI.java
  
  Index: ElemPI.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:processing-instruction.
   * <pre>
   * <!ELEMENT xsl:processing-instruction %char-template;>
   * <!ATTLIST xsl:processing-instruction 
   *   name %avt; #REQUIRED
   *   %space-att;
   * >
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-Processing-Instructions";>section-Creating-Processing-Instructions
 in XSLT Specification</a>
   */
  public class ElemPI extends ElemTemplateElement
  {
    /**
     * The xsl:processing-instruction element has a required name 
     * attribute that specifies the name of the processing instruction node. 
     * The value of the name attribute is interpreted as an 
     * attribute value template.
     */
    private AVT m_name_atv = null;
  
    /**
     * Set the "name" attribute. 
     * DJD 
     */
    public void setName(AVT v)
    {
      m_name_atv = v;
    }
  
    /**
     * Get the "name" attribute. 
     * DJD 
     */
    public AVT getName()
    {
      return m_name_atv;
    }
    
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_PI;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_PI_STRING;
    }
  
    /**
     * Create a processing instruction in the result tree.
     * The content of the xsl:processing-instruction element is a 
     * template for the string-value of the processing instruction node. 
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-Processing-Instructions";>section-Creating-Processing-Instructions
 in XSLT Specification</a>
     */
    public void execute(TransformerImpl transformer, 
                       Node sourceNode,
                       QName mode)
      throws SAXException
    {    
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      String piName = m_name_atv.evaluate(transformer.getXPathContext(), 
sourceNode, this, 
                                          new StringBuffer());
      if(piName.equalsIgnoreCase("xml"))
      {
        error(XSLTErrorResources.ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML); 
//"processing-instruction name can not be 'xml'");
      }
      else if(!isValidNCName(piName))
      {
        error(XSLTErrorResources.ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME, new 
Object[] {piName}); //"processing-instruction name must be a valid NCName: 
"+piName);
      }
      
      // Note the content model is:
      // <!ENTITY % instructions "
      // %char-instructions;
      // | xsl:processing-instruction
      // | xsl:comment
      // | xsl:element
      // | xsl:attribute
      // ">
      String data = transformer.transformToString(this,  
                                     sourceNode, mode);
      transformer.getResultTreeHandler().processingInstruction(piName, data);
    }
    
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      int type = ((ElemTemplateElement)newChild).getXSLToken();
      switch(type)
      {
        // char-instructions 
      case Constants.ELEMNAME_TEXTLITERALRESULT:
      case Constants.ELEMNAME_APPLY_TEMPLATES:
      case Constants.ELEMNAME_APPLY_IMPORTS:
      case Constants.ELEMNAME_CALLTEMPLATE:
      case Constants.ELEMNAME_FOREACH:
      case Constants.ELEMNAME_VALUEOF:
      case Constants.ELEMNAME_COPY_OF:
      case Constants.ELEMNAME_NUMBER:
      case Constants.ELEMNAME_CHOOSE:
      case Constants.ELEMNAME_IF:
      case Constants.ELEMNAME_TEXT:
      case Constants.ELEMNAME_COPY:
      case Constants.ELEMNAME_VARIABLE:
      case Constants.ELEMNAME_MESSAGE:
        
        // instructions 
        // case Constants.ELEMNAME_PI:
        // case Constants.ELEMNAME_COMMENT:
        // case Constants.ELEMNAME_ELEMENT:
        // case Constants.ELEMNAME_ATTRIBUTE:
  
        break;
        
      default:
        error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
              //" to " + this.m_elemName);
      }
      return super.appendChild(newChild);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemParam.java
  
  Index: ElemParam.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.trace.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:param.
   * <pre>
   * <!ELEMENT xsl:param %template;>
   * <!ATTLIST xsl:param 
   *   name %qname; #REQUIRED
   *   select %expr; #IMPLIED
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#variables";>variables in XSLT 
Specification</a>
   */
  public class ElemParam extends ElemVariable
  {
    public ElemParam()
    {
    }
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_PARAMVARIABLE;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_PARAMVARIABLE_STRING;
    }
    
    /**
     * Copy constructor.
     */
    public ElemParam (ElemParam param)
      throws SAXException
    {
      super(param);
    }
  
    /**
     * Execute a parameter declaration.  There are two elements that can 
     * be used to bind variables: xsl:variable and xsl:param. The 
     * difference is that the value specified on the xsl:param variable 
     * is only a default value for the binding; when the template or 
     * stylesheet within which the xsl:param element occurs is invoked, 
     * parameters may be passed that are used in place of the default values.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {    
      Object obj = 
transformer.getXPathContext().getVarStack().getParamVariable(getName());
      
      if(null == obj)
      {
        super.execute(transformer, sourceNode, mode);
      }
      else
      {
        if(TransformerImpl.S_DEBUG)
          transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemSort.java
  
  Index: ElemSort.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
   
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:sort.
   * <pre>
   * <!ELEMENT xsl:sort EMPTY>
   * <!ATTLIST xsl:sort
   *   select %expr; "."
   *   lang %avt; #IMPLIED
   *   data-type %avt; "text"
   *   order %avt; "ascending"
   *   case-order %avt; #IMPLIED
   * >
   * <!-- xsl:sort cannot occur after any other elements or
   * any non-whitespace character -->
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#sorting";>sorting in XSLT 
Specification</a>
   */
  public class ElemSort extends ElemTemplateElement
  {
    /**
     * xsl:sort has a select attribute whose value is an expression.
     */
    private XPath m_selectExpression = null;
    
    /**
     * Set the "select" attribute. 
     * xsl:sort has a select attribute whose value is an expression. 
     * For each node to be processed, the expression is evaluated 
     * with that node as the current node and with the complete 
     * list of nodes being processed in unsorted order as the current 
     * node list. The resulting object is converted to a string as if 
     * by a call to the string function; this string is used as the 
     * sort key for that node. The default value of the select attribute 
     * is ., which will cause the string-value of the current node to 
     * be used as the sort key.
     */
    public void setSelect(XPath v)
    {
      m_selectExpression = v;
    }
  
    /**
     * Get the "select" attribute. 
     * xsl:sort has a select attribute whose value is an expression. 
     * For each node to be processed, the expression is evaluated 
     * with that node as the current node and with the complete 
     * list of nodes being processed in unsorted order as the current 
     * node list. The resulting object is converted to a string as if 
     * by a call to the string function; this string is used as the 
     * sort key for that node. The default value of the select attribute 
     * is ., which will cause the string-value of the current node to 
     * be used as the sort key.
     */
    public XPath getSelect()
    {
      return m_selectExpression;
    }
    
    /**
     * lang specifies the language of the sort keys.
     */
    private AVT m_lang_avt = null;
    
    /**
     * Set the "lang" attribute. 
     * lang specifies the language of the sort keys; it has the same 
     * range of values as xml:lang [XML]; if no lang value is 
     * specified, the language should be determined from the system environment.
     */
    public void setLang(AVT v)
    {
      m_lang_avt = v;
    }
  
    /**
     * Get the "lang" attribute. 
     * lang specifies the language of the sort keys; it has the same 
     * range of values as xml:lang [XML]; if no lang value is 
     * specified, the language should be determined from the system environment.
     */
    public AVT getLang()
    {
      return m_lang_avt;
    }
    
    
    /**
     * data-type specifies the data type of the
     * strings to be sorted.
     */
    private AVT m_dataType_avt = null;
    
    /**
     * Set the "data-type" attribute. 
     * <code>data-type</code> specifies the data type of the
     * strings; the following values are allowed:
     * <ul>
     * <li>
     * <code>text</code> specifies that the sort keys should be
     * sorted lexicographically in the culturally correct manner for the
     * language specified by <code>lang</code>.
     * </li>
     * <li>
     * <code>number</code> specifies that the sort keys should be
     * converted to numbers and then sorted according to the numeric value;
     * the sort key is converted to a number as if by a call to the
     * <b><a href="http://www.w3.org/TR/xpath#function-number";>number</a></b> 
function; the <code>lang</code>
     * attribute is ignored.
     * </li>
     * <li>
     * A <a href="http://www.w3.org/TR/REC-xml-names#NT-QName";>QName</a> with a 
prefix
     * is expanded into an <a 
href="http://www.w3.org/TR/xpath#dt-expanded-name";>expanded-name</a> as 
described
     * in <a href="#qname">[<b>2.4 Qualified Names</b>]</a>; the expanded-name 
identifies the data-type;
     * the behavior in this case is not specified by this document.
     * </li>
     * </ul>
     * <p>The default value is <code>text</code>.</p>
     * <blockquote>
     * <b>NOTE: </b>The XSL Working Group plans that future versions of XSLT 
will
     * leverage XML Schemas to define further values for this
     * attribute.</blockquote>
     */
    public void setDataType(AVT v)
    {
      m_dataType_avt = v;
    }
  
    /**
     * Get the "data-type" attribute. 
     * <code>data-type</code> specifies the data type of the
     * strings; the following values are allowed:
     * <ul>
     * <li>
     * <code>text</code> specifies that the sort keys should be
     * sorted lexicographically in the culturally correct manner for the
     * language specified by <code>lang</code>.
     * </li>
     * <li>
     * <code>number</code> specifies that the sort keys should be
     * converted to numbers and then sorted according to the numeric value;
     * the sort key is converted to a number as if by a call to the
     * <b><a href="http://www.w3.org/TR/xpath#function-number";>number</a></b> 
function; the <code>lang</code>
     * attribute is ignored.
     * </li>
     * <li>
     * A <a href="http://www.w3.org/TR/REC-xml-names#NT-QName";>QName</a> with a 
prefix
     * is expanded into an <a 
href="http://www.w3.org/TR/xpath#dt-expanded-name";>expanded-name</a> as 
described
     * in <a href="#qname">[<b>2.4 Qualified Names</b>]</a>; the expanded-name 
identifies the data-type;
     * the behavior in this case is not specified by this document.
     * </li>
     * </ul>
     * <p>The default value is <code>text</code>.</p>
     * <blockquote>
     * <b>NOTE: </b>The XSL Working Group plans that future versions of XSLT 
will
     * leverage XML Schemas to define further values for this
     * attribute.</blockquote>
     */
    public AVT getDataType()
    {
      return m_dataType_avt;
    }
      
    /**
     * order specifies whether the strings should be sorted in ascending 
     * or descending order.
     */
    private AVT m_order_avt = null;
    
    /**
     * Set the "order" attribute. 
     * order specifies whether the strings should be sorted in ascending 
     * or descending order; ascending specifies ascending order; descending 
     * specifies descending order; the default is ascending.
     */
    public void setOrder(AVT v)
    {
      m_order_avt = v;
    }
  
    /**
     * Get the "order" attribute. 
     * order specifies whether the strings should be sorted in ascending 
     * or descending order; ascending specifies ascending order; descending 
     * specifies descending order; the default is ascending.
     */
    public AVT getOrder()
    {
      return m_order_avt;
    }
      
    /**
     * case-order has the value upper-first or lower-first. 
     * The default value is language dependent.
     */
    private AVT m_caseorder_avt = null;
    
    /**
     * Set the "case-order" attribute. 
     * case-order has the value upper-first or lower-first; this applies 
     * when data-type="text", and specifies that upper-case letters should 
     * sort before lower-case letters or vice-versa respectively. 
     * For example, if lang="en", then A a B b are sorted with 
     * case-order="upper-first" and a A b B are sorted with 
case-order="lower-first". 
     * The default value is language dependent.
     */
    public void setCaseOrder(AVT v)
    {
      m_caseorder_avt = v;
    }
  
    /**
     * Get the "case-order" attribute. 
     * case-order has the value upper-first or lower-first; this applies 
     * when data-type="text", and specifies that upper-case letters should 
     * sort before lower-case letters or vice-versa respectively. 
     * For example, if lang="en", then A a B b are sorted with 
     * case-order="upper-first" and a A b B are sorted with 
case-order="lower-first". 
     * The default value is language dependent.
     */
    public AVT getCaseOrder()
    {
      return m_caseorder_avt;
    }
    
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_SORT;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_SORT_STRING;
    }
    
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
            //" to " + this.m_elemName);
      return null;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemTemplate.java
  
  Index: ElemTemplate.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:template.
   * <pre>
   * <!ELEMENT xsl:template
   *  (#PCDATA
   *   %instructions;
   *   %result-elements;
   *   | xsl:param)*
   * >
   * 
   * <!ATTLIST xsl:template
   *   match %pattern; #IMPLIED
   *   name %qname; #IMPLIED
   *   priority %priority; #IMPLIED
   *   mode %qname; #IMPLIED
   *   %space-att;
   * >
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Defining-Template-Rules";>section-Defining-Template-Rules
 in XSLT Specification</a>
   */
  public class ElemTemplate extends ElemTemplateElement
  {
    private String m_publicId;
    private String m_systemId;
    
    /**
     * Return the public identifier for the current document event.
     * <p>This will be the public identifier
     * @return A string containing the public identifier, or
     *         null if none is available.
     * @see #getSystemId
     */
    public String getPublicId ()
    {
      return m_publicId;
    }
    
    /**
     * Return the system identifier for the current document event.
     *
     * <p>If the system identifier is a URL, the parser must resolve it
     * fully before passing it to the application.</p>
     *
     * @return A string containing the system identifier, or null
     *         if none is available.
     * @see #getPublicId
     */
    public String getSystemId ()
    {
      return m_systemId;
    }
    
    /**
     * Set the location information for this element.
     */
    public void setLocaterInfo(Locator locator)
    {
      m_publicId = locator.getPublicId();
      m_systemId = locator.getSystemId();
      super.setLocaterInfo(locator);
    }
    
    /** 
     * The owning stylesheet.
     * (Should this only be put on the template element, to
     * conserve space?)
     * @serial
     */
    private Stylesheet m_stylesheet;
  
    /**
     * Get the owning stylesheet.
     */
    public StylesheetComposed getStylesheetComposed()
    {
      return m_stylesheet.getStylesheetComposed();
    }
  
    /**
     * Get the owning stylesheet.
     */
    public Stylesheet getStylesheet()
    {
      return m_stylesheet;
    }
    
    /**
     * Set the owning stylesheet.
     */
    public void setStylesheet(Stylesheet sheet)
    {
      m_stylesheet = sheet;
    }
  
    /**
     * Get the owning stylesheet.
     */
    public StylesheetRoot getStylesheetRoot()
    {
      return m_stylesheet.getStylesheetRoot();
    }
    
    /**
     * The match attribute is a Pattern that identifies the source 
     * node or nodes to which the rule applies.
     */
    private XPath m_matchPattern = null;
    
    /**
     * Set the "match" attribute. 
     * The match attribute is a Pattern that identifies the source 
     * node or nodes to which the rule applies. The match attribute 
     * is required unless the xsl:template element has a name 
     * attribute (see [6 Named Templates]). It is an error for the 
     * value of the match attribute to contain a VariableReference. 
     * @see <a href="http://www.w3.org/TR/xslt#patterns";>patterns in XSLT 
Specification</a>
     */
    public void setMatch(XPath v)
    {
      m_matchPattern = v;
    }
  
    /**
     * Get the "match" attribute. 
     * The match attribute is a Pattern that identifies the source 
     * node or nodes to which the rule applies. The match attribute 
     * is required unless the xsl:template element has a name 
     * attribute (see [6 Named Templates]). It is an error for the 
     * value of the match attribute to contain a VariableReference. 
     * @see <a href="http://www.w3.org/TR/xslt#patterns";>patterns in XSLT 
Specification</a>
     */
    public XPath getMatch()
    {
      return m_matchPattern;
    }
    
    /**
     * An xsl:template element with a name attribute specifies a named template.
     */
    private QName m_name = null;
    
    /**
     * Set the "name" attribute. 
     * An xsl:template element with a name attribute specifies a named template.
     * If an xsl:template element has a name attribute, it may, but need not, 
     * also have a match attribute. 
     * @see <a href="http://www.w3.org/TR/xslt#named-templates";>named-templates 
in XSLT Specification</a>
     */
    public void setName(QName v)
    {
      m_name = v;
    }
  
    /**
     * Get the "name" attribute. 
     * An xsl:template element with a name attribute specifies a named template.
     * If an xsl:template element has a name attribute, it may, but need not, 
     * also have a match attribute. 
     * @see <a href="http://www.w3.org/TR/xslt#named-templates";>named-templates 
in XSLT Specification</a>
     */
    public QName getName()
    {
      return m_name;
    }
    
    /**
     * Modes allow an element to be processed multiple times, 
     * each time producing a different result.
     */
    private QName m_mode;
    
    /**
     * Set the "mode" attribute. 
     * Modes allow an element to be processed multiple times, 
     * each time producing a different result.  If xsl:template 
     * does not have a match attribute, it must not have a mode attribute. 
     * @see <a href="http://www.w3.org/TR/xslt#modes";>modes in XSLT 
Specification</a>
     */
    public void setMode(QName v)
    {
      m_mode = v;
    }
  
    /**
     * Get the "mode" attribute. 
     * Modes allow an element to be processed multiple times, 
     * each time producing a different result.  If xsl:template 
     * does not have a match attribute, it must not have a mode attribute. 
     * @see <a href="http://www.w3.org/TR/xslt#modes";>modes in XSLT 
Specification</a>
     */
    public QName getMode()
    {
      return m_mode;
    }
    
    /**
     * The priority of a template rule is specified by the priority 
     * attribute on the template rule.
     */
    private double m_priority = XPath.MATCH_SCORE_NONE;
    
    /**
     * Set the "priority" attribute. 
     * The priority of a template rule is specified by the priority 
     * attribute on the template rule. The value of this must be a 
     * real number (positive or negative), matching the production 
     * Number with an optional leading minus sign (-). 
     * @see <a href="http://www.w3.org/TR/xslt#conflict";>conflict in XSLT 
Specification</a>
     */
    public void setPriority(double v)
    {
      m_priority = v;
    }
  
    /**
     * Get the "priority" attribute. 
     * The priority of a template rule is specified by the priority 
     * attribute on the template rule. The value of this must be a 
     * real number (positive or negative), matching the production 
     * Number with an optional leading minus sign (-). 
     * @see <a href="http://www.w3.org/TR/xslt#conflict";>conflict in XSLT 
Specification</a>
     */
    public double getPriority()
    {
      return m_priority;
    }
  
    /**
     * Get an int constant identifying the type of element.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_TEMPLATE;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_TEMPLATE_STRING;
    }
  
    /**
     * Copy the template contents into the result tree.
     * The content of the xsl:template element is the template 
     * that is instantiated when the template rule is applied.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {    
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      if(null != sourceNode)
      { 
        transformer.executeChildTemplates(this, sourceNode, mode);
      }
      else // if(null == sourceNode)
      {
        transformer.getMsgMgr().error(this, sourceNode, 
                                      
XSLTErrorResources.ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES); 
        //"sourceNode is null in handleApplyTemplatesInstruction!");
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemTemplateElement.java
  
  Index: ElemTemplateElement.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import java.lang.InstantiationException;
  import java.io.Serializable;
  import java.util.Enumeration;
  import java.util.Vector;
  
  // Xalan imports
  import org.apache.xalan.utils.UnImplNode;
  import org.apache.xalan.utils.NameSpace;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.utils.StringToStringTable;
  
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.res.XSLMessages;
  
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.transformer.ResultNameSpace;
  import org.apache.xalan.transformer.ResultTreeHandler;
  
  import org.apache.xalan.xpath.VariableStack;
  
  // TRaX imports
  import trax.Templates;
  
  // Serializer imports
  import org.apache.xml.serialize.OutputFormat;
  import org.apache.xml.serialize.Serializer;
  
  // DOM Imports
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  import org.w3c.dom.DOMException;
  import org.w3c.dom.Document;
  
  // SAX Imports
  import org.xml.sax.Locator;
  import org.xml.sax.SAXException;
  import org.xml.sax.helpers.NamespaceSupport;
  
  /** 
   * <meta name="usage" content="advanced"/>
   * An instance of this class represents an element inside
   * an xsl:template class.  It has a single "execute" method
   * which is expected to perform the given action on the
   * result tree.
   * This class acts like a Element node, and implements the
   * Element interface, but is not a full implementation
   * of that interface... it only implements enough for
   * basic traversal of the tree.
   * 
   * @see Stylesheet
   */
  public class ElemTemplateElement extends UnImplNode 
    implements PrefixResolver, Serializable, Locator
  {  
    /** Construct a template element instance.
     * 
     * @param transformer The XSLT Processor.
     * @param stylesheetTree The owning stylesheet.
     * @param name The name of the element.
     * @param atts The element attributes.
     * @param lineNumber The line in the XSLT file that the element occurs on.
     * @param columnNumber The column index in the XSLT file that the element 
occurs on.
     * @exception SAXException Never.
     */
    public ElemTemplateElement()
    {
    }
    
    /** 
     * Get an integer representation of the element type.
     * 
     * @return An integer representation of the element, defined in the 
     *     Constants class.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_UNDEFINED;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return "Unknown XSLT Element";
    }
    
    /** Execute the element's primary function.  Subclasses of this
     * function may recursivly execute down the element tree.
     * 
     * @exception XSLProcessorException 
     * @exception java.net.MalformedURLException 
     * @exception java.io.FileNotFoundException 
     * @exception java.io.IOException 
     * @exception SAXException 
     * @param transformer The XSLT Processor.
     * @param sourceNode The current context node.
     * @param mode The current mode.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
    }
  
    
    /**
     * Get the owning "composed" stylesheet.  This looks up the 
     * inheritance chain until it calls getStylesheetComposed
     * on a Stylesheet object, which will Get the owning 
     * aggregated stylesheet, or that stylesheet if it is aggregated.
     */
    public StylesheetComposed getStylesheetComposed()
    {
      return m_parentNode.getStylesheetComposed();
    }
  
    /**
     * Get the owning stylesheet.  This looks up the 
     * inheritance chain until it calls getStylesheet
     * on a Stylesheet object, which will return itself.
     */
    public Stylesheet getStylesheet()
    {
      return m_parentNode.getStylesheet();
    }
  
    /**
     * Get the owning root stylesheet.  This looks up the 
     * inheritance chain until it calls StylesheetRoot
     * on a Stylesheet object, which will return a reference 
     * to the root stylesheet.
     */
    public StylesheetRoot getStylesheetRoot()
    {
      return m_parentNode.getStylesheetRoot();
    } 
    
    /** 
     * Validate that the string is an NCName.
     * 
     * @param s The name in question.
     * @return True if the string is a valid NCName according to XML rules.
     * @see <a href="http://www.w3.org/TR/REC-xml-names#NT-NCName";>XXX in XSLT 
Specification</a>
     */
    protected boolean isValidNCName(String s)
    {
      int len = s.length();
      char c = s.charAt(0);
      if(!(Character.isLetter(c) || (c == '_')))
        return false;
      if(len > 0)
      {
        for(int i = 1; i < len; i++)
        {
          c = s.charAt(i);
          if(!(Character.isLetterOrDigit(c) || (c == '_') || (c == '-') || (c 
== '.')))
            return false;
        }
      }
      return true;
    }
      
    /** 
     * Throw a template element runtime error.  (Note: should we throw a 
SAXException instead?)
     * 
     * @param msg Description of the error that occured.
     */
    public void error(int msg, Object[] args)
    {
      String themsg = XSLMessages.createMessage(msg, args);  
      throw new 
RuntimeException(XSLMessages.createMessage(XSLTErrorResources.ER_ELEMTEMPLATEELEM_ERR,
 new Object[] {themsg})); //"ElemTemplateElement error: "+msg);
    }
    
    // Implemented DOM Element methods.
    
    /** 
     * Add a child to the child list.
     * 
     * @exception DOMException 
     * @param newChild 
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      if(null == newChild)
      {
        error(XSLTErrorResources.ER_NULL_CHILD, null); //"Trying to add a null 
child!");
      }
      ElemTemplateElement elem = (ElemTemplateElement)newChild;
      if(null == m_firstChild)
      {
        m_firstChild = elem;
      }
      else
      {
        ElemTemplateElement last = (ElemTemplateElement)getLastChild();
        last.m_nextSibling = elem;
      }
      elem.m_parentNode = this;
      
      return newChild;
    }
    
    /** 
     * Tell if there are child nodes.
     */
    public boolean            hasChildNodes()
    {
      return (null != m_firstChild);
    }
    
    /** 
     * Get the type of the node.
     */
    public short              getNodeType()
    {
      return Node.ELEMENT_NODE;
    }
      
    /** Return the nodelist (same reference).
     */
    public NodeList           getChildNodes()
    {
      return this;
    }
    
    
    /** Replace the old child with a new child. */
    public Node               replaceChild(Node newChild,
                                           Node oldChild)
      throws DOMException
    {
      ElemTemplateElement node = (ElemTemplateElement)getFirstChild();
      while(null != node)
      {
        if(node == oldChild)
        {
          ElemTemplateElement newChildElem 
            = ((ElemTemplateElement)newChild);
          ElemTemplateElement oldChildElem 
            = ((ElemTemplateElement)oldChild);
  
          // Fix up previous sibling.
          ElemTemplateElement prev 
            = (ElemTemplateElement)oldChildElem.getPreviousSibling();
          if(null != prev)
            prev.m_nextSibling = newChildElem;
  
          // Fix up parent.
          if(newChildElem.m_parentNode.m_firstChild == oldChildElem)
            newChildElem.m_parentNode.m_firstChild = newChildElem;
  
          newChildElem.m_parentNode = oldChildElem.m_parentNode;
          oldChildElem.m_parentNode = null;
          
          newChildElem.m_nextSibling = oldChildElem.m_nextSibling;
          oldChildElem.m_nextSibling = null;
  
          // newChildElem.m_stylesheet = oldChildElem.m_stylesheet;
          // oldChildElem.m_stylesheet = null;
          
          return newChildElem;
        }
        node = (ElemTemplateElement)node.getNextSibling();
      }
      return null;
    }
    
    /** 
     * NodeList method: Count the immediate children of this node
     * 
     * @return int
     */
    public int getLength() 
    {
  
      // It is assumed that the getChildNodes call synchronized
      // the children. Therefore, we can access the first child
      // reference directly.
      int count = 0;
      for (ElemTemplateElement node = m_firstChild; node != null; node = 
node.m_nextSibling) 
      {
        count++;
      }
      return count;
  
    } // getLength():int
    
    /** 
     * NodeList method: Return the Nth immediate child of this node, or
     * null if the index is out of bounds.
     * 
     * @param index 
     * @return org.w3c.dom.Node
     */
    public Node item(int index) 
    {
      // It is assumed that the getChildNodes call synchronized
      // the children. Therefore, we can access the first child
      // reference directly.
      ElemTemplateElement node = m_firstChild;
      for (int i = 0; i < index && node != null; i++) 
      {
        node = node.m_nextSibling;
      }
      return node;
  
    } // item(int):Node
    
    /** Get the stylesheet owner.
     */
    public Document           getOwnerDocument()
    {
      return getStylesheet();
    }
    
    /** Return the element name.
     */
    public String getTagName()
    {
      return getNodeName();
    }
      
    /** Return the base identifier.
     */
    public String getBaseIdentifier()
    {
      // Should this always be absolute?
      return this.getSystemId();
    }
    
    private int m_lineNumber;
  
    /**
     * Return the line number where the current document event ends.
     * Note that this is the line position of the first character
     * after the text associated with the document event.
     * @return The line number, or -1 if none is available.
     * @see #getColumnNumber
     */
    public int getLineNumber ()
    {
      return m_lineNumber;
    }
    
    
    private int m_columnNumber;
  
    /**
     * Return the column number where the current document event ends.
     * Note that this is the column number of the first
     * character after the text associated with the document
     * event.  The first column in a line is position 1.
     * @return The column number, or -1 if none is available.
     * @see #getLineNumber
     */
    public int getColumnNumber ()
    {
      return m_columnNumber;
    }
    
    /**
     * Return the public identifier for the current document event.
     * <p>This will be the public identifier
     * @return A string containing the public identifier, or
     *         null if none is available.
     * @see #getSystemId
     */
    public String getPublicId ()
    {
      return m_parentNode.getPublicId();
    }
    
    /**
     * Return the system identifier for the current document event.
     *
     * <p>If the system identifier is a URL, the parser must resolve it
     * fully before passing it to the application.</p>
     *
     * @return A string containing the system identifier, or null
     *         if none is available.
     * @see #getPublicId
     */
    public String getSystemId ()
    {
      return m_parentNode.getSystemId();
    }
  
    
    /**
     * Set the location information for this element.
     */
    public void setLocaterInfo(Locator locator)
    {
      m_lineNumber = locator.getLineNumber();
      m_columnNumber = locator.getColumnNumber();
    }
  
    
    /** 
     * Tell if this element has the default space handling
     * turned off or on according to the xml:space attribute.
     * @serial
     */
    private boolean m_defaultSpace = true;
    
    /**
     * Set the "xml:space" attribute. 
     * A text node is preserved if an ancestor element of the text node 
     * has an xml:space attribute with a value of preserve, and 
     * no closer ancestor element has xml:space with a value of default.
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-Text";>section-Creating-Text in 
XSLT Specification</a>
     */
    public void setXmlSpace(boolean v)
    {
      m_defaultSpace = v;
    }
  
    /**
     * Get the "xml:space" attribute. 
     * A text node is preserved if an ancestor element of the text node 
     * has an xml:space attribute with a value of preserve, and 
     * no closer ancestor element has xml:space with a value of default.
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-Text";>section-Creating-Text in 
XSLT Specification</a>
     */
    public boolean getXmlSpace()
    {
      return m_defaultSpace;
    }
    
    /** 
     * The list of namespace declarations for this element only.
     * @serial
     */
    private Vector m_declaredPrefixes;
    
    /**
     * Return a table that contains all prefixes available 
     * within this element context.
     */
    public Vector getDeclaredPrefixes()
    {
      return m_declaredPrefixes;
    }
    
    /**
     * From the SAX2 helper class, set the namespace table for 
     * this element.  Take care to call resolveInheritedNamespaceDecls.
     * after all namespace declarations have been added.
     */
    public void setPrefixes(NamespaceSupport nsSupport)
      throws SAXException
    {
      Enumeration decls = nsSupport.getDeclaredPrefixes ();
      while(decls.hasMoreElements())
      {
        String prefix = (String)decls.nextElement();
        if(null == m_declaredPrefixes)
          m_declaredPrefixes = new Vector();
        String uri = nsSupport.getURI(prefix);
        // System.out.println("setPrefixes - "+prefix+", "+uri);
        XMLNSDecl decl = new XMLNSDecl(prefix, uri, false);
        m_declaredPrefixes.addElement(decl);
      }
    }
    
    /** 
     * Fullfill the PrefixResolver interface.  Calling this will throw an error.
     */
    public String getNamespaceForPrefix(String prefix, org.w3c.dom.Node context)
    {
      this.error(XSLTErrorResources.ER_CANT_RESOLVE_NSPREFIX, null);
      return null;
    }
    
    /** 
     * Given a namespace, get the corrisponding prefix.
     */
    public String getNamespaceForPrefix(String prefix)
    {
      ElemTemplateElement elem = this;
      while(null != elem)
      {
        Vector nsDecls = elem.m_declaredPrefixes;
        if(null != nsDecls)
        {
          int n = nsDecls.size();
          for(int i = 0; i < n; i++)
          {
            XMLNSDecl decl = (XMLNSDecl)nsDecls.elementAt(i);
            if(prefix.equals(decl.getPrefix()))
              return decl.getURI();
          }
        }
        elem = elem.m_parentNode;
      }
  
      return null;
    }
  
    /** 
     * The table of namespace declarations for this element 
     * and all parent elements, screened for excluded prefixes.
     * @serial
     */
    private Vector m_prefixTable;
  
    /**
     * Return a table that contains all prefixes available 
     * within this element context.
     */
    public Vector getPrefixes()
    {
      return m_prefixTable;
    }
    
    /**
     * Tell if the result namespace decl should be excluded.  Should be called 
before 
     * namespace aliasing (I think).
     */
    private boolean excludeResultNSDecl(String prefix, String uri)
      throws SAXException
    {
      if(uri.equals(Constants.S_XSLNAMESPACEURL)
         || getStylesheet().containsExtensionElementURI(uri)
         || uri.equals("http://xml.apache.org/xslt";)
         || uri.equals("http://xsl.lotus.com/";)
         || uri.equals("http://xsl.lotus.com";))
        return true; 
      
      if(getStylesheet().containsExcludeResultPrefix(prefix))
        return true;
      
      return false;
    }
  
      
    /**
     * Combine the parent's namespaces with this namespace 
     * for fast processing, taking care to reference the 
     * parent's namespace if this namespace adds nothing new.
     * (Recursive method, walking the elements depth-first, 
     * processing parents before children).
     */
    public void resolvePrefixTables()
      throws SAXException
    {
      // Always start with a fresh prefix table!
      m_prefixTable = null;
      
      // If we have declared declarations, then we look for 
      // a parent that has namespace decls, and add them 
      // to this element's decls.  Otherwise we just point 
      // to the parent that has decls.
      if(null != this.m_declaredPrefixes)
      {
        // Add this element's declared prefixes to the 
        // prefix table.
        int n = m_declaredPrefixes.size();
        for(int i = 0; i < n; i++)
        {
          XMLNSDecl decl = (XMLNSDecl)m_declaredPrefixes.elementAt(i);
          String prefix = decl.getPrefix();
          String uri = decl.getURI();
          boolean shouldExclude = excludeResultNSDecl(prefix, uri);
          // Create a new prefix table if one has not already been created.
          if(null == m_prefixTable)
            m_prefixTable = new Vector();
          m_prefixTable.addElement(new XMLNSDecl(prefix, uri, shouldExclude));
        }
      }
      
      ElemTemplateElement parent = (ElemTemplateElement)this.getParentNode();
      if(null != parent)
      {
        // The prefix table of the parent should never be null!
        Vector prefixes = parent.m_prefixTable;
        if(null == m_prefixTable)
        {
          // Nothing to combine, so just use parent's table!
          this.m_prefixTable = parent.m_prefixTable;
        }
        else
        {
          // Add the prefixes from the parent's prefix table.
          int n = prefixes.size();
          for(int i = 0; i < n; i++)
          {
            XMLNSDecl decl = (XMLNSDecl)prefixes.elementAt(i);
            boolean shouldExclude 
              = excludeResultNSDecl(decl.getPrefix(), decl.getURI());
            if(shouldExclude != decl.getIsExcluded())
            {
              decl = new XMLNSDecl(decl.getPrefix(), decl.getURI(), 
shouldExclude);
            }
  
            m_prefixTable.addElement(decl);
          }
  
        }
      }
      else if(null == m_prefixTable)
      {
        // Must be stylesheet element without any result prefixes!
        m_prefixTable = new Vector();
      }
      
      // Resolve the children's prefix tables.
      for(ElemTemplateElement child = m_firstChild; 
          child != null; child = child.m_nextSibling)
      {
        child.resolvePrefixTables();
      }
    }
    
    /**
     * Send startPrefixMapping events to the result tree handler 
     * for all declared prefix mappings in the stylesheet.
     */
    void executeNSDecls(TransformerImpl transformer)
      throws SAXException
    {
      ResultTreeHandler rhandler = transformer.getResultTreeHandler();
      int n = m_prefixTable.size();
      for(int i = 0; i < n; i++)
      {
        XMLNSDecl decl = (XMLNSDecl)m_prefixTable.elementAt(i);
        if(!decl.getIsExcluded())
        {
          rhandler.startPrefixMapping(decl.getPrefix(), decl.getURI());
        }
      }    
    }
      
    /** 
     * Parent node.
     * @serial
     */
    protected ElemTemplateElement m_parentNode;
  
    /** 
     * Get the parent as a Node.
     */
    public Node getParentNode()
    {
      return m_parentNode;
    }
  
    /** 
     * Get the parent as a Node.
     */
    public ElemTemplateElement getParentElem()
    {
      return m_parentNode;
    }
  
    /** 
     * Next sibling.
     * @serial
     */
    protected ElemTemplateElement m_nextSibling;
    
    /** 
     * Get the next sibling (as a Node) or return null.
     */
    public Node getNextSibling()
    {
      return m_nextSibling;
    }
  
    /** 
     * Get the next sibling (as a ElemTemplateElement) or return null.
     */
    public ElemTemplateElement getNextSiblingElem()
    {
      return m_nextSibling;
    }
    
    /** 
     * First child.
     * @serial
     */
    protected ElemTemplateElement m_firstChild;
    
    /** 
     * Get the first child as a Node.
     */
    public Node getFirstChild()
    {
      return m_firstChild;
    }
    
    /** 
     * Get the first child as a ElemTemplateElement.
     */
    public ElemTemplateElement getFirstChildElem()
    {
      return m_firstChild;
    }
    
    /** Get the last child.
     */
    public Node               getLastChild()
    {
      ElemTemplateElement lastChild = null;
      for (ElemTemplateElement node = m_firstChild; 
           node != null; node = node.m_nextSibling) 
      {
        lastChild = node;
      }
      return lastChild;
    }
  
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemText.java
  
  Index: ElemText.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  import java.io.*;
  import java.util.*;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:template.
   * This primarily acts as a marker on the element 
   * stack to signal that whitespace should be preserved.
   * <pre>
   * <!ELEMENT xsl:text (#PCDATA)>
   * <!ATTLIST xsl:text
   *   disable-output-escaping (yes|no) "no"
   * >
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-Text";>section-Creating-Text in 
XSLT Specification</a>
   */
  public class ElemText extends ElemTemplateElement
  {
    /**
     * Tells if this element should disable escaping.
     */
    private boolean m_disableOutputEscaping = false;
    
    /**
     * Set the "disable-output-escaping" attribute. 
     * Normally, the xml output method escapes & and < (and 
     * possibly other characters) when outputting text nodes. 
     * This ensures that the output is well-formed XML. However, 
     * it is sometimes convenient to be able to produce output 
     * that is almost, but not quite well-formed XML; for 
     * example, the output may include ill-formed sections 
     * which are intended to be transformed into well-formed 
     * XML by a subsequent non-XML aware process. For this reason, 
     * XSLT provides a mechanism for disabling output escaping. 
     * An xsl:value-of or xsl:text element may have a 
     * disable-output-escaping attribute; the allowed values 
     * are yes or no; the default is no; if the value is yes, 
     * then a text node generated by instantiating the xsl:value-of 
     * or xsl:text element should be output without any escaping.  
     * @see <a 
href="http://www.w3.org/TR/xslt#disable-output-escaping";>disable-output-escaping
 in XSLT Specification</a>
     */
    public void setDisableOutputEscaping(boolean v)
    {
      m_disableOutputEscaping = v;
    }
  
    /**
     * Get the "disable-output-escaping" attribute. 
     * Normally, the xml output method escapes & and < (and 
     * possibly other characters) when outputting text nodes. 
     * This ensures that the output is well-formed XML. However, 
     * it is sometimes convenient to be able to produce output 
     * that is almost, but not quite well-formed XML; for 
     * example, the output may include ill-formed sections 
     * which are intended to be transformed into well-formed 
     * XML by a subsequent non-XML aware process. For this reason, 
     * XSLT provides a mechanism for disabling output escaping. 
     * An xsl:value-of or xsl:text element may have a 
     * disable-output-escaping attribute; the allowed values 
     * are yes or no; the default is no; if the value is yes, 
     * then a text node generated by instantiating the xsl:value-of 
     * or xsl:text element should be output without any escaping.  
     * @see <a 
href="http://www.w3.org/TR/xslt#disable-output-escaping";>disable-output-escaping
 in XSLT Specification</a>
     */
    public boolean getDisableOutputEscaping()
    {
      return m_disableOutputEscaping;
    }
    
    /** 
     * Get an integer representation of the element type.
     * 
     * @return An integer representation of the element, defined in the 
     *     Constants class.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_TEXT;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_TEXT_STRING;
    }
    
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      int type = ((ElemTemplateElement)newChild).getXSLToken();
      switch(type)
      {
      case Constants.ELEMNAME_TEXTLITERALRESULT:
  
        break;
        
      default:
        error(XSLTErrorResources.ER_CANNOT_ADD, new 
Object[]{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
              //" to " + this.m_elemName);
      }
      return super.appendChild(newChild);
    }
  
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemTextLiteral.java
  
  Index: ElemTextLiteral.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement a text literal.
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Creating-Text";>section-Creating-Text in 
XSLT Specification</a>
   */
  public class ElemTextLiteral extends ElemTemplateElement
  {  
    /**
     * Tell if space should be preserved.
     */
    private boolean m_preserveSpace;
    
    /**
     * Set whether or not space should be preserved.
     */
    public void setPreserveSpace(boolean v)
    {
      m_preserveSpace = v;
    }
  
    /**
     * Get whether or not space should be preserved.
     */
    public boolean getPreserveSpace()
    {
      return m_preserveSpace;
    }
    
    /**
     * The character array.
     */
    private char m_ch[];
    
    /**
     * Set the characters that will be output to the result tree.. 
     */
    public void setChars(char[] v)
    {
      m_ch = v;
    }
  
    /**
     * Get the characters that will be output to the result tree.. 
     */
    public char[] getChars()
    {
      return m_ch;
    }
    
    /**
     * Tells if this element should disable escaping.
     */
    private boolean m_disableOutputEscaping = false;
    
    /**
     * Set the "disable-output-escaping" attribute. 
     * Normally, the xml output method escapes & and < (and 
     * possibly other characters) when outputting text nodes. 
     * This ensures that the output is well-formed XML. However, 
     * it is sometimes convenient to be able to produce output 
     * that is almost, but not quite well-formed XML; for 
     * example, the output may include ill-formed sections 
     * which are intended to be transformed into well-formed 
     * XML by a subsequent non-XML aware process. For this reason, 
     * XSLT provides a mechanism for disabling output escaping. 
     * An xsl:value-of or xsl:text element may have a 
     * disable-output-escaping attribute; the allowed values 
     * are yes or no; the default is no; if the value is yes, 
     * then a text node generated by instantiating the xsl:value-of 
     * or xsl:text element should be output without any escaping.  
     * @see <a 
href="http://www.w3.org/TR/xslt#disable-output-escaping";>disable-output-escaping
 in XSLT Specification</a>
     */
    public void setDisableOutputEscaping(boolean v)
    {
      m_disableOutputEscaping = v;
    }
  
    /**
     * Get the "disable-output-escaping" attribute. 
     * Normally, the xml output method escapes & and < (and 
     * possibly other characters) when outputting text nodes. 
     * This ensures that the output is well-formed XML. However, 
     * it is sometimes convenient to be able to produce output 
     * that is almost, but not quite well-formed XML; for 
     * example, the output may include ill-formed sections 
     * which are intended to be transformed into well-formed 
     * XML by a subsequent non-XML aware process. For this reason, 
     * XSLT provides a mechanism for disabling output escaping. 
     * An xsl:value-of or xsl:text element may have a 
     * disable-output-escaping attribute; the allowed values 
     * are yes or no; the default is no; if the value is yes, 
     * then a text node generated by instantiating the xsl:value-of 
     * or xsl:text element should be output without any escaping.  
     * @see <a 
href="http://www.w3.org/TR/xslt#disable-output-escaping";>disable-output-escaping
 in XSLT Specification</a>
     */
    public boolean getDisableOutputEscaping()
    {
      return m_disableOutputEscaping;
    }
  
    /** 
     * Get an integer representation of the element type.
     * 
     * @return An integer representation of the element, defined in the 
     *     Constants class.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_TEXTLITERALRESULT;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return "#Text";
    }
    
    /**
     * Copy the text literal to the result tree.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      if(!m_disableOutputEscaping)
      {
        transformer.getResultTreeHandler().characters(m_ch, 0, m_ch.length);
      }
      else
      {
        transformer.getResultTreeHandler().charactersRaw(m_ch, 0, m_ch.length);
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemUse.java
  
  Index: ElemUse.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import java.util.Vector;
  import org.w3c.dom.Node;
  import org.xml.sax.SAXException;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import java.util.StringTokenizer;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:use.
   * This acts as a superclass for ElemCopy, ElemAttributeSet,
   * ElemElement, and ElemLiteralResult, on order to implement 
   * shared behavior the use-attribute-sets attribute.
   * @see <a href="http://www.w3.org/TR/xslt#attribute-sets";>attribute-sets in 
XSLT Specification</a>
   */
  public class ElemUse extends ElemTemplateElement
  {
    /**
     * The value of the "use-attribute-sets" attribute.
     */
    private QName m_attributeSetsNames[] = null;
  
    /**
     * Set the "use-attribute-sets" attribute. 
     * Attribute sets are used by specifying a use-attribute-sets 
     * attribute on xsl:element, xsl:copy (see [7.5 Copying]) or 
     * xsl:attribute-set elements. The value of the use-attribute-sets 
     * attribute is a whitespace-separated list of names of attribute 
     * sets. Each name is specified as a QName, which is expanded as 
     * described in [2.4 Qualified Names].  
     */
    public void setUseAttributeSets (Vector v)
    {
      int n = v.size();
      m_attributeSetsNames = new QName[n];
      for(int i = 0; i < n; i++)
      {
        m_attributeSetsNames[i] = (QName)v.elementAt(i);
      }
    }
    
    /**
     * Set the "use-attribute-sets" attribute. 
     * Attribute sets are used by specifying a use-attribute-sets 
     * attribute on xsl:element, xsl:copy (see [7.5 Copying]) or 
     * xsl:attribute-set elements. The value of the use-attribute-sets 
     * attribute is a whitespace-separated list of names of attribute 
     * sets. Each name is specified as a QName, which is expanded as 
     * described in [2.4 Qualified Names].  
     */
    public void setUseAttributeSets (QName[] v)
    {
      m_attributeSetsNames = v;
    }
  
    /**
     * Get the "use-attribute-sets" attribute. 
     * Attribute sets are used by specifying a use-attribute-sets 
     * attribute on xsl:element, xsl:copy (see [7.5 Copying]) or 
     * xsl:attribute-set elements, or a xsl:use-attribute-sets attribute on
     * Literal Result Elements. 
     * The value of the use-attribute-sets 
     * attribute is a whitespace-separated list of names of attribute 
     * sets. Each name is specified as a QName, which is expanded as 
     * described in [2.4 Qualified Names].  
     */
    public QName[] getUseAttributeSets()
    {
      return m_attributeSetsNames;
    }
    
    /**
     * Add the attributes from the named attribute sets to the attribute list.
     * TODO: Error handling for: "It is an error if there are two attribute sets
     * with the same expanded-name and with equal import precedence and that 
both
     * contain the same attribute unless there is a definition of the attribute
     * set with higher import precedence that also contains the attribute."
     */
    private void applyAttrSets(TransformerImpl transformer,
                               StylesheetComposed stylesheet,
                               QName attributeSetsNames[],
                               Node sourceNode,
                               QName mode)
      throws SAXException
    {
      if(null != attributeSetsNames)
      {
        int nNames = attributeSetsNames.length;
        for(int i = 0; i < nNames; i++)
        {
          QName qname = attributeSetsNames[i];
          Vector attrSets = stylesheet.getAttributeSetComposed(qname);
          int nSets = attrSets.size();
          for(int k = 0; k < nSets; k++)
          {
            ElemAttributeSet attrSet = (ElemAttributeSet)attrSets.elementAt(k);
            attrSet.execute(transformer, sourceNode, mode);
          }
        }
      }
    }
  
    
    /**
     * Copy attributes specified by use-attribute-sets to the result tree.
     * Specifying a use-attribute-sets attribute is equivalent to adding 
     * xsl:attribute elements for each of the attributes in each of the 
     * named attribute sets to the beginning of the content of the element 
     * with the use-attribute-sets attribute, in the same order in which 
     * the names of the attribute sets are specified in the use-attribute-sets 
     * attribute. It is an error if use of use-attribute-sets attributes 
     * on xsl:attribute-set elements causes an attribute set to directly 
     * or indirectly use itself.
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      if(null != m_attributeSetsNames)
      {
        applyAttrSets(transformer, 
                      getStylesheetComposed(),
                      m_attributeSetsNames, 
                      sourceNode, mode);
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemValueOf.java
  
  Index: ElemValueOf.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.trace.SelectionEvent;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:value-of.
   * <pre>
   * <!ELEMENT xsl:value-of EMPTY>
   * <!ATTLIST xsl:value-of
   *   select %expr; #REQUIRED
   *   disable-output-escaping (yes|no) "no"
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#value-of";>value-of in XSLT 
Specification</a>
   */
  public class ElemValueOf extends ElemTemplateElement
  {
    /**
     * The select expression to be executed.
     */
    private XPath m_selectExpression = null;
    
    /**
     * Set the "select" attribute. 
     * The required select attribute is an expression; this expression 
     * is evaluated and the resulting object is converted to a 
     * string as if by a call to the string function.  
     */
    public void setSelect(XPath v)
    {
      m_selectExpression = v;
    }
  
    /**
     * Get the "select" attribute. 
     * The required select attribute is an expression; this expression 
     * is evaluated and the resulting object is converted to a 
     * string as if by a call to the string function.  
     */
    public XPath getSelect()
    {
      return m_selectExpression;
    }
    
    /**
     * Tells if this element should disable escaping.
     */
    private boolean m_disableOutputEscaping = false;
    
    /**
     * Set the "disable-output-escaping" attribute. 
     * Normally, the xml output method escapes & and < (and 
     * possibly other characters) when outputting text nodes. 
     * This ensures that the output is well-formed XML. However, 
     * it is sometimes convenient to be able to produce output 
     * that is almost, but not quite well-formed XML; for 
     * example, the output may include ill-formed sections 
     * which are intended to be transformed into well-formed 
     * XML by a subsequent non-XML aware process. For this reason, 
     * XSLT provides a mechanism for disabling output escaping. 
     * An xsl:value-of or xsl:text element may have a 
     * disable-output-escaping attribute; the allowed values 
     * are yes or no; the default is no; if the value is yes, 
     * then a text node generated by instantiating the xsl:value-of 
     * or xsl:text element should be output without any escaping.  
     * @see <a 
href="http://www.w3.org/TR/xslt#disable-output-escaping";>disable-output-escaping
 in XSLT Specification</a>
     */
    public void setDisableOutputEscaping(boolean v)
    {
      m_disableOutputEscaping = v;
    }
  
    /**
     * Get the "disable-output-escaping" attribute. 
     * Normally, the xml output method escapes & and < (and 
     * possibly other characters) when outputting text nodes. 
     * This ensures that the output is well-formed XML. However, 
     * it is sometimes convenient to be able to produce output 
     * that is almost, but not quite well-formed XML; for 
     * example, the output may include ill-formed sections 
     * which are intended to be transformed into well-formed 
     * XML by a subsequent non-XML aware process. For this reason, 
     * XSLT provides a mechanism for disabling output escaping. 
     * An xsl:value-of or xsl:text element may have a 
     * disable-output-escaping attribute; the allowed values 
     * are yes or no; the default is no; if the value is yes, 
     * then a text node generated by instantiating the xsl:value-of 
     * or xsl:text element should be output without any escaping.  
     * @see <a 
href="http://www.w3.org/TR/xslt#disable-output-escaping";>disable-output-escaping
 in XSLT Specification</a>
     */
    public boolean getDisableOutputEscaping()
    {
      return m_disableOutputEscaping;
    }
    
    /**
     * Optimization to tell if pattern is a simple ".".
     */
    private boolean isDot = false;
  
    /** 
     * Get an integer representation of the element type.
     * 
     * @return An integer representation of the element, defined in the 
     *     Constants class.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_VALUEOF;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_VALUEOF_STRING;
    }
  
    /**
     * Execute the string expression and copy the text to the 
     * result tree.
     * The required select attribute is an expression; this expression 
     * is evaluated and the resulting object is converted to a string 
     * as if by a call to the string function. The string specifies 
     * the string-value of the created text node. If the string is 
     * empty, no text node will be created. The created text node will 
     * be merged with any adjacent text nodes.
     * @see <a href="http://www.w3.org/TR/xslt#value-of";>value-of in XSLT 
Specification</a>
     */
    public void execute(TransformerImpl transformer, 
                        Node sourceNode,
                        QName mode)
      throws SAXException
    {    
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      if(isDot)
      {
        String s;
        
        int t = sourceNode.getNodeType();
        if(((Node.COMMENT_NODE ==t) || 
            (Node.PROCESSING_INSTRUCTION_NODE == t)))
        {
          s = sourceNode.getNodeValue();
        }
        else
        {
          s = org.apache.xalan.xpath.DOMHelper.getNodeData(sourceNode);
        }
  
        if(TransformerImpl.S_DEBUG)
          transformer.getTraceManager().fireSelectedEvent(sourceNode,
                                        this, "select", m_selectExpression, new 
XString(s));
        
        if(null != s)
        {
          int len = s.length();
          if(len > 0)
          {
            if(!m_disableOutputEscaping)
            {
              transformer.getResultTreeHandler().characters(s.toCharArray(), 0, 
s.length());
            }
            else
            {
              transformer.getResultTreeHandler().charactersRaw(s.toCharArray(), 
0, s.length());
            }
          }
        }
  
      }
      else
      {
        XObject value = 
m_selectExpression.execute(transformer.getXPathContext(), 
                                                   sourceNode, this);
        
        if(TransformerImpl.S_DEBUG)
          transformer.getTraceManager().fireSelectedEvent(sourceNode,
                                        this, "select", m_selectExpression, 
value);
        if(null != value)
        {
          int type = value.getType();
          if(XObject.CLASS_NULL != type)
          {
            String s = value.str();
            if(null != s)
            {
              int len = s.length();
              if(len > 0)
              {
                if(!m_disableOutputEscaping)
                {
                  
transformer.getResultTreeHandler().characters(s.toCharArray(), 0, s.length());
                }
                else
                {
                  
transformer.getResultTreeHandler().charactersRaw(s.toCharArray(), 0, 
s.length());
                }
              }
            }
          }
        }
      }
    }
    
    /**
     * Add a child to the child list.
     */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_CANNOT_ADD, new Object[] 
{newChild.getNodeName(), this.getNodeName()}); //"Can not add " 
+((ElemTemplateElement)newChild).m_elemName +
      //" to " + this.m_elemName);
      return null;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemVariable.java
  
  Index: ElemVariable.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.trace.SelectionEvent;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:variable.
   * <pre>
   * <!ELEMENT xsl:variable %template;>
   * <!ATTLIST xsl:variable 
   *   name %qname; #REQUIRED
   *   select %expr; #IMPLIED
   * >
   * </pre>
   * @see <a href="http://www.w3.org/TR/xslt#variables";>variables in XSLT 
Specification</a>
   */
  public class ElemVariable extends ElemTemplateElement
  {
    public ElemVariable()
    {
    }
  
    /**
     * The value of the "select" attribute.
     */
    private XPath m_selectPattern;
    
    /**
     * Set the "select" attribute. 
     * If the variable-binding element has a select attribute, 
     * then the value of the attribute must be an expression and 
     * the value of the variable is the object that results from 
     * evaluating the expression. In this case, the content
     * of the variable must be empty.
     */
    public void setSelect(XPath v)
    {
      m_selectPattern = v;
    }
  
    /**
     * Get the "select" attribute. 
     * If the variable-binding element has a select attribute, 
     * then the value of the attribute must be an expression and 
     * the value of the variable is the object that results from 
     * evaluating the expression. In this case, the content
     * of the variable must be empty.
     */
    public XPath getSelect()
    {
      return m_selectPattern;
    }
    
    /**
     * The value of the "name" attribute.
     */
    private QName m_qname;
    
    /**
     * Set the "name" attribute. 
     * Both xsl:variable and xsl:param have a required name 
     * attribute, which specifies the name of the variable. The 
     * value of the name attribute is a QName, which is expanded 
     * as described in [2.4 Qualified Names].
     * @see <a href="http://www.w3.org/TR/xslt#qname";>qname in XSLT 
Specification</a>
     */
    public void setName(QName v)
    {
      m_qname = v;
    }
  
    /**
     * Get the "name" attribute. 
     * Both xsl:variable and xsl:param have a required name 
     * attribute, which specifies the name of the variable. The 
     * value of the name attribute is a QName, which is expanded 
     * as described in [2.4 Qualified Names].
     * @see <a href="http://www.w3.org/TR/xslt#qname";>qname in XSLT 
Specification</a>
     */
    public QName getName()
    {
      return m_qname;
    }
    
    /**
     * Tells if this is a top-level variable or param, or not.
     */
    private boolean m_isTopLevel = false;
    
    /**
     * Set if this is a top-level variable or param, or not.
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public void setIsTopLevel(boolean v)
    {
      m_isTopLevel = v;
    }
  
    /**
     * Get if this is a top-level variable or param, or not.
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public boolean getIsTopLevel()
    {
      return m_isTopLevel;
    }
    
    /** 
     * Get an integer representation of the element type.
     * 
     * @return An integer representation of the element, defined in the 
     *     Constants class.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_VARIABLE;
    }
    
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_VARIABLE_STRING;
    }
  
    
    /**
     * Copy constructor.
     */
    public ElemVariable (ElemVariable param)
      throws SAXException
    {
      m_selectPattern = param.m_selectPattern;
      m_qname = param.m_qname;
      m_isTopLevel = param.m_isTopLevel;
      // m_value = param.m_value;
      // m_varContext = param.m_varContext;
    }
    
    /**
     * Execute a variable declaration and push it onto the variable stack.
     * @see <a href="http://www.w3.org/TR/xslt#variables";>variables in XSLT 
Specification</a>
     */
    public void execute(TransformerImpl transformer, 
                       Node sourceNode,
                       QName mode)
      throws SAXException
    {    
      if(TransformerImpl.S_DEBUG)
        transformer.getTraceManager().fireTraceEvent(sourceNode, mode, this);
  
      XObject var = getValue(transformer, sourceNode);
      transformer.getXPathContext().getVarStack().pushVariable(m_qname, var);
    }
    
    /**
     * Get the XObject representation of the variable.
     */
    public XObject getValue(TransformerImpl transformer, 
                       Node sourceNode)
      throws SAXException
    {
      XObject var;
      if(null != m_selectPattern)
      {
        XPathContext xctxt = transformer.getXPathContext();
        var = m_selectPattern.execute(xctxt, sourceNode, this);
        if(TransformerImpl.S_DEBUG)
          transformer.getTraceManager().fireSelectedEvent(sourceNode, this, 
                                        "select", m_selectPattern, var);
      }
      else
      {
        // Use result tree fragment
        DocumentFragment df = transformer.transformToRTF(getStylesheet(), this, 
                                                         sourceNode, null);
        var = new XRTreeFrag(df);
      }
      return var;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemWhen.java
  
  Index: ElemWhen.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:when.
   * <pre>
   * <!ELEMENT xsl:when %template;>
   * <!ATTLIST xsl:when
   *   test %expr; #REQUIRED
   *   %space-att;
   * >
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Conditional-Processing-with-xsl:choose";>XXX
 in XSLT Specification</a>
   */
  public class ElemWhen extends ElemTemplateElement
  {
    /**
     * Each xsl:when element has a single attribute, test, 
     * which specifies an expression. 
     */
    private XPath m_test;
  
    /**
     * Set the "test" attribute. 
     * Each xsl:when element has a single attribute, test, 
     * which specifies an expression. 
     */
    public void setTest(XPath v)
    {
      m_test = v;
    }
  
    /**
     * Get the "test" attribute. 
     * Each xsl:when element has a single attribute, test, 
     * which specifies an expression. 
     */
    public XPath getTest()
    {
      return m_test;
    }
  
    /** 
     * Get an integer representation of the element type.
     * 
     * @return An integer representation of the element, defined in the 
     *     Constants class.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_WHEN;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_WHEN_STRING;
    }
  
    public ElemWhen()
    {
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/ElemWithParam.java
  
  Index: ElemWithParam.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement xsl:with-param.  xsl:with-param is allowed within 
   * both xsl:call-template and xsl:apply-templates.
   * <pre>
   * <!ELEMENT xsl:with-param %template;>
   * <!ATTLIST xsl:with-param
   *   name %qname; #REQUIRED
   *   select %expr; #IMPLIED
   * >
   * </pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#element-with-param";>element-with-param in XSLT 
Specification</a>
   */
  public class ElemWithParam extends ElemTemplateElement
  {
    /**
     * The "select" attribute, which specifies the value of the 
     * argument, if element content is not specified.
     */
    private XPath m_selectPattern = null;
    
    /**
     * Set the "select" attribute. 
     * The "select" attribute specifies the value of the 
     * argument, if element content is not specified.
     */
    public void setSelect(XPath v)
    {
      m_selectPattern = v;
    }
  
    /**
     * Get the "select" attribute. 
     * The "select" attribute specifies the value of the 
     * argument, if element content is not specified.
     */
    public XPath getSelect()
    {
      return m_selectPattern;
    }
    
    /**
     * The required name attribute specifies the name of the 
     * parameter (the variable the value of whose binding is 
     * to be replaced). The value of the name attribute is a QName, 
     * which is expanded as described in [2.4 Qualified Names]. 
     */
    private QName m_qname = null;
  
    /**
     * Set the "name" attribute. 
     * DJD 
     */
    public void setName(QName v)
    {
      m_qname = v;
    }
  
    /**
     * Get the "name" attribute. 
     * DJD 
     */
    public QName getName()
    {
      return m_qname;
    }
    
    /** 
     * Get an integer representation of the element type.
     * 
     * @return An integer representation of the element, defined in the 
     *     Constants class.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_WITHPARAM;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_WITHPARAM_STRING;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/FuncDocument.java
  
  Index: FuncDocument.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import java.util.Vector;
  
  import org.w3c.dom.Document;
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.functions.Function;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNodeSet;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.DOMHelper;
  import org.apache.xalan.xpath.SourceTreeManager;
  
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.xpath.XPathContext;
  
  import org.apache.xalan.transformer.TransformerImpl;
  
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.InputSource;
  import org.xml.sax.Locator;
  
  import trax.TransformException;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Doc() function.
   * 
   * When the document function has exactly one argument and the argument 
   * is a node-set, then the result is the union, for each node in the 
   * argument node-set, of the result of calling the document function with 
   * the first argument being the string-value of the node, and the second 
   * argument being a node-set with the node as its only member. When the 
   * document function has two arguments and the first argument is a node-set, 
   * then the result is the union, for each node in the argument node-set, 
   * of the result of calling the document function with the first argument 
   * being the string-value of the node, and with the second argument being 
   * the second argument passed to the document function.
   */
  public class FuncDocument extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      Document docContext = (Node.DOCUMENT_NODE == context.getNodeType()) 
                            ? (Document)context : context.getOwnerDocument();
      XObject arg = (XObject)args.elementAt(0);
      String base = "";
      if(args.size() > 1)
      {
        // The URI reference may be relative. The base URI (see [3.2 Base URI]) 
        // of the node in the second argument node-set that is first in 
document 
        // order is used as the base URI for resolving the 
        // relative URI into an absolute URI. 
        XObject arg2 = (XObject)args.elementAt(1);
        if(XObject.CLASS_NODESET == arg2.getType())
        {
          Node baseNode = arg2.nodeset().nextNode();
          Document baseDoc = (Node.DOCUMENT_NODE == baseNode.getNodeType()) ? 
                             (Document)baseNode : baseNode.getOwnerDocument();
          
          if(baseDoc instanceof Stylesheet)
          {
            // base = ((Stylesheet)baseDoc).getBaseIdentifier();
            base = xctxt.getNamespaceContext().getBaseIdentifier();   
          }
          else
            base = xctxt.getSourceTreeManager().findURIFromDoc(baseDoc);
        }
        else
        {
          base = arg2.str();
        }
       
      }
      else
      {
        // If the second argument is omitted, then it defaults to 
        // the node in the stylesheet that contains the expression that 
        // includes the call to the document function. Note that a 
        // zero-length URI reference is a reference to the document 
        // relative to which the URI reference is being resolved; thus 
        // document("") refers to the root node of the stylesheet; 
        // the tree representation of the stylesheet is exactly 
        // the same as if the XML document containing the stylesheet 
        // was the initial source document.
        base = xctxt.getNamespaceContext().getBaseIdentifier();
      }
        
      XNodeSet nodes = new XNodeSet();
      NodeSet mnl = nodes.mutableNodeset();
      NodeIterator iterator = (XObject.CLASS_NODESET == arg.getType()) ?
                              arg.nodeset() : null;
      Node pos = null;
      while((null == iterator) || (null != (pos = iterator.nextNode())))
      {
        String ref = (null != iterator)
                        ? DOMHelper.getNodeData(pos) : arg.str();
        if(null == ref)
          continue;
        if(null == docContext)
        {
          error(xctxt, XSLTErrorResources.ER_NO_CONTEXT_OWNERDOC, null); 
//"context does not have an owner document!");
        }
          
        // From http://www.ics.uci.edu/pub/ietf/uri/rfc1630.txt
        // A partial form can be distinguished from an absolute form in that the
        // latter must have a colon and that colon must occur before any slash
        // characters. Systems not requiring partial forms should not use any
        // unencoded slashes in their naming schemes.  If they do, absolute URIs
        // will still work, but confusion may result.
        int indexOfColon = ref.indexOf(':');
        int indexOfSlash = ref.indexOf('/');
        if((indexOfColon != -1) && (indexOfSlash != -1) && (indexOfColon < 
indexOfSlash))
        {
          // The url (or filename, for that matter) is absolute.
          base = null;
        }
        
        Node newDoc = getDoc(path, xctxt, context, ref, base);
        // nodes.mutableNodeset().addNode(newDoc);  
        if(null != newDoc)
        {
          // TODO: mnl.addNodeInDocOrder(newDoc, true, xctxt); ??
          mnl.addElement(newDoc);
        }
        
        if(null == iterator)
          break;
      }
      return nodes;
    }
    
    /**
     * HandleDocExpr
     */
    Node getDoc(XPath path, XPathContext xctxt, Node context, String uri, 
String base)
      throws org.xml.sax.SAXException
    {
      SourceTreeManager treeMgr = xctxt.getSourceTreeManager();
      Node newDoc = treeMgr.findNodeFromURL(uri);
      if(null == newDoc)
      {
        if(uri.length() == 0)
        {
          uri = xctxt.getNamespaceContext().getBaseIdentifier();
        }
        // TransformerImpl transformer = (TransformerImpl)xctxt;
        TransformerImpl transformer = (TransformerImpl)xctxt.getOwnerObject();
        
        { 
          java.net.URL url = null;
          try
          {
            url = xctxt.getURLFromString(uri, base);
            if((null != url) && (url.toString().length() > 0))
            {
              InputSource inputSource = new InputSource(url.toString());
              // System.out.println("Trying to parse: "+url.toString());
              newDoc = transformer.parseToNode(inputSource);
            }
            else
            {
              warn(xctxt, XSLTErrorResources.WG_CANNOT_MAKE_URL_FROM, new 
Object[]{((base == null) ? "" : base )+uri}); //"Can not make URL from: 
"+((base == null) ? "" : base )+uri);
            }
          }
          catch(Exception e)
          {
            newDoc = null;
            // 
path.warn(XSLTErrorResources.WG_ENCODING_NOT_SUPPORTED_USING_JAVA, new 
Object[]{((base == null) ? "" : base )+uri}); //"Can not load requested doc: 
"+((base == null) ? "" : base )+uri);
          }
          if(null == newDoc)
          {
            warn(xctxt, XSLTErrorResources.WG_CANNOT_LOAD_REQUESTED_DOC, new 
Object[]{url== null ?((base == null) ? "" : base)+uri : url.toString()}); 
//"Can not load requested doc: "+((base == null) ? "" : base )+uri);
          }
          else
          {
            // TBD: What to do about XLocator?
            xctxt.getSourceTreeManager().associateXLocatorToNode(newDoc, url, 
null);
          }
        }
      }
      return newDoc;
    }
    
    /**
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void error(XPathContext xctxt, int msg, Object args[])
          throws org.xml.sax.SAXException
    {   
          String formattedMsg = XSLMessages.createMessage(msg, args);
      
      ErrorHandler errHandler = xctxt.getPrimaryReader().getErrorHandler();
      TransformException te = new TransformException(formattedMsg, 
                                                     xctxt.getSAXLocator());
                                                     
      if(null != errHandler)
        errHandler.error(te);
      else
      {
        System.out.println(te.getMessage()
                           +"; file "+te.getSystemId()
                           +"; line "+te.getLineNumber()
                           +"; column "+te.getColumnNumber());
      }
    }
    
    /**
     * Warn the user of a problem.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void warn(XPathContext xctxt, int msg, Object args[])
      throws org.xml.sax.SAXException
    {
      String formattedMsg = XSLMessages.createWarning(msg, args);
      
      ErrorHandler errHandler = xctxt.getPrimaryReader().getErrorHandler();
      TransformException te = new TransformException(formattedMsg, 
                                                     xctxt.getSAXLocator());
                                                     
      if(null != errHandler)
        errHandler.warning(te);
      else
      {
        System.out.println(te.getMessage()
                           +"; file "+te.getSystemId()
                           +"; line "+te.getLineNumber()
                           +"; column "+te.getColumnNumber());
      }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/FuncFormatNumb.java
  
  Index: FuncFormatNumb.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import java.util.Vector;
  
  import org.apache.xalan.utils.QName;
  
  import org.apache.xalan.xpath.functions.Function;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  import org.apache.xalan.xpath.XPath;
  
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.res.XSLTErrorResources;
  
  import org.xml.sax.ErrorHandler;
  
  import org.w3c.dom.Node;
  
  import trax.TransformException;
  
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the FormatNumber() function.
   */
  public class FuncFormatNumb extends Function
  {
    /**
     * Execute the function.  The function must return
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt,
                           Node context, int opPos, Vector args)
      throws org.xml.sax.SAXException
    {
      // A bit of an ugly hack to get our context.
      ElemTemplateElement templElem = 
(ElemTemplateElement)xctxt.getNamespaceContext();
      StylesheetComposed ss = templElem.getStylesheetComposed();
  
      java.text.DecimalFormat formatter = null;
      java.text.DecimalFormatSymbols dfs = null;
      double num = ((XObject)args.elementAt(0)).num();
      String patternStr = ((XObject)args.elementAt(1)).str();
      // TODO: what should be the behavior here??
      if (patternStr.indexOf(0x00A4)> 0)
        ss.error(XSLTErrorResources.ER_CURRENCY_SIGN_ILLEGAL); // currency sign 
not allowed
      int nArgs = args.size();
      // this third argument is not a locale name. It is the name of a
      // decimal-format declared in the stylesheet!(xsl:decimal-format
      try
      {
        if(nArgs == 3)
        {
          String dfName = ((XObject)args.elementAt(2)).str();
          QName qname = new QName(dfName, xctxt.getNamespaceContext());
          dfs = ss.getDecimalFormatComposed(qname);
          if (null == dfs)
          {
            warn(xctxt, XSLTErrorResources.WG_NO_DECIMALFORMAT_DECLARATION, new 
Object[]{dfName}); //"not found!!!
            //formatter = new java.text.DecimalFormat(patternStr);
          }
          else
          {
            //formatter = new java.text.DecimalFormat(patternStr, dfs);
            formatter = new java.text.DecimalFormat();
            formatter.setDecimalFormatSymbols(dfs);
            formatter.applyLocalizedPattern(patternStr);
          }
  
        }
        //else
        if (null == formatter)
        {
          if (null != patternStr)
          {
            formatter = new java.text.DecimalFormat(patternStr);
            formatter.applyLocalizedPattern(patternStr); // fix bug??
          }
          else
            formatter = new java.text.DecimalFormat();
        }
        return new XString(formatter.format(num));
      }
      catch(Exception iae)
      {
        templElem.error(XSLTErrorResources.ER_MALFORMED_FORMAT_STRING, new 
Object[]{patternStr});
        return new XString("");
        //throw new XSLProcessorException(iae);
      }
    }
  
    /**
     * Warn the user of a problem.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void warn(XPathContext xctxt, int msg, Object args[])
      throws org.xml.sax.SAXException
    {
      String formattedMsg = XSLMessages.createWarning(msg, args);
  
      ErrorHandler errHandler = xctxt.getPrimaryReader().getErrorHandler();
      errHandler.warning(new TransformException(formattedMsg));
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/FuncKey.java
  
  Index: FuncKey.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import java.util.Vector;
  import java.util.Hashtable;
  
  import org.apache.xalan.xpath.functions.Function;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNodeSet;
  import org.apache.xalan.xpath.DOMHelper;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.UnionPathIterator;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.transformer.KeyManager;
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.xpath.XPathContext;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import org.w3c.dom.NodeList;
  import org.w3c.dom.traversal.NodeIterator;
  
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Key() function.
   */
  public class FuncKey extends Function
  {
    static private Boolean ISTRUE = new Boolean(true);
    
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, 
                           Node context, int opPos, Vector args) 
      throws org.xml.sax.SAXException
    {
      // TransformerImpl transformer = (TransformerImpl)xctxt;
      TransformerImpl transformer = (TransformerImpl)xctxt.getOwnerObject();
      XNodeSet nodes = null;
      Document docContext = (Node.DOCUMENT_NODE == context.getNodeType()) 
                            ? (Document)context : context.getOwnerDocument();
      if(null == docContext)
      {
        // path.error(context, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC); 
//"context does not have an owner document!");
      }
      if (args.size()!= 2)
      {
        // path.error(XPATHErrorResources.ER_KEY_HAS_TOO_MANY_ARGS);
      }
      String xkeyname = ((XObject)args.elementAt(0)).str();
      QName keyname = new QName(xkeyname, xctxt.getNamespaceContext());
      XObject arg = (XObject)args.elementAt(1);
      boolean argIsNodeSet = (XObject.CLASS_NODESET == arg.getType());
      
      KeyManager kmgr = transformer.getKeyManager();
      if(argIsNodeSet)
      {
        Hashtable usedrefs = null;
        NodeIterator ni = arg.nodeset();
        Node pos;
        UnionPathIterator upi = new UnionPathIterator();
        while(null != (pos = ni.nextNode()))
        {
          String ref = DOMHelper.getNodeData(pos);
          if(null == ref)
            continue;
          if(null == usedrefs)
            usedrefs = new Hashtable();
  
          if(usedrefs.get(ref) != null)
          {
            continue; // We already have 'em.
          }
          else
          {
            // ISTRUE being used as a dummy value.
            usedrefs.put(ref, ISTRUE);
          }
          
          LocPathIterator nl = kmgr.getNodeSetByKey(xctxt, docContext, 
                                             keyname, ref, 
                                             xctxt.getNamespaceContext());
          upi.addIterator(nl);
          //mnodeset.addNodesInDocOrder(nl, xctxt); needed??
        }
        nodes = new XNodeSet(upi);
      }
      else
      {
        String ref = arg.str();
        LocPathIterator nl = kmgr.getNodeSetByKey(xctxt, docContext, 
                                           keyname, ref, 
                                           xctxt.getNamespaceContext());
        nodes = new XNodeSet(nl);
      }
      return nodes;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/KeyDeclaration.java
  
  Index: KeyDeclaration.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.utils.QName;
  
  /**
   * <meta name="usage" content="internal"/>
   * Holds the attribute declarations for the xsl:keys element.
   * A stylesheet declares a set of keys for each document using 
   * the xsl:key element. When this set of keys contains a member 
   * with node x, name y and value z, we say that node x has a key 
   * with name y and value z.
   * @see <a href="http://www.w3.org/TR/xslt#key";>key in XSLT Specification</a>
   */
public class KeyDeclaration extends ElemTemplateElement
{
    /**
     * The "name" property.
     */
  private QName m_name;
    
    /**
     * Set the "name" attribute. 
     * The name attribute specifies the name of the key. The value 
     * of the name attribute is a QName, which is expanded as 
     * described in [2.4 Qualified Names]. 
     */
    public void setName(QName name)
    {
      m_name = name;
    }
  
    /**
     * Get the "name" attribute.
     * The name attribute specifies the name of the key. The value 
     * of the name attribute is a QName, which is expanded as 
     * described in [2.4 Qualified Names]. 
     */
    public QName getName()
    {
      return m_name;
    }
    
    /**
     * The "match" attribute.
     */
    private XPath m_matchPattern = null;
    
    /**
     * Set the "match" attribute.
     * The match attribute is a Pattern; an xsl:key element gives 
     * information about the keys of any node that matches the 
     * pattern specified in the match attribute.  
     * @see <a href="http://www.w3.org/TR/xslt#patterns";>patterns in XSLT 
Specification</a>
     */
    public void setMatch(XPath v)
    {
      m_matchPattern = v;
    }
  
    /**
     * Get the "match" attribute. 
     * The match attribute is a Pattern; an xsl:key element gives 
     * information about the keys of any node that matches the 
     * pattern specified in the match attribute.  
     * @see <a href="http://www.w3.org/TR/xslt#patterns";>patterns in XSLT 
Specification</a>
     */
    public XPath getMatch()
    {
      return m_matchPattern;
    }
    
    /**
     * The "use" attribute.
     */
    private XPath m_use;
    
    /**
     * Set the "use" attribute. 
     * The use attribute is an expression specifying the values 
     * of the key; the expression is evaluated once for each node 
     * that matches the pattern. 
     */
    public void setUse(XPath v)
    {
      m_use = v;
    }
  
    /**
     * Get the "use" attribute. 
     * The use attribute is an expression specifying the values 
     * of the key; the expression is evaluated once for each node 
     * that matches the pattern. 
     */
    public XPath getUse()
    {
      return m_use;
    }
    
    public static int UNBUILT = -1;
    public static int BUILDING = 0;
    public static int BUILT = 1;
    
    private int m_buildState = UNBUILT;
    
    /**
     * Set the state of the build for this key.
     * @param state One of UNBUILT, BUILDING, BUILT.
     */
    public void setBuildState(int state)
    {
      m_buildState = state;
    }
  
    /**
     * Get the state of the build for this key.
     * @return One of UNBUILT, BUILDING, BUILT.
     */
    public int getBuildState()
    {
      return m_buildState;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/NamespaceAlias.java
  
  Index: NamespaceAlias.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  /**
   * Object to hold an xsl:namespace element.
   * A stylesheet can use the xsl:namespace-alias element to declare 
   * that one namespace URI is an alias for another namespace URI. 
   * @see <a 
href="http://www.w3.org/TR/xslt#literal-result-element";>literal-result-element 
in XSLT Specification</a>
   */
  public class NamespaceAlias
  {
    /**
     * The "stylesheet-prefix" attribute
     */
    private String m_StylesheetPrefix;
    
    /**
     * Set the "stylesheet-prefix" attribute. 
     */
    public void setStylesheetPrefix(String v)
    {
      m_StylesheetPrefix = v;
    }
  
    /**
     * Get the "stylesheet-prefix" attribute. 
     */
    public String getStylesheetPrefix()
    {
      return m_StylesheetPrefix;
    }
  
    /**
     * The "result-prefix" attribute
     */
    private String m_ResultPrefix;
    
    /**
     * Set the "result-prefix" attribute. 
     */
    public void setResultPrefix(String v)
    {
      m_ResultPrefix = v;
    }
  
    /**
     * Get the "result-prefix" attribute. 
     */
    public String getResultPrefix()
    {
      return m_ResultPrefix;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/OutputFormatExtended.java
  
  Index: OutputFormatExtended.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.apache.xml.serialize.OutputFormat;
  import java.util.Vector;
  import org.w3c.dom.Document;
  
  import org.apache.xalan.utils.QName;
  
  /**
   * This class extends OutputFormat to act as a bean that 
   * has methods that match the algorithmically generated 
   * method signatures of the processor.  It also has flags 
   * that tell if a given method has been set or not by the 
   * stylesheet.
   */
  public class OutputFormatExtended extends OutputFormat
  {
    // Flag to tell us when to record that an attribute 
    // has been set.
    private boolean m_shouldRecordHasBeenSet = false;
    
    private boolean m_methodHasBeenSet = false;
    public boolean methodHasBeenSet() { return m_methodHasBeenSet; }
    private boolean m_versionHasBeenSet = false;
    public boolean versionHasBeenSet() { return m_versionHasBeenSet; }
    private boolean m_indentingHasBeenSet = false;
    public boolean indentingHasBeenSet() { return m_indentingHasBeenSet; }
    private boolean m_indentHasBeenSet = false;
    public boolean indentHasBeenSet() { return m_indentHasBeenSet; }
    private boolean m_encodingHasBeenSet = false;
    public boolean encodingHasBeenSet() { return m_encodingHasBeenSet; }
    private boolean m_mediaTypeHasBeenSet;
    public boolean mediaTypeHasBeenSet() { return m_mediaTypeHasBeenSet; }
    private boolean m_doctypeSystemHasBeenSet;
    public boolean doctypeSystemHasBeenSet() { return 
m_doctypeSystemHasBeenSet; }
    private boolean m_doctypePublicHasBeenSet;
    public boolean doctypePublicHasBeenSet() { return 
m_doctypePublicHasBeenSet; }
    private boolean m_omitXmlDeclarationHasBeenSet = false;
    public boolean omitXmlDeclarationHasBeenSet() { return 
m_omitXmlDeclarationHasBeenSet; }
    private boolean m_standaloneHasBeenSet = false;
    public boolean standaloneHasBeenSet() { return m_standaloneHasBeenSet; }
    private boolean m_cdataElementsHasBeenSet = false;
    public boolean cdataElementsHasBeenSet() { return 
m_cdataElementsHasBeenSet; }
    private boolean m_nonEscapingElementsHasBeenSet = false;
    public boolean nonEscapingElementsHasBeenSet() { return 
m_nonEscapingElementsHasBeenSet; }
    
    /**
     * Constructs a new output format with the default values.
     */
    public OutputFormatExtended()
    {
      super();
      m_shouldRecordHasBeenSet = true;
      setPreserveSpace(true);
    }
  
    /**
     * Constructs a new output format with the default values for
     * the specified method and encoding. If <tt>indent</tt>
     * is true, the document will be pretty printed with the default
     * indentation level and default line wrapping.
     *
     * @param method The specified output method
     * @param encoding The specified encoding
     * @param indenting True for pretty printing
     * @see #setEncoding
     * @see #setIndenting
     * @see #setMethod
     */
    public OutputFormatExtended( String method, String encoding, boolean 
indenting )
    {
      super(method, encoding, indenting);
      m_shouldRecordHasBeenSet = true;
    }
  
    /**
     * Constructs a new output format with the proper method,
     * document type identifiers and media type for the specified
     * document.
     *
     * @param doc The document to output
     * @see #whichMethod
     */
    public OutputFormatExtended( Document doc )
    {
      super(doc);
      m_shouldRecordHasBeenSet = true;
    }
    
    /**
     * Constructs a new output format with the proper method,
     * document type identifiers and media type for the specified
     * document, and with the specified encoding. If <tt>indent</tt>
     * is true, the document will be pretty printed with the default
     * indentation level and default line wrapping.
     *
     * @param doc The document to output
     * @param encoding The specified encoding
     * @param indenting True for pretty printing
     * @see #setEncoding
     * @see #setIndenting
     * @see #whichMethod
     */
    public OutputFormatExtended( Document doc, String encoding, boolean 
indenting )
    {
      super(doc, encoding, indenting);
      m_shouldRecordHasBeenSet = true;
    }
    
    /**
     * The doctype-public attribute.
     */
    public void setDoctypePublic ( String publicId )
    {
      if(m_shouldRecordHasBeenSet)
        m_doctypePublicHasBeenSet = true;
      super.setDoctype(publicId, this.getDoctypeSystem());
    }
  
    /**
     * The doctype-system attribute.
     */
    public void setDoctypeSystem  ( String systemId )
    {
      if(m_shouldRecordHasBeenSet)
        m_doctypeSystemHasBeenSet = true;
      super.setDoctype(this.getDoctypePublic(), systemId);
    }
    
    /**
     * The omit-xml-declaration attribute.
     */
    public void setOmitXmlDeclaration( boolean omit )
    {
      if(m_shouldRecordHasBeenSet)
        m_omitXmlDeclarationHasBeenSet = true;
      super.setOmitXMLDeclaration(omit);
    }
    
    /**
     * The cdata-section-elements attribute.
     */
    public void setCdataSectionElements(Vector elements)
    {
      if(m_shouldRecordHasBeenSet)
        m_cdataElementsHasBeenSet = true;
      // TO DO: I have to work something out with Assaf!
      int n = elements.size();
      String elems[] = new String[n];
      for(int i = 0; i < n; i++)
        elems[i] = elements.elementAt(i).toString();
      super.setCDataElements(elems);
    }
    
    /**
     * Sets the method for this output format.
     *
     * @see #getMethod
     * @param method The output method, or null
     */
    public void setMethod( String method )
    {
      if(m_shouldRecordHasBeenSet)
        m_methodHasBeenSet = true;
      super.setMethod(method);;
    }
    
    /**
     * Sets the method for this output format.
     *
     * @see #getMethod
     * @param method The output method, or null
     */
    public void setMethod( QName method )
    {
      if(m_shouldRecordHasBeenSet)
        m_methodHasBeenSet = true;
      // TODO: Work with Assaf on this.
      String meth = method.getLocalPart();
      super.setMethod(meth);;
    }
  
    /**
     * Sets the version for this output method.
     * For XML the value would be "1.0", for HTML
     * it would be "4.0".
     *
     * @see #getVersion
     * @param version The output method version, or null
     */
    public void setVersion( String version )
    {
      if(m_shouldRecordHasBeenSet)
        m_versionHasBeenSet = true;
      super.setVersion(version);;
    }
  
  
    /**
     * Sets the indentation amount. The document will not be
     * indented if the indentation is set to zero.
     * Calling [EMAIL PROTECTED] #setIndenting} will reset this
     * value to zero (off) or the default (on).
     *
     * @param indent The indentation, or zero
     */
    public void setIndent( int indent )
    {
      if(m_shouldRecordHasBeenSet)
        m_indentHasBeenSet = true;
      super.setIndent(indent);
    }
  
    /**
     * Sets the indentation on and off. When set on, the default
     * indentation level and default line wrapping is used
     * (see [EMAIL PROTECTED] #DEFAULT_INDENT} and [EMAIL PROTECTED] 
#DEFAULT_LINE_WIDTH}).
     * To specify a different indentation level or line wrapping,
     * use [EMAIL PROTECTED] #setIndent} and [EMAIL PROTECTED] #setLineWidth}.
     * 
     * <p>This method signature is required by the
     * [EMAIL PROTECTED] 
org.apache.xalan.processor.XSLTAttributeDef#getSetterMethodName() 
     * getSetterMethodName} 
     * method.  See also 
     * the [EMAIL PROTECTED] org.apache.xalan.processor.XSLTSchema 
     * XSLTSchema} class.</p>
     *
     * @param on True if indentation should be on
     */
    public void setIndent( boolean indent )
    {
      super.setIndenting(indent);
    }
  
    /**
     * Sets the indentation on and off. When set on, the default
     * indentation level and default line wrapping is used
     * (see [EMAIL PROTECTED] #DEFAULT_INDENT} and [EMAIL PROTECTED] 
#DEFAULT_LINE_WIDTH}).
     * To specify a different indentation level or line wrapping,
     * use [EMAIL PROTECTED] #setIndent} and [EMAIL PROTECTED] #setLineWidth}.
     *
     * @param on True if indentation should be on
     */
    public void setIndenting( boolean on )
    {
      if(m_shouldRecordHasBeenSet)
        m_indentingHasBeenSet = true;
      super.setIndenting(on);
    }
  
    /**
     * Sets the encoding for this output method. If no
     * encoding was specified, the default is always "UTF-8".
     * Make sure the encoding is compatible with the one
     * used by the [EMAIL PROTECTED] java.io.Writer}.
     *
     * @see #getEncoding
     * @param encoding The encoding, or null
     */
    public void setEncoding( String encoding )
    {
      if(m_shouldRecordHasBeenSet)
        m_encodingHasBeenSet = true;
      super.setEncoding(encoding);
    }
  
  
    /**
     * Sets the media type.
     *
     * @see #getMediaType
     * @param mediaType The specified media type
     */
    public void setMediaType( String mediaType )
    {
      if(m_shouldRecordHasBeenSet)
        m_mediaTypeHasBeenSet = true;
      super.setMediaType(mediaType);
    }
  
    /**
     * Sets XML declaration omitting on and off.
     *
     * @param omit True if XML declaration should be ommited
     */
    public void setOmitXMLDeclaration( boolean omit )
    {
      if(m_shouldRecordHasBeenSet)
        m_omitXmlDeclarationHasBeenSet = true;
      super.setOmitXMLDeclaration(omit);
    }
  
    /**
     * Sets document DTD standalone. The public and system
     * identifiers must be null for the document to be
     * serialized as standalone.
     *
     * @param standalone True if document DTD is standalone
     */
    public void setStandalone( boolean standalone )
    {
      if(m_shouldRecordHasBeenSet)
        m_standaloneHasBeenSet = true;
      super.setStandalone(standalone);
    }
  
    /**
     * Sets the list of elements for which text node children
     * should be output unescaped (no character references).
     *
     * @param nonEscapingElements List of unescaped element tag names
     */
    public void setNonEscapingElements( String[] nonEscapingElements )
    {
      // TODO: Need to work on this.
      if(m_shouldRecordHasBeenSet)
        m_nonEscapingElementsHasBeenSet = true;
      super.setNonEscapingElements(nonEscapingElements);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/Stylesheet.java
  
  Index: Stylesheet.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  package org.apache.xalan.templates;
  
  // Java imports
  import java.io.ObjectInputStream;
  import java.io.IOException;
  import java.io.ObjectOutputStream;
  import java.net.URL;
  import java.text.DecimalFormatSymbols;
  import java.util.Hashtable;
  import java.util.Stack;
  import java.util.Vector;
  
  // Xalan imports
  import org.apache.xalan.utils.SystemIDResolver;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.utils.StringVector;
  
  import org.apache.xalan.xpath.XPath;
  
  // DOM Imports
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  
  // SAX2 Imports
  import org.xml.sax.SAXException;
  import org.xml.sax.Locator;
  
  /**
   * Represents a stylesheet element.
   * <p>All properties in this class have a fixed form of bean-style property 
   * accessors for all properties that represent XSL attributes or elements.  
   * These properties have setter method names accessed generically by the 
   * processor, and so these names must be fixed according to the system 
   * defined in the <a 
href="XSLTAttributeDef#getSetterMethodName">getSetterMethodName</a>
   * function.</p>
   * <p><pre>
   * <!ENTITY % top-level "
   *  (xsl:import*,
   *   (xsl:include
   *   | xsl:strip-space
   *   | xsl:preserve-space
   *   | xsl:output
   *   | xsl:key
   *   | xsl:decimal-format
   *   | xsl:attribute-set
   *   | xsl:variable
   *   | xsl:param
   *   | xsl:template
   *   | xsl:namespace-alias
   *   %non-xsl-top-level;)*)
   * ">
   * 
   * <!ENTITY % top-level-atts '
   *   extension-element-prefixes CDATA #IMPLIED
   *   exclude-result-prefixes CDATA #IMPLIED
   *   id ID #IMPLIED
   *   version NMTOKEN #REQUIRED
   *   xmlns:xsl CDATA #FIXED "http://www.w3.org/1999/XSL/Transform";
   *   %space-att;
   * '>
   * 
   * <!ELEMENT xsl:stylesheet %top-level;>
   * <!ATTLIST xsl:stylesheet %top-level-atts;>
   * 
   * <!ELEMENT xsl:transform %top-level;>
   * <!ATTLIST xsl:transform %top-level-atts;>
   * 
   * </p></pre>
   * @see <a 
href="http://www.w3.org/TR/xslt#section-Stylesheet-Structure";>section-Stylesheet-Structure
 in XSLT Specification</a>
   */
  public class Stylesheet  extends ElemTemplateElement
    implements java.io.Serializable, Document
  {
    /**
     * Constructor for a Stylesheet.
     * @param parent  The including or importing stylesheet.
     */
    public Stylesheet(Stylesheet parent)
    {
      if(null != parent)
      {
        m_stylesheetParent = parent;
        m_stylesheetRoot = parent.getStylesheetRoot();
      }
    }
    
    /**
     * Get the owning stylesheet.  This looks up the 
     * inheritance chain until it calls getStylesheet
     * on a Stylesheet object, which will return itself.
     */
    public Stylesheet getStylesheet()
    {
      return this;
    }
  
    /**
     * Tell if this can be cast to a StylesheetComposed, meaning, you 
     * can ask questions from getXXXComposed functions.
     */
    public boolean isAggregatedType()
    {
      return false;
    }
    
    /**
     * Tell if this is the root of the stylesheet tree.
     */
    public boolean isRoot()
    {
      return false;
    }
    
    /**
     * Extension to be used when serializing to disk.
     */
    public static final String STYLESHEET_EXT = ".lxc";
  
    /**
     * Read the stylesheet from a serialization stream.
     */
    private void readObject(ObjectInputStream stream)
      throws IOException, SAXException
    {
      // System.out.println("Reading Stylesheet");
      try
      {
        stream.defaultReadObject();
      }
      catch(ClassNotFoundException cnfe)
      {
        throw new SAXException(cnfe);
      }
      // System.out.println("Done reading Stylesheet");
    }
  
    private void writeObject(ObjectOutputStream stream)
      throws IOException
    {
      // System.out.println("Writing Stylesheet");
      stream.defaultWriteObject();
      // System.out.println("Done writing Stylesheet");
    }
  
    //============== XSLT Properties =================
    
    /**
     * The "xmlns:xsl" property. 
     */
    private String m_XmlnsXsl;
  
    /**
     * Set the "xmlns:xsl" property. 
     * @see <a href="http://www.w3.org/TR/xslt#xslt-namespace";>xslt-namespace 
in XSLT Specification</a>
     */
    public void setXmlnsXsl (String v)
    {
      m_XmlnsXsl = v;
    }
  
    /**
     * Get the "xmlns:xsl" property. 
     * @see <a href="http://www.w3.org/TR/xslt#xslt-namespace";>xslt-namespace 
in XSLT Specification</a>
     */
    public String getXmlnsXsl()
    {
      return m_XmlnsXsl;
    }
  
    /**
     * The "extension-element-prefixes" property, actually contains URIs. 
     */
    private StringVector m_ExtensionElementURIs;
  
    /**
     * Set the "extension-element-prefixes" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#extension-element";>extension-element in XSLT 
Specification</a>
     */
    public void setExtensionElementPrefixes (StringVector v)
    {
      m_ExtensionElementURIs = v;
    }
  
    /**
     * Get and "extension-element-prefix" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#extension-element";>extension-element in XSLT 
Specification</a>
     */
    public String getExtensionElementPrefix(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_ExtensionElementURIs)
        throw new ArrayIndexOutOfBoundsException();
      return m_ExtensionElementURIs.elementAt(i);
    }
    
    /**
     * Get the number of "extension-element-prefixes" Strings. 
     * @see <a 
href="http://www.w3.org/TR/xslt#extension-element";>extension-element in XSLT 
Specification</a>
     */
    public int getExtensionElementPrefixCount()
    {
      return (null != m_ExtensionElementURIs) 
             ? m_ExtensionElementURIs.size() : 0;
    }
    
    /**
     * Get and "extension-element-prefix" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#extension-element";>extension-element in XSLT 
Specification</a>
     */
    public boolean containsExtensionElementURI(String uri)
    {
      if(null == m_ExtensionElementURIs)
        return false;
      return m_ExtensionElementURIs.contains(uri);
    }
  
    /**
     * The "exclude-result-prefixes" property.
     */
    private StringVector m_ExcludeResultPrefixs;
  
    /**
     * Set the "exclude-result-prefixes" property. 
     * The designation of a namespace as an excluded namespace is 
     * effective within the subtree of the stylesheet rooted at 
     * the element bearing the exclude-result-prefixes or 
     * xsl:exclude-result-prefixes attribute; a subtree rooted 
     * at an xsl:stylesheet element does not include any stylesheets 
     * imported or included by children of that xsl:stylesheet element.
     * @see <a 
href="http://www.w3.org/TR/xslt#literal-result-element";>literal-result-element 
in XSLT Specification</a>
     */
    public void setExcludeResultPrefixes (StringVector v)
    {
      m_ExcludeResultPrefixs = v;
    }
  
    /**
     * Get an "exclude-result-prefix" property. 
     * The designation of a namespace as an excluded namespace is 
     * effective within the subtree of the stylesheet rooted at 
     * the element bearing the exclude-result-prefixes or 
     * xsl:exclude-result-prefixes attribute; a subtree rooted 
     * at an xsl:stylesheet element does not include any stylesheets 
     * imported or included by children of that xsl:stylesheet element.
     * @see <a 
href="http://www.w3.org/TR/xslt#literal-result-element";>literal-result-element 
in XSLT Specification</a>
     */
    public String getExcludeResultPrefix(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_ExcludeResultPrefixs)
        throw new ArrayIndexOutOfBoundsException();
      return m_ExcludeResultPrefixs.elementAt(i);
    }
    
    /**
     * Get the number of "extension-element-prefixes" Strings. 
     * @see <a 
href="http://www.w3.org/TR/xslt#extension-element";>extension-element in XSLT 
Specification</a>
     */
    public int getExcludeResultPrefixCount()
    {
      return (null != m_ExcludeResultPrefixs) 
             ? m_ExcludeResultPrefixs.size() : 0;
    }
  
    /**
     * Get whether or not the passed URL is contained flagged by
     * the "extension-element-prefixes" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#extension-element";>extension-element in XSLT 
Specification</a>
     */
    public boolean containsExcludeResultPrefix(String prefix)
    {
      if(null == m_ExcludeResultPrefixs)
        return false;
      return m_ExcludeResultPrefixs.contains(prefix);
    }
  
    /**
     * The "id" property. 
     */
    private String m_Id;
  
    /**
     * Set the "id" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Embedding-Stylesheets";>section-Embedding-Stylesheets
 in XSLT Specification</a>
     */
    public void setId (String v)
    {
      m_Id = v;
    }
  
    /**
     * Get the "id" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Embedding-Stylesheets";>section-Embedding-Stylesheets
 in XSLT Specification</a>
     */
    public String getId()
    {
      return m_Id;
    }
  
    /**
     * The "version" property. 
     */
    private String m_Version;
  
    /**
     * Set the "version" property. 
     * @see <a href="http://www.w3.org/TR/xslt#forwards";>forwards in XSLT 
Specification</a>
     */
    public void setVersion (String v)
    {
      m_Version = v;
    }
  
    /**
     * Get the "version" property. 
     * @see <a href="http://www.w3.org/TR/xslt#forwards";>forwards in XSLT 
Specification</a>
     */
    public String getVersion()
    {
      return m_Version;
    }
  
    /**
     * The "xml:space" property. 
     */
    private boolean m_XmlSpace;
  
    /**
     * Set the "xml:space" property. 
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public void setXmlSpace (boolean v)
    {
      m_XmlSpace = v;
    }
  
    /**
     * Get the "xml:space" property. 
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public boolean getXmlSpace()
    {
      return m_XmlSpace;
    }
  
    /**
     * The "xsl:import" list. 
     */
    private Vector m_imports;
  
    /**
     * Add a stylesheet to the "import" list. 
     * @see <a href="http://www.w3.org/TR/xslt#import";>import in XSLT 
Specification</a>
     */
    public void setImport (StylesheetComposed v)
    {
      if(null == m_imports)
        m_imports = new Vector();
      
      // I'm going to insert the elements in backwards order,
      // so I can walk them 0 to n.
      m_imports.addElement(v);
    }
  
    /**
     * Get a stylesheet from the "import" list. 
     * @see <a href="http://www.w3.org/TR/xslt#import";>import in XSLT 
Specification</a>
     */
    public StylesheetComposed getImport(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_imports)
        throw new ArrayIndexOutOfBoundsException();
      return (StylesheetComposed)m_imports.elementAt(i);
    }
  
    /**
     * Get the number of imported stylesheets. 
     * @see <a href="http://www.w3.org/TR/xslt#import";>import in XSLT 
Specification</a>
     */
    public int getImportCount()
    {
      return (null != m_imports) ? m_imports.size() : 0;
    }
    
    /**
     * The "xsl:include" properties. 
     */
    private Vector m_includes;
  
    /**
     * Set a "xsl:include" property. 
     * @see <a href="http://www.w3.org/TR/xslt#include";>include in XSLT 
Specification</a>
     */
    public void setInclude (Stylesheet v)
    {
      if(null == m_includes)
        m_includes = new Vector();
      m_includes.addElement(v);
    }
  
    /**
     * Get an "xsl:include" property. 
     * @see <a href="http://www.w3.org/TR/xslt#include";>include in XSLT 
Specification</a>
     */
    public Stylesheet getInclude(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_includes)
        throw new ArrayIndexOutOfBoundsException();
      return (Stylesheet)m_includes.elementAt(i);
    }
  
    /**
     * Get the number of included stylesheets. 
     * @see <a href="http://www.w3.org/TR/xslt#import";>import in XSLT 
Specification</a>
     */
    public int getIncludeCount()
    {
      return (null != m_includes) ? m_includes.size() : 0;
    }
    
    /**
     * Table of tables of element decimal-format.
     * @see ElemDecimalFormat.
     */
    Stack m_DecimalFormatDeclarations;
  
    /**
     * Process the xsl:decimal-format element.
     */
    public void setDecimalFormat(DecimalFormatProperties edf)
    {
      if(null == m_DecimalFormatDeclarations)
        m_DecimalFormatDeclarations = new Stack();
      m_DecimalFormatDeclarations.push(edf);
    }
    
    /**
     * Get an "xsl:decimal-format" property. 
     * @see ElemDecimalFormat.
     * @see <a href="http://www.w3.org/TR/xslt#format-number";>format-number in 
XSLT Specification</a>
     * @return null if not found, otherwise a DecimalFormatProperties
     * object, from which you can get a DecimalFormatSymbols object.
     */
    public DecimalFormatProperties getDecimalFormat(QName name)
    {
      if(null == m_DecimalFormatDeclarations)
        return null;
      
      int n = getDecimalFormatCount();
      for(int i = (n-1); i >= 0; i++)
      {
        DecimalFormatProperties dfp = getDecimalFormat(i);
        if(dfp.getName().equals(name))
          return dfp;
      }
      
      return null;
    }
    
    /**
     * Get an "xsl:decimal-format" property. 
     * @see <a href="http://www.w3.org/TR/xslt#format-number";>format-number in 
XSLT Specification</a>
     * @see ElemDecimalFormat.
     */
    public DecimalFormatProperties getDecimalFormat(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_DecimalFormatDeclarations)
        throw new ArrayIndexOutOfBoundsException();
      return (DecimalFormatProperties)m_DecimalFormatDeclarations.elementAt(i);
    }
  
    /**
     * Get the number of xsl:decimal-format declarations. 
     * @see ElemDecimalFormat.
     */
    public int getDecimalFormatCount()
    {
      return (null != m_DecimalFormatDeclarations) 
             ? m_DecimalFormatDeclarations.size() : 0;
    }
  
  
    /**
     * The "xsl:strip-space" properties,
     * A lookup table of all space stripping elements.
     */
    private Vector m_whitespaceStrippingElements;
  
    /**
     * Set the "xsl:strip-space" properties. 
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public void setStripSpaces(Vector v)
    {
      if(null == m_whitespaceStrippingElements)
      {
        m_whitespaceStrippingElements = v;
      }
      else
      {
        int n = v.size();
        for(int i = 0; i < n; i++)
          m_whitespaceStrippingElements.addElement(v.elementAt(i));
      }
    }
  
    /**
     * Get an "xsl:strip-space" property. 
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public XPath getStripSpace(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_whitespaceStrippingElements)
        throw new ArrayIndexOutOfBoundsException();
      return (XPath)m_whitespaceStrippingElements.elementAt(i);
    }
  
    /**
     * Get the number of "xsl:strip-space" properties. 
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public int getStripSpaceCount()
    {
      return (null != m_whitespaceStrippingElements) 
             ? m_whitespaceStrippingElements.size() : 0;
    }
  
    /**
     * The "xsl:preserve-space" property,
     * A lookup table of all space preserving elements.
     */
    private Vector m_whitespacePreservingElements;
  
    /**
     * Set the "xsl:preserve-space" property. 
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public void setPreserveSpaces (Vector v)
    {
      if(null == m_whitespacePreservingElements)
      {
        m_whitespacePreservingElements = v;
      }
      else
      {
        int n = v.size();
        for(int i = 0; i < n; i++)
          m_whitespacePreservingElements.addElement(v.elementAt(i));
      }
    }
  
    /**
     * Get a "xsl:preserve-space" property. 
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public XPath getPreserveSpace(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_whitespacePreservingElements)
        throw new ArrayIndexOutOfBoundsException();
      return (XPath)m_whitespacePreservingElements.elementAt(i);
    }
  
    /**
     * Get the number of "xsl:preserve-space" properties. 
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public int getPreserveSpaceCount()
    {
      return (null != m_whitespacePreservingElements) 
             ? m_whitespacePreservingElements.size() : 0;
    }
  
    /**
     * The "xsl:output" property. 
     */
    private OutputFormatExtended m_output;
  
    /**
     * Set the "xsl:output" property. 
     * @see <a href="http://www.w3.org/TR/xslt#output";>output in XSLT 
Specification</a>
     */
    public void setOutput (OutputFormatExtended v)
    {
      m_output = v;
    }
  
    /**
     * Get the "xsl:output" property. 
     * @see <a href="http://www.w3.org/TR/xslt#output";>output in XSLT 
Specification</a>
     */
    public OutputFormatExtended getOutput()
    {
      return m_output;
    }
  
    /**
     * The "xsl:key" property. 
     */
    private Vector m_keyDeclarations;
  
    /**
     * Set the "xsl:key" property. 
     * @see <a href="http://www.w3.org/TR/xslt#key";>key in XSLT 
Specification</a>
     */
    public void setKey (KeyDeclaration v)
    {
      if(null == m_keyDeclarations)
        m_keyDeclarations = new Vector();
      m_keyDeclarations.addElement(v);
    }
  
    /**
     * Get an "xsl:key" property. 
     * @see <a href="http://www.w3.org/TR/xslt#key";>key in XSLT 
Specification</a>
     */
    public KeyDeclaration getKey(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_keyDeclarations)
        throw new ArrayIndexOutOfBoundsException();
      return (KeyDeclaration)m_keyDeclarations.elementAt(i);
    }
  
    /**
     * Get the number of "xsl:key" properties. 
     * @see <a href="http://www.w3.org/TR/xslt#key";>key in XSLT 
Specification</a>
     */
    public int getKeyCount()
    {
      return (null != m_keyDeclarations) 
             ? m_keyDeclarations.size() : 0;
    }
  
    /**
     * The "xsl:attribute-set" property. 
     */
    private Vector m_attributeSets;
  
    /**
     * Set the "xsl:attribute-set" property. 
     * @see <a href="http://www.w3.org/TR/xslt#attribute-sets";>attribute-sets 
in XSLT Specification</a>
     */
    public void setAttributeSet (ElemAttributeSet attrSet)
    {
      if(null == m_attributeSets)
      {
        m_attributeSets = new Vector();
      }
      m_attributeSets.addElement(attrSet);  
    }
  
    /**
     * Get an "xsl:attribute-set" property. 
     * @see <a href="http://www.w3.org/TR/xslt#attribute-sets";>attribute-sets 
in XSLT Specification</a>
     */
    public ElemAttributeSet getAttributeSet(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_attributeSets)
        throw new ArrayIndexOutOfBoundsException();
      return (ElemAttributeSet)m_attributeSets.elementAt(i);
    }
  
    /**
     * Get the number of "xsl:attribute-set" properties. 
     * @see <a href="http://www.w3.org/TR/xslt#attribute-sets";>attribute-sets 
in XSLT Specification</a>
     */
    public int getAttributeSetCount()
    {
      return (null != m_attributeSets) 
             ? m_attributeSets.size() : 0;
    }
  
    /**
     * The "xsl:variable" properties. 
     */
    private Vector m_topLevelVariables;
  
    /**
     * Set the "xsl:variable" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public void setVariable (ElemVariable v)
    {
      if(null == m_topLevelVariables)
        m_topLevelVariables = new Vector();
      m_topLevelVariables.addElement(v);
    }
    
    /**
     * Get an "xsl:variable" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public ElemVariable getVariable(QName qname)
    {
      if(null != m_topLevelVariables)
      {
        int n = getVariableCount();
        for(int i = 0; i < n; i++)
        {
          ElemVariable var = (ElemVariable)getVariable(i);
          if(var.getName().equals(qname))
            return var;
        }
      }
      return null;
    }
  
    /**
     * Get an "xsl:variable" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public ElemVariable getVariable(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_topLevelVariables)
        throw new ArrayIndexOutOfBoundsException();
      return (ElemVariable)m_topLevelVariables.elementAt(i);
    }
  
    /**
     * Get the number of "xsl:variable" properties. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public int getVariableCount()
    {
      return (null != m_topLevelVariables) 
             ? m_topLevelVariables.size() : 0;
    }
  
    /**
     * The "xsl:param" properties. 
     */
    private Vector m_topLevelParams;
  
    /**
     * Set an "xsl:param" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public void setParam (ElemParam v)
    {
      if(null == m_topLevelParams)
        m_topLevelParams = new Vector();
      m_topLevelParams.addElement(v);
    }
    
    /**
     * Get an "xsl:param" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public ElemParam getParam(QName qname)
    {
      if(null != m_topLevelParams)
      {
        int n = getParamCount();
        for(int i = 0; i < n; i++)
        {
          ElemParam var = getParam(i);
          if(var.getName().equals(qname))
            return var;
        }
      }
      return null;
    }
  
    /**
     * Get an "xsl:param" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public ElemParam getParam(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_topLevelParams)
        throw new ArrayIndexOutOfBoundsException();
      return (ElemParam)m_topLevelParams.elementAt(i);
    }
  
    /**
     * Get the number of "xsl:param" properties. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public int getParamCount()
    {
      return (null != m_topLevelParams) 
             ? m_topLevelParams.size() : 0;
    }
  
    /**
     * The "xsl:template" properties. 
     */
    private Vector m_templates;
    
    /**
     * Set an "xsl:template" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Defining-Template-Rules";>section-Defining-Template-Rules
 in XSLT Specification</a>
     */
    public void setTemplate (ElemTemplate v)
    {
      if(null == m_templates)
        m_templates = new Vector();
      m_templates.addElement(v);
      v.setStylesheet(this);
    }
  
    /**
     * Get an "xsl:template" property.
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Defining-Template-Rules";>section-Defining-Template-Rules
 in XSLT Specification</a>
     */
    public ElemTemplate getTemplate(int i)
      throws SAXException
    {
      if(null == m_templates)
        throw new ArrayIndexOutOfBoundsException();
      return (ElemTemplate)m_templates.elementAt(i);
    }
  
    /**
     * Get the number of "xsl:template" properties.
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Defining-Template-Rules";>section-Defining-Template-Rules
 in XSLT Specification</a>
     */
    public int getTemplateCount()
    {
      return (null != m_templates) 
             ? m_templates.size() : 0;
    }
  
    /**
     * The "xsl:namespace-alias" properties. 
     */
    private Vector m_prefix_aliases;
    
    /**
     * Set the "xsl:namespace-alias" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#literal-result-element";>literal-result-element 
in XSLT Specification</a>
     */
    public void setNamespaceAlias (NamespaceAlias na)
    {
      m_prefix_aliases.addElement(na);
    }
      
    /**
     * Get an "xsl:variable" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public NamespaceAlias getNamespaceAlias(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_prefix_aliases)
        throw new ArrayIndexOutOfBoundsException();
      return (NamespaceAlias)m_prefix_aliases.elementAt(i);
    }
  
    /**
     * Get the number of "xsl:variable" properties. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public int getNamespaceAliasCount()
    {
      return (null != m_prefix_aliases) 
             ? m_prefix_aliases.size() : 0;
    }
  
  
    /**
     * The "non-xsl-top-level" properties. 
     */
    private Hashtable m_NonXslTopLevel;
  
    /**
     * Set a found non-xslt element. 
     * @see <a 
href="http://www.w3.org/TR/xslt#stylesheet-element";>stylesheet-element in XSLT 
Specification</a>
     */
    public void setNonXslTopLevel (QName name, Object obj)
    {
      if(null == m_NonXslTopLevel)
        m_NonXslTopLevel = new Hashtable();
      
      m_NonXslTopLevel.put(name, obj);
    }
  
    /**
     * Get a non-xslt element. 
     * @see <a 
href="http://www.w3.org/TR/xslt#stylesheet-element";>stylesheet-element in XSLT 
Specification</a>
     */
    public Object getNonXslTopLevel(QName name)
    {
      return (null != m_NonXslTopLevel) ? m_NonXslTopLevel.get(name) : null;
    }
  
    // =========== End top-level XSLT properties ===========
    
    /**
     * The base URL of the XSL document.
     * @serial
     */
    private URL m_href = null;
    private String m_publicId;
    private String m_systemId;
  
    /**
     * Get the base identifier with which this stylesheet is associated.
     */
    public URL getHref()
    {
      return m_href;
    }
  
    /**
     * Get the base identifier with which this stylesheet is associated.
     */
    public void setHref(URL baseIdent)
    {
      m_href = baseIdent;
    }
    
    /**
     * Set the location information for this element.
     */
    public void setLocaterInfo(Locator locator)
    {
      m_publicId = locator.getPublicId();
      m_systemId = locator.getSystemId();
      
      if(null != m_systemId)
      {
        try
        {
          m_href = SystemIDResolver.getURLFromString(m_systemId, null);
        }
        catch(SAXException se)
        {
          // Ignore this for right now
        }
      }
      
      super.setLocaterInfo(locator);
    }
  
  
    /**
     * The root of the stylesheet, where all the tables common
     * to all stylesheets are kept.
     * @serial
     */
    private StylesheetRoot m_stylesheetRoot;
  
    /**
     * Get the root of the stylesheet, where all the tables common
     * to all stylesheets are kept.
     */
    public StylesheetRoot getStylesheetRoot()
    {
      return m_stylesheetRoot;
    }
  
    /**
     * Set the root of the stylesheet, where all the tables common
     * to all stylesheets are kept.
     */
    public void setStylesheetRoot(StylesheetRoot v)
    {
      m_stylesheetRoot = v;
    }
  
    /**
     * The parent of the stylesheet.  This will be null if this
     * is the root stylesheet.
     * @serial
     */
    private Stylesheet m_stylesheetParent;
  
    /**
     * Get the parent of the stylesheet.  This will be null if this
     * is the root stylesheet.
     */
    public Stylesheet getStylesheetParent()
    {
      return m_stylesheetParent;
    }
  
    /**
     * Set the parent of the stylesheet.  This should be null if this
     * is the root stylesheet.
     */
    public void setStylesheetParent(Stylesheet v)
    {
      m_stylesheetParent = v;
    }
  
    /**
     * Get the owning aggregated stylesheet, or this 
     * stylesheet if it is aggregated.
     */
    public StylesheetComposed getStylesheetComposed()
    {
      Stylesheet sheet = this;
      while(!sheet.isAggregatedType())
      {
        sheet = sheet.getStylesheetParent();
      }
      return (StylesheetComposed)sheet;
    }
  
    /**
     * Get the type of the node.  We'll pretend we're a Document.
     */
    public short              getNodeType()
    {
      return Node.DOCUMENT_NODE;
    }
    
    /** 
     * Get an integer representation of the element type.
     * 
     * @return An integer representation of the element, defined in the 
     *     Constants class.
     * @see org.apache.xalan.templates.Constants
     */
    public int getXSLToken()
    {
      return Constants.ELEMNAME_STYLESHEET;
    }
    
    /** 
     * Return the node name.
     */
    public String getNodeName()
    {
      return Constants.ELEMNAME_STYLESHEET_STRING;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/StylesheetComposed.java
  
  Index: StylesheetComposed.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import java.util.Vector;
  import java.util.Hashtable;
  import java.util.Enumeration;
  import trax.ProcessorException;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.utils.QName;
  import org.apache.xml.serialize.OutputFormat;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  import org.w3c.dom.Element;
  import org.xml.sax.SAXException;
  import java.text.DecimalFormat;
  import java.text.DecimalFormatSymbols;
  
  /**
   * Represents a stylesheet that has methods that resolve includes and 
   * imports.  It has methods on it that 
   * return "composed" properties, which mean that:
   * <ol>
   * <li>Properties that are aggregates, like OutputFormat, will 
   * be composed of properties declared in this stylsheet and all 
   * included stylesheets.</li>
   * <li>Properties that aren't found, will be searched for first in 
   * the includes, and, if none are located, will be searched for in 
   * the imports.</li>
   * <li>Properties in that are not atomic on a stylesheet will 
   * have the form getXXXComposed. Some properties, like version and id, 
   * are not inherited, and so won't have getXXXComposed methods.</li>
   * </ol> 
   * <p>In some cases getXXXComposed methods may calculate the composed 
   * values dynamically, while in other cases they may store the composed 
   * values.</p>
   */
  public class StylesheetComposed extends Stylesheet
  {
    /**
     * Uses an XSL stylesheet document.
     * @param parent  The including or importing stylesheet.
     */
    public StylesheetComposed(Stylesheet parent)
    {
      super(parent);
    }
    
    /**
     * Tell if this can be cast to a StylesheetComposed, meaning, you 
     * can ask questions from getXXXComposed functions.
     */
    public boolean isAggregatedType()
    {
      return true;
    }
    
    private transient int m_importNumber = -1;
    
    /**
     * Recalculate the number of this stylesheet in the global 
     * import list.
     * <p>For example, suppose</p>
     * <p>stylesheet A imports stylesheets B and C in that order;</p>
     * <p>stylesheet B imports stylesheet D;</p>
     * <p>stylesheet C imports stylesheet E.</p>
     * <p>Then the order of import precedence (lowest first) is D, B, E, C, 
A.</p>
     * <p>If this were stylesheet C, then the importsComposed list 
     * would be E, B, D (highest first).</p>
     */
    void recomposeImports()
    {
      m_importNumber = getStylesheetRoot().getImportNumber(this);
    }
  
    /**
     * Get a stylesheet from the "import" list. 
     * @see <a href="http://www.w3.org/TR/xslt#import";>import in XSLT 
Specification</a>
     */
    public StylesheetComposed getImportComposed(int i)
      throws ArrayIndexOutOfBoundsException
    {
      StylesheetRoot root = getStylesheetRoot();
      // Get the stylesheet that is offset past this stylesheet.
      // Thus, if the index of this stylesheet is 3, an argument 
      // to getImportComposed of 0 will return the 4th stylesheet 
      // in the global import list.
      return root.getGlobalImport(1+m_importNumber+i);
    }
  
    /**
     * Get the number of imported stylesheets. 
     * @see <a href="http://www.w3.org/TR/xslt#import";>import in XSLT 
Specification</a>
     */
    public int getImportCountComposed()
    {
      StylesheetRoot root = getStylesheetRoot();
      int globalImportCount = root.getGlobalImportCount();
      return (globalImportCount-m_importNumber)-1;
    }
    
    /**
     * The combined list of includes.
     */
    private transient Vector m_includesComposed;
    
    /**
     * Recompose the value of the composed include list.
     */
    void recomposeIncludes(Stylesheet including)
    {
      int n = including.getIncludeCount();
      if(n > 0)
      {
        if(null == m_includesComposed)
          m_includesComposed = new Vector();
        for(int i = 0; i < n; i++)
        {
          Stylesheet included = including.getInclude(i);
          m_includesComposed.addElement(included);
          recomposeIncludes(included);
        }
      }
    }
      
    /**
     * Get an "xsl:include" property. 
     * @see <a href="http://www.w3.org/TR/xslt#include";>include in XSLT 
Specification</a>
     */
    public Stylesheet getIncludeComposed(int i)
      throws ArrayIndexOutOfBoundsException
    {
      if(null == m_includesComposed)
        throw new ArrayIndexOutOfBoundsException();
      return (Stylesheet)m_includesComposed.elementAt(i);
    }
  
    /**
     * Get the number of included stylesheets. 
     * @see <a href="http://www.w3.org/TR/xslt#import";>import in XSLT 
Specification</a>
     */
    public int getIncludeCountComposed()
    {
      return (null != m_includesComposed) ? m_includesComposed.size() : 0;
    }
    
    /**
     * Table of DecimalFormatSymbols, keyed by QName.
     */
    private transient Hashtable m_decimalFormatSymbols;
    
    /**
     * Given a valid element decimal-format name, return the 
     * decimalFormatSymbols with that name.
     * <p>It is an error to declare either the default decimal-format or 
     * a decimal-format with a given name more than once (even with 
     * different import precedence), unless it is declared every 
     * time with the same value for all attributes (taking into 
     * account any default values).</p>
     * <p>Which means, as far as I can tell, the decimal-format 
     * properties are not additive.</p>
     * @return null if name is not found.
     */
    void recomposeDecimalFormats()
    {
      m_decimalFormatSymbols = new Hashtable();
      
      // Loop for this stylesheet and all stylesheets included or of lower 
      // import precidence.
      int nImports = getImportCountComposed();
      for(int i = -1; i < nImports; i++)
      {
        StylesheetComposed stylesheet = (i == i) ? this : getImportComposed(i);
        // Does this stylesheet contain it?
        int nDFPs = stylesheet.getDecimalFormatCount();
        for(int dfpIndex = 0; dfpIndex < nDFPs; dfpIndex++)
        {
          DecimalFormatProperties dfp = stylesheet.getDecimalFormat(dfpIndex);
          m_decimalFormatSymbols.put(dfp.getName(), 
dfp.getDecimalFormatSymbols());
        }
        
        // Do the included stylesheets contain it?
        int nIncludes = stylesheet.getIncludeCountComposed();
        for(int k = 0; k < nIncludes; k++)
        {
          Stylesheet included = stylesheet.getIncludeComposed(k);
          nDFPs = included.getDecimalFormatCount();
          for(int dfpIndex = 0; dfpIndex < nDFPs; dfpIndex++)
          {
            DecimalFormatProperties dfp = included.getDecimalFormat(dfpIndex);
            m_decimalFormatSymbols.put(dfp.getName(), 
dfp.getDecimalFormatSymbols());
          }
        }
      }
    }
  
    /**
     * Given a valid element decimal-format name, return the 
     * decimalFormatSymbols with that name.
     * <p>It is an error to declare either the default decimal-format or 
     * a decimal-format with a given name more than once (even with 
     * different import precedence), unless it is declared every 
     * time with the same value for all attributes (taking into 
     * account any default values).</p>
     * <p>Which means, as far as I can tell, the decimal-format 
     * properties are not additive.</p>
     * @return null if name is not found.
     */
    public DecimalFormatSymbols getDecimalFormatComposed(QName name)
    {
      return (DecimalFormatSymbols)m_decimalFormatSymbols.get(name);
    }
    
    /**
     * A list of properties that specify how to do space 
     * stripping. This uses the same exact mechanism as Templates.
     */
    private transient TemplateList m_whiteSpaceInfoList;
    
    /**
     * Compile a lookup table for WhiteSpaceInfo elements, which are built
     * from xsl:strip-space and xsl:preserve space information.
     * @return null if node is not matched.
     */
    void recomposeWhiteSpaceInfo()
      throws SAXException
    {
      m_whiteSpaceInfoList = new TemplateList(this);
      
      int nIncludes = getIncludeCountComposed();
      for(int k = -1; k < nIncludes; k++)
      {
        Stylesheet included = (-1 == k) ? this : getIncludeComposed(k);
        
        int n = included.getStripSpaceCount();
        for(int i = 0; i < n; i++)
        {
          XPath match = included.getStripSpace(i);
          m_whiteSpaceInfoList.setTemplate(new WhiteSpaceInfo(match, true));
        }
        n = included.getPreserveSpaceCount();
        for(int i = 0; i < n; i++)
        {
          XPath match = included.getPreserveSpace(i);
          m_whiteSpaceInfoList.setTemplate(new WhiteSpaceInfo(match, false));
        }
      }
    }
    
    /**
     * Get information about whether or not an element should strip whitespace.
     * @see <a href="http://www.w3.org/TR/xslt#strip";>strip in XSLT 
Specification</a>
     */
    public WhiteSpaceInfo getWhiteSpaceInfo(XPathContext support,
                                            Element targetElement)
      throws SAXException
    {
      return (WhiteSpaceInfo)m_whiteSpaceInfoList.getTemplate(support,
                                                              targetElement, 
null,
                                                              false);
    }
    
    /**
     * A list of all key declarations visible from this stylesheet and all 
     * lesser stylesheets.
     */
    private transient Vector m_keyDecls;
    
    /**
     * Recompose the key decls from this stylesheet and 
     * all stylesheets within lesser import precedence.
     */
    void recomposeKeys()
    {
      m_keyDecls = new Vector();
      
      // Loop for this stylesheet and all stylesheets included or of lower 
      // import precidence.
      int nImports = getImportCountComposed();
      for(int i = -1; i < nImports; i++)
      {
        StylesheetComposed stylesheet = (i == i) ? this : getImportComposed(i);
        // Does this stylesheet contain it?
        int nKeys = stylesheet.getKeyCount();
        for(int keyIndex = 0; keyIndex < nKeys; keyIndex++)
        {
          KeyDeclaration keyDecl = stylesheet.getKey(keyIndex);
          m_keyDecls.addElement(keyDecl);
        }
        
        // Do the included stylesheets contain it?
        int nIncludes = stylesheet.getIncludeCountComposed();
        for(int k = 0; k < nIncludes; k++)
        {
          Stylesheet included = stylesheet.getIncludeComposed(k);
          nKeys = included.getDecimalFormatCount();
          for(int keyIndex = 0; keyIndex < nKeys; keyIndex++)
          {
            KeyDeclaration keyDecl = included.getKey(keyIndex);
            m_keyDecls.addElement(keyDecl);
          }
        }
      }
    }
    
    /**
     * Get the composed "xsl:key" properties. 
     * @see <a href="http://www.w3.org/TR/xslt#key";>key in XSLT 
Specification</a>
     */
    public Vector getKeysComposed()
    {
      return m_keyDecls;
    }
    
    /**
     * Composed set of all included and imported attribute set properties.
     * Each entry is a vector of ElemAttributeSet objects.
     * <p>Note: Should this go on the StylesheetRoot class instead?</p>
     */
    private transient Hashtable m_attrSets;
  
    /**
     * Recompose the attribute-set decls from this stylesheet and 
     * all stylesheets within import precedence.
     */
    void recomposeAttributeSets()
    {
      m_attrSets = new Hashtable();
      
      // Loop for this stylesheet and all stylesheets included or of lower 
      // import precidence.
      int nImports = getImportCountComposed();
      for(int i = -1; i < nImports; i++)
      {
        StylesheetComposed stylesheet = (i == i) ? this : getImportComposed(i);
        // Does this stylesheet contain it?
        int nAS = stylesheet.getAttributeSetCount();
        for(int asIndex = 0; asIndex < nAS; asIndex++)
        {
          ElemAttributeSet attrSet = stylesheet.getAttributeSet(asIndex);
          Vector attrSetList = (Vector)m_attrSets.get(attrSet.getName());
          if(null == attrSetList)
          {
            attrSetList = new Vector();
            m_attrSets.put(attrSet.getName(), attrSetList);
          }
          attrSetList.addElement(attrSet);
        }
        
        // Do the included stylesheets contain it?
        int nIncludes = stylesheet.getIncludeCountComposed();
        for(int k = 0; k < nIncludes; k++)
        {
          Stylesheet included = stylesheet.getIncludeComposed(k);
          nAS = included.getAttributeSetCount();
          for(int asIndex = 0; asIndex < nAS; asIndex++)
          {
            ElemAttributeSet attrSet = included.getAttributeSet(asIndex);
            Vector attrSetList = (Vector)m_attrSets.get(attrSet.getName());
            if(null == attrSetList)
            {
              attrSetList = new Vector();
              m_attrSets.put(attrSet.getName(), attrSetList);
            }
            attrSetList.addElement(attrSet);
          }
        }
      }
    }
      
    /**
     * Get a list "xsl:attribute-set" properties that match the qname. 
     * @see <a href="http://www.w3.org/TR/xslt#attribute-sets";>attribute-sets 
in XSLT Specification</a>
     */
    public Vector getAttributeSetComposed(QName name)
      throws ArrayIndexOutOfBoundsException
    {
      return (Vector)m_attrSets.get(name);
    }
  
    /**
     * Composed set of all params.
     * <p>Note: Should this go on the StylesheetRoot class instead?</p>
     */
    private transient Hashtable m_variables;
  
    /**
     * Recompose the attribute-set decls from this stylesheet and 
     * all stylesheets within import precedence.
     */
    void recomposeVariables()
    {
      m_variables = new Hashtable();
      
      // Loop for this stylesheet and all stylesheets included or of lower 
      // import precidence.
      int nImports = getImportCountComposed();
      for(int i = -1; i < nImports; i++)
      {
        StylesheetComposed stylesheet = (i == i) ? this : getImportComposed(i);
        // Does this stylesheet contain it?
        int nVariables = stylesheet.getVariableCount();
        for(int vIndex = 0; vIndex < nVariables; vIndex++)
        {
          ElemVariable elemVar = stylesheet.getVariable(vIndex);
          m_variables.put(elemVar.getName(), elemVar);
        }
        
        // Do the included stylesheets contain it?
        int nIncludes = stylesheet.getIncludeCountComposed();
        for(int k = 0; k < nIncludes; k++)
        {
          Stylesheet included = stylesheet.getIncludeComposed(k);
          nVariables = included.getVariableCount();
          for(int vIndex = 0; vIndex < nVariables; vIndex++)
          {
            ElemVariable elemVar = included.getVariable(vIndex);
            m_variables.put(elemVar.getName(), elemVar);
          }
        }
      }
    }
  
    /**
     * Get an "xsl:variable" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public ElemVariable getVariableComposed(QName qname)
    {
      return (ElemVariable)m_variables.get(qname);
    }
    
    /**
     * Get all global "xsl:variable" properties in scope for this stylesheet. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public Enumeration getVariablesComposed()
    {
      return m_variables.elements();
    }
    
    /**
     * Composed set of all params.
     */
    private transient Hashtable m_params;
  
    /**
     * Recompose the attribute-set decls from this stylesheet and 
     * all stylesheets within import precedence.
     */
    void recomposeParams()
    {
      m_params = new Hashtable();
      
      // Loop for this stylesheet and all stylesheets included or of lower 
      // import precidence.
      int nImports = getImportCountComposed();
      for(int i = -1; i < nImports; i++)
      {
        StylesheetComposed stylesheet = (i == i) ? this : getImportComposed(i);
        // Does this stylesheet contain it?
        int nVariables = stylesheet.getParamCount();
        for(int vIndex = 0; vIndex < nVariables; vIndex++)
        {
          ElemParam elemVar = stylesheet.getParam(vIndex);
          m_params.put(elemVar.getName(), elemVar);
        }
        
        // Do the included stylesheets contain it?
        int nIncludes = stylesheet.getIncludeCountComposed();
        for(int k = 0; k < nIncludes; k++)
        {
          Stylesheet included = stylesheet.getIncludeComposed(k);
          nVariables = included.getParamCount();
          for(int vIndex = 0; vIndex < nVariables; vIndex++)
          {
            ElemParam elemVar = included.getParam(vIndex);
            m_params.put(elemVar.getName(), elemVar);
          }
        }
      }
    }
  
    /**
     * Get an "xsl:param" property. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public ElemParam getParamComposed(QName qname)
    {
      return (ElemParam)m_params.get(qname);
    }
    
    /**
     * Get all global "xsl:variable" properties in scope for this stylesheet. 
     * @see <a 
href="http://www.w3.org/TR/xslt#top-level-variables";>top-level-variables in 
XSLT Specification</a>
     */
    public Enumeration getParamsComposed()
    {
      return m_params.elements();
    }
    
    /**
     * The "xsl:template" properties. 
     */
    private transient TemplateList m_templateList = new TemplateList(this);
    
    /**
     * Aggregate the list of templates and included templates into a single 
list. 
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Defining-Template-Rules";>section-Defining-Template-Rules
 in XSLT Specification</a>
     */
    public void recomposeTemplates()
      throws SAXException
    {
      int nIncludes = getIncludeCountComposed();
      for(int k = -1; k < nIncludes; k++)
      {
        Stylesheet included = (-1 == k) ? this : getIncludeComposed(k);
        
        int n = included.getTemplateCount();
        for(int i = 0; i < n; i++)
        {
          m_templateList.setTemplate(included.getTemplate(i));
        }
      }
    }
  
    /**
     * Get an "xsl:template" property by node match. This looks in the imports 
as 
     * well as this stylesheet.
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Defining-Template-Rules";>section-Defining-Template-Rules
 in XSLT Specification</a>
     */
    public ElemTemplate getTemplateComposed(XPathContext support,
                                     Node targetNode,
                                     QName mode, 
                                     boolean quietConflictWarnings)
      throws SAXException
    {
      return m_templateList.getTemplate(support,
                                        targetNode,
                                        mode,
                                        quietConflictWarnings);
    }
  
    /**
     * Get an "xsl:template" property. This looks in the imports as 
     * well as this stylesheet.
     * @see <a 
href="http://www.w3.org/TR/xslt#section-Defining-Template-Rules";>section-Defining-Template-Rules
 in XSLT Specification</a>
     */
    public ElemTemplate getTemplateComposed(QName qname)
    {
      return m_templateList.getTemplate(qname);
    }
  
    /**
     * Composed set of all params.
     * <p>Note: Should this go on the StylesheetRoot class instead?</p>
     */
    private transient Hashtable m_namespaceAliasComposed;
  
    /**
     * Recompose the attribute-set decls from this stylesheet and 
     * all stylesheets within import precedence.
     */
    void recomposeNamespaceAliases()
    {
      m_namespaceAliasComposed = new Hashtable();
      
      // Loop for this stylesheet and all stylesheets included or of lower 
      // import precidence.
      int nImports = getImportCountComposed();
      for(int i = -1; i < nImports; i++)
      {
        StylesheetComposed stylesheet = (i == i) ? this : getImportComposed(i);
        // Does this stylesheet contain it?
        int nNSA = stylesheet.getNamespaceAliasCount();
        for(int nsaIndex = 0; nsaIndex < nNSA; nsaIndex++)
        {
          NamespaceAlias nsAlias = stylesheet.getNamespaceAlias(nsaIndex);
          m_namespaceAliasComposed.put(nsAlias.getStylesheetPrefix(), 
                       nsAlias.getResultPrefix());
        }
        
        // Do the included stylesheets contain it?
        int nIncludes = stylesheet.getIncludeCountComposed();
        for(int k = 0; k < nIncludes; k++)
        {
          Stylesheet included = stylesheet.getIncludeComposed(k);
          nNSA = included.getParamCount();
          for(int nsaIndex = 0; nsaIndex < nNSA; nsaIndex++)
          {
            NamespaceAlias nsAlias = included.getNamespaceAlias(nsaIndex);
            m_namespaceAliasComposed.put(nsAlias.getStylesheetPrefix(), 
                         nsAlias.getResultPrefix());
          }
        }
      }
    }
  
    /**
     * Get the "xsl:namespace-alias" property. 
     * Return the alias namespace uri for a given namespace uri if one is found.
     * @see <a 
href="http://www.w3.org/TR/xslt#literal-result-element";>literal-result-element 
in XSLT Specification</a>
     */
    public String getNamespaceAliasComposed(String uri)
    {
      return (String)m_namespaceAliasComposed.get(uri);
    }
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/StylesheetRoot.java
  
  Index: StylesheetRoot.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.w3c.dom.*;
  import java.util.*;
  import java.net.URL;
  import java.net.MalformedURLException;
  import java.io.*;
  import org.xml.sax.*;
  import org.xml.sax.helpers.*;
  
  import org.apache.xml.serialize.*;
  
  import org.apache.xalan.utils.*;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.trace.*;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.transformer.TransformerImpl;
  import trax.Transformer;
  import trax.ProcessorException;
  import trax.Templates;
  
  /**
   * <meta name="usage" content="general"/>
   * This class represents the root object of the stylesheet tree.
   */
  public class StylesheetRoot 
    extends StylesheetComposed 
    implements java.io.Serializable, Templates
  {
    /**
     * Uses an XSL stylesheet document.
     * @param transformer  The XSLTProcessor implementation.
     * @param baseIdentifier The file name or URL for the XSL stylesheet.
     * @exception ProcessorException if the baseIdentifier can not be resolved 
to a URL.
     */
    public StylesheetRoot()
      throws ProcessorException
    {
      super(null);
      setStylesheetRoot(this);
      try
      {
        initDefaultRule();
      }
      catch(SAXException se)
      {
        throw new ProcessorException("Can't init default templates!", se);
      }
    }
    
    /**
     * Tell if this is the root of the stylesheet tree.
     */
    public boolean isRoot()
    {
      return true;
    }
    
    
    //============== Templates Interface ================
    
    /**
     * Create a new transformation context for this Templates object.
     */
    public Transformer newTransformer()
    {
      return new TransformerImpl(this);
    }
        
    /**
     * Get the properties for xsl:output.  The object returned will 
     * be a clone of the internal values, and thus it can be mutated 
     * without mutating the Templates object, and then handed in to 
     * the process method.
     * <p>A stylesheet may contain multiple xsl:output elements and may 
     * include or import stylesheets that also contain xsl:output elements. 
     * All the xsl:output elements occurring in a stylesheet are merged 
     * into a single effective xsl:output element. For the 
     * cdata-section-elements attribute, the effective value is the 
     * union of the specified values. For other attributes, the effective 
     * value is the specified value with the highest import precedence. 
     * It is an error if there is more than one such value for an attribute. 
     * An XSLT processor may signal the error; if it does not signal the 
     * error, if should recover by using the value that occurs last in 
     * the stylesheet. The values of attributes are defaulted after 
     * the xsl:output elements have been merged; different output 
     * methods may have different default values for an attribute.</p>
     * @see <a href="http://www.w3.org/TR/xslt#output";>output in XSLT 
Specification</a>
     * @return A OutputProperties object that may be mutated.
     * 
     * @see org.xml.serialize.OutputFormat
     */
    public OutputFormat getOutputFormat()
    {
      OutputFormat cloned = new OutputFormat();
      cloned.setPreserveSpace(true);
      cloned.setCDataElements(m_outputFormatComposed.getCDataElements());
      cloned.setDoctype(m_outputFormatComposed.getDoctypePublic(), 
m_outputFormatComposed.getDoctypeSystem());
      cloned.setEncoding(m_outputFormatComposed.getEncoding());
      cloned.setIndent(m_outputFormatComposed.getIndent());
      cloned.setIndenting(m_outputFormatComposed.getIndenting());
      cloned.setLineSeparator(m_outputFormatComposed.getLineSeparator());
      cloned.setLineWidth(m_outputFormatComposed.getLineWidth());
      cloned.setMediaType(m_outputFormatComposed.getMediaType());
      cloned.setMethod(m_outputFormatComposed.getMethod());
      
cloned.setNonEscapingElements(m_outputFormatComposed.getNonEscapingElements());
      
cloned.setOmitXMLDeclaration(m_outputFormatComposed.getOmitXMLDeclaration());
      cloned.setPreserveSpace(m_outputFormatComposed.getPreserveSpace());
      cloned.setStandalone(m_outputFormatComposed.getStandalone());
      cloned.setVersion(m_outputFormatComposed.getVersion());
      return cloned;
    }
  
    //============== End Templates Interface ================
    
    /**
     * Recompose the values of all "composed" properties, meaning 
     * properties that need to be combined or calculated from 
     * the combination of imported and included stylesheets.
     */
    public void recompose()
      throws SAXException
    {
      recomposeImports();
      recomposeOutput();
      
      int n = getGlobalImportCount();
      for(int i = 0; i < n; i++)
      {
        StylesheetComposed sheet = getGlobalImport(i);
        if(sheet != this) // already done
          sheet.recomposeImports();
        sheet.recomposeIncludes(sheet);
        sheet.recomposeAttributeSets();
        sheet.recomposeDecimalFormats();
        sheet.recomposeKeys();
        sheet.recomposeNamespaceAliases();
        sheet.recomposeParams();
        sheet.recomposeTemplates();
        sheet.recomposeVariables();
        sheet.recomposeWhiteSpaceInfo();
      }
    }
    
    /**
     * This will be set up with the default values, and then the values 
     * will be set as stylesheets are encountered.
     */
    private OutputFormat m_outputFormatComposed;
  
    /**
     * Get the combined "xsl:output" property with the properties 
     * combined from the included stylesheets.  If a xsl:output 
     * is not declared in this stylesheet or an included stylesheet, 
     * look in the imports. 
     * Please note that this returns a reference to the OutputFormat
     * object, not a cloned object, like getOutputFormat does.
     * @see <a href="http://www.w3.org/TR/xslt#output";>output in XSLT 
Specification</a>
     */
    public OutputFormat getOutputComposed()
    {
      return m_outputFormatComposed;
    }
    
    /**
     * Recompose the output format object from the included elements.
     */
    public void recomposeOutput()
    {
      m_outputFormatComposed = new OutputFormat();
      m_outputFormatComposed.setPreserveSpace(true);
      recomposeOutput(this);
    }
    
    
    /**
     * Recompose the output format object from the included elements.
     */
    private void recomposeOutput(Stylesheet stylesheet)
    {
      // Get the direct imports of this sheet.
      int n = stylesheet.getImportCount();
      if(n > 0)
      {
        for(int i = 0; i < n; i++)
        {
          Stylesheet imported = stylesheet.getImport(i);
          recomposeOutput(imported);
        }
      }
      
      n = stylesheet.getIncludeCount();
      if(n > 0)
      {
        for(int i = 0; i < n; i++)
        {
          Stylesheet included = stylesheet.getInclude(i);
          recomposeOutput(included);
        }
      }
      
      OutputFormatExtended of = getOutput();
      if(null != of)
      {
        if(of.cdataElementsHasBeenSet())
          m_outputFormatComposed.setCDataElements(of.getCDataElements());
        if(of.doctypePublicHasBeenSet())
          m_outputFormatComposed.setDoctype(of.getDoctypePublic(), 
                                            
m_outputFormatComposed.getDoctypeSystem());
        if(of.doctypeSystemHasBeenSet())
          
m_outputFormatComposed.setDoctype(m_outputFormatComposed.getDoctypePublic(), 
                                            of.getDoctypeSystem());
        if(of.encodingHasBeenSet())
          m_outputFormatComposed.setEncoding(of.getEncoding());
        if(of.indentHasBeenSet())
          m_outputFormatComposed.setIndent(of.getIndent());
        if(of.indentingHasBeenSet())
          m_outputFormatComposed.setIndenting(of.getIndenting());
        if(of.mediaTypeHasBeenSet())
          m_outputFormatComposed.setMediaType(of.getMediaType());
        if(of.methodHasBeenSet())
          m_outputFormatComposed.setMethod(of.getMethod());
        if(of.nonEscapingElementsHasBeenSet())
          
m_outputFormatComposed.setNonEscapingElements(of.getNonEscapingElements());
        if(of.omitXmlDeclarationHasBeenSet())
          
m_outputFormatComposed.setOmitXMLDeclaration(of.getOmitXMLDeclaration());
        if(of.standaloneHasBeenSet())
          m_outputFormatComposed.setStandalone(of.getStandalone());
        if(of.versionHasBeenSet())
          m_outputFormatComposed.setVersion(of.getVersion());
      }
    }
  
    
    private boolean m_outputMethodSet = false;
  
    /**
     * <meta name="usage" content="internal"/>
     * Find out if an output method has been set by the user.
     */
    public boolean isOutputMethodSet()
    {
      return m_outputMethodSet;
    }
    
    /**
     * The combined list of imports.
     */
    private transient Vector m_globalImportList;
    
    /**
     * Add the imports in the given sheet to the m_globalImportList
     * list.  The will be added from highest import precedence to 
     * least import precidence.
     */
    protected void addImports(Stylesheet stylesheet)
    {
      // Get the direct imports of this sheet.
      int n = stylesheet.getImportCount();
      if(n > 0)
      {
        for(int i = 0; i < n; i++)
        {
          Stylesheet imported = stylesheet.getImport(i);
          m_globalImportList.insertElementAt(imported, 0);
          addImports(imported);
        }
      }
      
      n = stylesheet.getIncludeCount();
      if(n > 0)
      {
        for(int i = 0; i < n; i++)
        {
          Stylesheet included = stylesheet.getInclude(i);
          addImports(included);
        }
      }
    }
    
    /**
     * Recompose the value of the composed import list. This 
     * means any stylesheets of lesser import precidence.
     * <p>For example, suppose</p>
     * <p>stylesheet A imports stylesheets B and C in that order;</p>
     * <p>stylesheet B imports stylesheet D;</p>
     * <p>stylesheet C imports stylesheet E.</p>
     * <p>Then the order of import precedence (highest first) is 
     * A, C, E, B, D.</p>
     */
    protected void recomposeImports()
    {
      if(null == m_globalImportList)
      {
        m_globalImportList = new Vector();
        int n = getImportCount();
        for(int i = 0; i < n; i++)
        {
          StylesheetComposed imported = getImport(i);
          addImports(imported);
        }
        m_globalImportList.insertElementAt(this, 0);
      }
      super.recomposeImports();
    }
    
    /**
     * Get a stylesheet from the global import list.
     */
    protected StylesheetComposed getGlobalImport(int i)
    {
      return (StylesheetComposed)m_globalImportList.elementAt(i);
    }
    
    /**
     * Get the total number of imports in the global import list.
     * @return The total number of imported stylesheets, including 
     * the root stylesheet, thus the number will always be 1 or 
     * greater.
     */
    protected int getGlobalImportCount()
    {
      return m_globalImportList.size();
    }
    
    /**
     * Given a stylesheet, return the number of the stylesheet 
     * in the global import list.
     * @param sheet The stylesheet which will be located in the 
     * global import list.
     * @return The index into the global import list of the given stylesheet,
     * or -1 if it is not found (which should never happen).
     */
    protected int getImportNumber(StylesheetComposed sheet)
    {
      if(this == sheet)
        return 0;
      
      int n = getImportCount();
      for(int i = 0; i < n; i++)
      {
        if(this == getImport(i))
          return i;
      }
      return -1;
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * The default template to use for text nodes if we don't find
     * anything else.  This is initialized in initDefaultRule().
     * @serial
     */
    private ElemTemplate m_defaultTextRule;
    
    /**
     * <meta name="usage" content="advanced"/>
     * Get the default template for text.
     */
    public ElemTemplate getDefaultTextRule()
    {
      return m_defaultTextRule;
    }
    
  
    /**
     * <meta name="usage" content="advanced"/>
     * The default template to use if we don't find anything
     * else.  This is initialized in initDefaultRule().
     * @serial
     */
    private ElemTemplate m_defaultRule;
  
    /**
     * <meta name="usage" content="advanced"/>
     * Get the default template for elements.
     */
    public ElemTemplate getDefaultRule()
    {
      return m_defaultRule;
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * The default template to use for the root if we don't find
     * anything else.  This is initialized in initDefaultRule().
     * We kind of need this because the defaultRule isn't good
     * enough because it doesn't supply a document context.
     * For now, I default the root document element to "HTML".
     * Don't know if this is really a good idea or not.
     * I suspect it is not.
     * @serial
     */
    private ElemTemplate m_defaultRootRule;
  
    /**
     * <meta name="usage" content="advanced"/>
     * Get the default template for a root node.
     */
    public ElemTemplate getDefaultRootRule()
    {
      return m_defaultRootRule;
    }
  
    /**
     * Create the default rule if needed.
     */
    private void initDefaultRule()
      throws SAXException
    {
      XPathParser processor = new XPathParser();
  
      // Then manufacture a default
      m_defaultRule = new ElemTemplate();
      m_defaultRule.setStylesheet(this);
      XPath defMatch = new XPath();
      processor.initMatchPattern(defMatch, "*", this);
      m_defaultRule.setMatch(defMatch);
  
      ElemApplyTemplates childrenElement
        = new ElemApplyTemplates();
      childrenElement.setIsDefaultTemplate(true);
      m_defaultRule.appendChild(childrenElement);
  
      // -----------------------------
  
      m_defaultTextRule = new ElemTemplate();
      m_defaultTextRule.setStylesheet(this);
      
      defMatch = new XPath();
      processor.initMatchPattern(defMatch, "text() | @*", this);
      m_defaultTextRule.setMatch(defMatch);
  
      ElemValueOf elemValueOf
        = new ElemValueOf();
      m_defaultTextRule.appendChild(elemValueOf);
      
      XPath selectPattern = new XPath();
      processor.initXPath(selectPattern, ".", this);
      elemValueOf.setSelect(selectPattern);
  
  
      //--------------------------------
  
      m_defaultRootRule = new ElemTemplate();
      m_defaultRootRule.setStylesheet(this);
      
      defMatch = new XPath();
      processor.initMatchPattern(defMatch, "/", this);
      m_defaultRootRule.setMatch(defMatch);
  
      childrenElement
        = new ElemApplyTemplates();
      childrenElement.setIsDefaultTemplate(true);
      m_defaultRootRule.appendChild(childrenElement);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/TemplateList.java
  
  Index: TemplateList.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import java.util.Hashtable;
  import org.w3c.dom.Node;
  import org.xml.sax.SAXException;
  import java.util.Vector;
  import java.io.Serializable;
  
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.PsuedoNames;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.xpath.XPathContext;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Encapsulates a template list, and helps locate individual templates.
   */
  public class TemplateList implements java.io.Serializable
  {
    /**
     * Construct a TemplateList object.
     */
    TemplateList(Stylesheet stylesheet)
    {
      m_stylesheet = stylesheet;
    }
    
    /**
     * Add a template to the template list.
     */
    public void setTemplate(ElemTemplate template)
    {
      int pos = 0;
      if(null == m_firstTemplate)
      {
        m_firstTemplate = template;
      }
      else
      {
        ElemTemplateElement next = m_firstTemplate;
        while(null != next)
        {
          if(null == next.m_nextSibling)
          {
            next.m_nextSibling = template;
            template.m_nextSibling = null; // just to play it safe.
            break;
          }
          pos++;
          next = next.m_nextSibling;
        }
      }
      if(null != template.getName())
      {
        m_namedTemplates.put(template.getName(), template);
      }
  
      if(null != template.getMatch())
      {
        Vector strings = template.getMatch().getTargetElementStrings();
        if(null != strings)
        {
          int nTargets = strings.size();
          for(int stringIndex = 0; stringIndex < nTargets; stringIndex++)
          {
            String target = (String)strings.elementAt(stringIndex);
  
            Object newMatchPat = new 
MatchPattern2(template.getMatch().getPatternString(),
                                                   template.getMatch(),
                                                   template, pos,
                                                   target, m_stylesheet);
  
            // See if there's already one there
            Object val = m_patternTable.get(target);
            if(null == val)
            {
              // System.out.println("putting: "+target);
              m_patternTable.put(target, newMatchPat);
            }
            else
            {
              // find the tail of the list
              MatchPattern2 matchPat = (MatchPattern2)val;
              ((MatchPattern2)newMatchPat).setNext(matchPat);
              m_patternTable.put(target, newMatchPat);
              /*
              MatchPattern2 next;
              while((next = matchPat.getNext()) != null)
              {
              matchPat = next;
              }
              // System.out.println("appending: "+target+" to 
"+matchPat.getPattern());
              matchPat.setNext((MatchPattern2)newMatchPat);
              */
            }
          }
        }
      }
    }
    
    /**
     * Locate a macro via the "name" attribute.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public ElemTemplate getTemplate(QName qname)
    {
      ElemTemplate namedTemplate = (ElemTemplate)m_namedTemplates.get(qname);
      if(null == namedTemplate)
      {
        StylesheetComposed stylesheet = getStylesheet().getStylesheetComposed();
        int n = stylesheet.getImportCountComposed();
        for(int i = 0; i < n; i++)
        {
          StylesheetComposed imported = stylesheet.getImportComposed(i);
          namedTemplate = imported.getTemplateComposed(qname);
          if(null != namedTemplate)
            break;
        }
      }
      return namedTemplate;
    }
    
    /**
     * Given a target element, find the template that best
     * matches in the given XSL document, according
     * to the rules specified in the xsl draft.
     * @param stylesheetTree Where the XSL rules are to be found.
     * @param targetElem The element that needs a rule.
     * @param mode A string indicating the display mode.
     * @param useImports means that this is an xsl:apply-imports commend.
     * @return Rule that best matches targetElem.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public ElemTemplate getTemplate(XPathContext support,
                                    Node targetNode,
                                    QName mode,
                                    boolean quietConflictWarnings)
      throws SAXException
    {
      ElemTemplate bestMatchedRule = null;
      MatchPattern2 bestMatchedPattern =null; // Syncs with bestMatchedRule
      if(m_isWrapperless)
      {
        return m_wrapperlessTemplate;
      }
      Vector conflicts = null;
  
      double highScore = XPath.MATCH_SCORE_NONE;
  
      MatchPattern2 matchPat = null;
      int targetNodeType = targetNode.getNodeType();
  
      switch(targetNodeType)
      {
      case Node.ELEMENT_NODE:
        // String targetName = 
m_parserLiaison.getExpandedElementName((Element)targetNode);
        String targetName = 
support.getDOMHelper().getLocalNameOfNode(targetNode);
        matchPat = locateMatchPatternList2(targetName, true);
        break;
  
      case Node.PROCESSING_INSTRUCTION_NODE:
      case Node.ATTRIBUTE_NODE:
        matchPat = locateMatchPatternList2(targetNode.getNodeName(), true);
        break;
  
      case Node.CDATA_SECTION_NODE:
      case Node.TEXT_NODE:
        matchPat = locateMatchPatternList2(PsuedoNames.PSEUDONAME_TEXT, false);
        break;
  
      case Node.COMMENT_NODE:
        matchPat = locateMatchPatternList2(PsuedoNames.PSEUDONAME_COMMENT, 
false);
        break;
  
      case Node.DOCUMENT_NODE:
        matchPat = locateMatchPatternList2(PsuedoNames.PSEUDONAME_ROOT, false);
        break;
  
      case Node.DOCUMENT_FRAGMENT_NODE:
        matchPat = locateMatchPatternList2(PsuedoNames.PSEUDONAME_ANY, false);
        break;
  
      default:
        {
          matchPat = locateMatchPatternList2(targetNode.getNodeName(), false);
        }
      }
  
      String prevPat = null;
      MatchPattern2 prevMatchPat = null;
  
      while(null != matchPat)
      {
        ElemTemplate rule = matchPat.getTemplate();
        // We'll be needing to match rules according to what
        // mode we're in.
        QName ruleMode = rule.getMode();
  
        // The logic here should be that if we are not in a mode AND
        // the rule does not have a node, then go ahead.
        // OR if we are in a mode, AND the rule has a node,
        // AND the rules match, then go ahead.
        if(((null == mode) && (null == ruleMode)) ||
           ((null != ruleMode) && (null != mode) && ruleMode.equals(mode)))
        {
          String patterns = matchPat.getPattern();
  
          if((null != patterns) && !((prevPat != null) && 
prevPat.equals(patterns) &&
                                     (prevMatchPat.getTemplate().getPriority()
                                      == matchPat.getTemplate().getPriority())) 
)
          {
            prevMatchPat = matchPat;
            prevPat = patterns;
  
            // Date date1 = new Date();
            XPath xpath = matchPat.getExpression();
            // System.out.println("Testing score for: 
"+targetNode.getNodeName()+
            //                   " against '"+xpath.m_currentPattern);
            double score = xpath.getMatchScore(support, targetNode);
            // System.out.println("Score for: "+targetNode.getNodeName()+
            //                   " against '"+xpath.m_currentPattern+
            //                   "' returned "+score);
  
            if(XPath.MATCH_SCORE_NONE != score)
            {
              double priorityOfRule
                = (XPath.MATCH_SCORE_NONE != rule.getPriority())
                  ? rule.getPriority() : score;
              matchPat.m_priority = priorityOfRule;
              double priorityOfBestMatched = (null != bestMatchedPattern) ?
                                             bestMatchedPattern.m_priority :
                                             XPath.MATCH_SCORE_NONE;
              // System.out.println("priorityOfRule: "+priorityOfRule+", 
priorityOfBestMatched: "+priorityOfBestMatched);
              if(priorityOfRule > priorityOfBestMatched)
              {
                if(null != conflicts)
                  conflicts.removeAllElements();
                highScore = score;
                bestMatchedRule = rule;
                bestMatchedPattern = matchPat;
              }
              else if(priorityOfRule == priorityOfBestMatched)
              {
                if(null == conflicts)
                  conflicts = new Vector(10);
                addObjectIfNotFound(bestMatchedPattern, conflicts);
                conflicts.addElement(matchPat);
                highScore = score;
                bestMatchedRule = rule;
                bestMatchedPattern = matchPat;
              }
            }
            // Date date2 = new Date();
            // m_totalTimePatternMatching+=(date2.getTime() - date1.getTime());
          } // end if(null != patterns)
        } // end if if(targetModeString.equals(mode))
  
        MatchPattern2 nextMatchPat = matchPat.getNext();
  
        // We also have to consider wildcard matches.
        if((null == nextMatchPat) && !matchPat.m_targetString.equals("*") &&
           ((Node.ELEMENT_NODE == targetNodeType) ||
            (Node.ATTRIBUTE_NODE == targetNodeType) ||
            (Node.PROCESSING_INSTRUCTION_NODE == targetNodeType)))
        {
          nextMatchPat = (MatchPattern2)m_patternTable.get("*");
        }
        matchPat = nextMatchPat;
      }
  
      if(null == bestMatchedRule)
      {
        StylesheetComposed stylesheet = getStylesheet().getStylesheetComposed();
        int n = stylesheet.getImportCountComposed();
        for(int i = 0; i < n; i++)
        {
          StylesheetComposed imported = stylesheet.getImportComposed(i);
          bestMatchedRule 
            = imported.getTemplateComposed(support, 
                                           targetNode, mode, 
quietConflictWarnings);
          if(null != bestMatchedRule)
            break;
        }
      }
  
      if(null != conflicts)
      {
        int nConflicts = conflicts.size();
        // System.out.println("nConflicts: "+nConflicts);
        String conflictsString = (!quietConflictWarnings)
                                 ? "" : null;
        for(int i = 0; i < nConflicts; i++)
        {
          MatchPattern2 conflictPat = (MatchPattern2)conflicts.elementAt(i);
          if(0 != i)
          {
            if(!quietConflictWarnings)
              conflictsString += ", ";
  
            // Find the furthest one towards the bottom of the document.
            if(conflictPat.m_posInStylesheet > 
bestMatchedPattern.m_posInStylesheet)
            {
              bestMatchedPattern = conflictPat;
            }
          }
          else
          {
            bestMatchedPattern = conflictPat;
          }
          if(!quietConflictWarnings)
            conflictsString += "\""+conflictPat.getPattern()+"\"";
        }
        bestMatchedRule = bestMatchedPattern.getTemplate();
        if(!quietConflictWarnings)
        {
          //conflictsString += " ";
          //conflictsString += "Last found in stylesheet will be used.";
          
          // transformContext.warn(XSLTErrorResources.WG_SPECIFICITY_CONFLICTS, 
new Object[] {conflictsString});
        }
      }
  
      return bestMatchedRule;
    } // end findTemplate
    
    /**
     * Set the manufactured template if there is no wrapper.
     * and xsl:template wrapper.
     */
    public void setWrapperlessTemplate(ElemTemplate t)
    {
      setIsWrapperless(true);
      m_wrapperlessTemplate = t;
    }
  
    /**
     * Get the manufactured template if there is no wrapper.
     * and xsl:template wrapper.
     */
    public ElemTemplate getWrapperlessTemplate()
    {
      return m_wrapperlessTemplate;
    }
  
    /**
     * Add object to vector if not already there.
     */
    private void addObjectIfNotFound(Object obj, Vector v)
    {
      int n = v.size();
      boolean addIt = true;
      for(int i = 0; i < n; i++)
      {
        if(v.elementAt(i) == obj)
        {
          addIt = false;
          break;
        }
      }
      if(addIt)
      {
        v.addElement(obj);
      }
    }
  
    /**
     * The stylesheet owner of the list.
     */
    private Stylesheet m_stylesheet;
    
    /**
     * Get the stylesheet owner of the list.
     */
    private Stylesheet getStylesheet()
    {
      return m_stylesheet;
    }
  
    /**
     * The first template of the template children.
     * @serial
     */
    private ElemTemplateElement m_firstTemplate = null;
  
    /**
     * Get the first template of the template children.
     */
    private ElemTemplateElement getFirstTemplate()
    {
      return m_firstTemplate;
    }
  
    /**
     * Keyed on string macro names, and holding values
     * that are macro elements in the XSL DOM tree.
     * Initialized in initMacroLookupTable, and used in
     * findNamedTemplate.
     * @serial
     */
    private Hashtable m_namedTemplates = new Hashtable();
  
    /**
     * Tells if the stylesheet is without an xsl:stylesheet
     * and xsl:template wrapper.
     * @serial
     */
    private boolean m_isWrapperless = false;
  
    /**
     * The manufactured template if there is no wrapper.
     * @serial
     */
    private ElemTemplate m_wrapperlessTemplate = null;
  
    /**
     * This table is keyed on the target elements
     * of patterns, and contains linked lists of
     * the actual patterns that match the target element
     * to some degree of specifity.
     * @serial
     */
    private Hashtable m_patternTable = new Hashtable();
  
    /**
     * Set if the stylesheet is without an xsl:stylesheet
     * and xsl:template wrapper.
     */
    private void setIsWrapperless(boolean b)
    {
      m_isWrapperless = b;
    }
  
    /**
     * Get if the stylesheet is without an xsl:stylesheet
     * and xsl:template wrapper.
     */
    boolean getIsWrapperless()
    {
      return m_isWrapperless;
    }
  
    /**
     * Get table of named Templates.
     * These are keyed on string macro names, and holding values
     * that are template elements in the XSL DOM tree.
     */
    private Hashtable getNamedTemplates()
    {
      return m_namedTemplates;
    }
  
    /**
     * Set table of named Templates.
     * These are keyed on string macro names, and holding values
     * that are template elements in the XSL DOM tree.
     */
    private void setNamedTemplates(Hashtable v)
    {
      m_namedTemplates = v;
    }
  
    /**
     * Given an element type, locate the start of a linked list of
     * possible template matches.
     */
    private MatchPattern2 locateMatchPatternList2(String sourceElementType, 
boolean tryWildCard)
    {
      MatchPattern2 startMatchList = null;
      Object val = m_patternTable.get(sourceElementType);
      if(null != val)
      {
        startMatchList = (MatchPattern2)val;
      }
      else if(tryWildCard)
      {
        val = m_patternTable.get("*");
        if(null != val)
        {
          startMatchList = (MatchPattern2)val;
        }
      }
      return startMatchList;
    }
  
    /**
     * A class to contain a match pattern and it's corresponding template.
     * This class also defines a node in a match pattern linked list.
     */
    class MatchPattern2 implements Serializable
    {
      /**
       * Construct a match pattern from a pattern and template.
       * @param pat For now a Nodelist that contains old-style element patterns.
       * @param template The node that contains the template for this pattern.
       * @param isMatchPatternsOnly tells if pat param contains only match
       * patterns (for compatibility with old syntax).
       */
      MatchPattern2(String pat, XPath exp, ElemTemplate template, int 
posInStylesheet,
                    String targetString, Stylesheet stylesheet)
      {
        m_pattern = pat;
        m_template = template;
        m_posInStylesheet = posInStylesheet;
        m_targetString = targetString;
        m_stylesheet = stylesheet;
        m_expression = exp;
      }
  
      Stylesheet m_stylesheet;
  
      String m_targetString;
  
      XPath m_expression;
      public XPath getExpression() { return m_expression; }
  
      int m_posInStylesheet;
  
      /**
       * Transient... only used to track priority while
       * processing.
       */
      double m_priority = XPath.MATCH_SCORE_NONE;
  
      private String m_pattern;
      public String getPattern() { return m_pattern; }
  
      private ElemTemplate m_template; // ref to the corrisponding template
      public ElemTemplate getTemplate() { return m_template; }
  
      private MatchPattern2 m_next = null; // null when at end of list.
      public MatchPattern2 getNext() { return m_next; }
      public void setNext(MatchPattern2 mp) { m_next = mp; }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/WhiteSpaceInfo.java
  
  Index: WhiteSpaceInfo.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.templates;
  
  import org.apache.xalan.xpath.XPath;
  
  /**
   * This is used as a special "fake" template that can be 
   * handled by the TemplateList to do pattern matching 
   * on nodes.
   */
  public class WhiteSpaceInfo extends ElemTemplate
  {
    private boolean m_shouldStripSpace;
    
    /**
     * Return true if this element specifies that the node that 
     * matches the match pattern should be stripped, otherwise 
     * the space should be preserved.
     */
    public boolean getShouldStripSpace()
    {
      return m_shouldStripSpace;
    }
    
    WhiteSpaceInfo(XPath matchPattern, boolean shouldStripSpace)
    {
      m_shouldStripSpace = shouldStripSpace;
      setMatch(matchPattern);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/templates/XMLNSDecl.java
  
  Index: XMLNSDecl.java
  ===================================================================
  package org.apache.xalan.templates;
  
  /**
   * Represents an xmlns declaration
   */
  public class XMLNSDecl
  {
    
    public XMLNSDecl(String prefix, String uri, boolean isExcluded)
    {
      m_prefix = prefix;
      m_uri = uri;
      m_isExcluded = isExcluded;
    }
    
    private String m_prefix;
  
    /**
     * Return the prefix.
     * @return The prefix that is associated with this URI, or null 
     * if the XMLNSDecl is declaring the default namespace.
     */
    public String getPrefix ()
    {
      return m_prefix;
    }
    
    private String m_uri;
  
    /**
     * Return the URI.
     * @return The URI that is associated with this declaration.
     */
    public String getURI ()
    {
      return m_uri;
    }
    
    private boolean m_isExcluded;
    
    /**
     * Tell if this declaration should be excluded from the 
     * result namespace.
     */
    public boolean getIsExcluded()
    {
      return m_isExcluded;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/trace/GenerateEvent.java
  
  Index: GenerateEvent.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.trace;
  
  import org.xml.sax.*;
  import java.util.*;
  import java.io.*;
  import org.apache.xalan.transformer.TransformerImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Event generated by the XSL processor after it generates a new node in the 
result tree.
   * This event responds to and is modeled on the SAX events that are sent to 
the
   * formatter listener FormatterToXXX)classes.
   *
   * @see org.apache.xalan.utils.DOMBuilder
   * @see org.apache.xalan.utils.FormatterToHTML
   * @see org.apache.xalan.utils.FormatterToText
   * @see org.apache.xalan.utils.FormatterToXML
  
   */
  public class GenerateEvent  implements java.util.EventListener
  {
    /**
     * The XSLT Processor, which either directly or indirectly contains most 
needed information.
     * Accessing the m_stylesheetRoot member variable will get you to the 
stylesheet information.
     *
     * @see org.apache.xalan.xslt.TransformerImpl, 
org.apache.xalan.xslt.StylesheetRoot,
     *     org.apache.xalan.xslt.Stylesheet
     */
    public TransformerImpl m_processor;
  
    /**
     * The type of SAX event that was generated, as enumerated in the 
EVENTTYPE_XXX constants below.
     */
    public int m_eventtype;
  
    /**
     * Event type generated when a document begins.
     *
     */
    public static final int EVENTTYPE_STARTDOCUMENT = 1;
  
    /**
     * Event type generated when a document ends.
     */
    public static final int EVENTTYPE_ENDDOCUMENT = 2;
  
    /**
     * Event type generated when an element begins (after the attributes have 
been processed but before the children have been added).
     */
    public static final int EVENTTYPE_STARTELEMENT = 3;
  
    /**
     * Event type generated when an element ends, after it's children have been 
added.
     */
    public static final int EVENTTYPE_ENDELEMENT = 4;
  
    /**
     * Event type generated for character data (CDATA and Ignorable Whitespace 
have their own events).
     */
    public static final int EVENTTYPE_CHARACTERS = 5;
  
    /**
     * Event type generated for ignorable whitespace (I'm not sure how much 
this is actually called.
     */
    public static final int EVENTTYPE_IGNORABLEWHITESPACE = 6;
  
    /**
     * Event type generated for processing instructions.
     */
    public static final int EVENTTYPE_PI = 7;
  
    /**
     * Event type generated after a comment has been added.
     */
    public static final int EVENTTYPE_COMMENT = 8;
  
    /**
     * Event type generate after an entity ref is created.
     */
    public static final int EVENTTYPE_ENTITYREF = 9;
  
    /**
     * Event type generated after CDATA is generated.
     */
    public static final int EVENTTYPE_CDATA = 10;
  
    /**
     * Character data from a character or cdata event.
     */
    public char m_characters[];
  
    /**
     * The start position of the current data in m_characters.
     */
    public int m_start;
  
    /**
     * The length of the current data in m_characters.
     */
    public int m_length;
  
    /**
     * The name of the element or PI.
     */
    public String m_name;
  
    /**
     * The string data in the element (comments and PIs).
     */
    public String m_data;
  
    /**
     * The current attribute list.
     */
    public Attributes m_atts;
  
    /**
     * Constructor for startDocument, endDocument events.
     *
     * @param processor The XSLT Processor instance.
     * @param eventType One of the EVENTTYPE_XXX constants.
     */
    public GenerateEvent(TransformerImpl processor, int eventType)
    {
      m_processor = processor;
      m_eventtype = eventType;
    }
  
    /**
     * Constructor for startElement, endElement events.
     *
     * @param processor The XSLT Processor Instance.
     * @param eventType One of the EVENTTYPE_XXX constants.
     * @param name The name of the element.
     * @param atts The SAX attribute list.
     */
    public GenerateEvent(TransformerImpl processor, int eventType,
                           String name, Attributes atts)
    {
      m_name = name;
      m_atts = atts;
      m_processor = processor;
      m_eventtype = eventType;
    }
  
    /**
     * Constructor for characters, cdate events.
     *
     * @param processor The XSLT Processor instance.
     * @param eventType One of the EVENTTYPE_XXX constants.
     * @param ch The char array from the SAX event.
     * @param start The start offset to be used in the char array.
     * @param length The end offset to be used in the chara array.
     */
    public GenerateEvent(TransformerImpl processor, int eventType,
                           char ch[], int start, int length)
    {
      m_characters = ch;
      m_start = start;
      m_length = length;
      m_processor = processor;
      m_eventtype = eventType;
    }
  
    /**
     * Constructor for processingInstruction events.
     *
     * @param processor The instance of the XSLT processor.
     * @param eventType One of the EVENTTYPE_XXX constants.
     * @param name The name of the processing instruction.
     * @param data The processing instruction data.
     */
    public GenerateEvent(TransformerImpl processor, int eventType,
                           String name, String data)
    {
      m_name = name;
      m_data = data;
      m_processor = processor;
      m_eventtype = eventType;
    }
  
    /**
     * Constructor for comment and entity ref events.
     *
     * @param processor The XSLT processor instance.
     * @param eventType One of the EVENTTYPE_XXX constants.
     * @param data The comment or entity ref data.
     */
    public GenerateEvent(TransformerImpl processor, int eventType,
                           String data)
    {
      m_data = data;
      m_processor = processor;
      m_eventtype = eventType;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/trace/PrintTraceListener.java
  
  Index: PrintTraceListener.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.trace;
  
  import java.io.*;
  
  import org.w3c.dom.*;
  import org.w3c.dom.traversal.NodeIterator;
  import org.apache.xalan.templates.ElemTemplate;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.templates.ElemTextLiteral;
  import org.apache.xalan.templates.Constants;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implementation of the TraceListener interface that
   * prints each event to standard out as it occurs.
   *
   * @see TracerEvent.java
   */
  public class PrintTraceListener implements TraceListener
  {
    /**
     * Construct a trace listener.
     */
    public PrintTraceListener(java.io.PrintWriter pw)
    {
      m_pw = pw;
    }
  
    /**
     * The print writer where the events should be written.
     */
    java.io.PrintWriter m_pw;
  
    /**
     * This needs to be set to true if the listener is to print an event 
whenever a template is invoked.
     */
    public boolean m_traceTemplates = false;
  
    /**
     * Set to true if the listener is to print events that occur as each node 
is 'executed' in the stylesheet.
     */
    public boolean m_traceElements = false;
  
    /**
     * Set to true if the listener is to print information after each 
result-tree generation event.
     */
    public boolean m_traceGeneration = false;
  
    /**
     * Set to true if the listener is to print information after each selection 
event.
     */
    public boolean m_traceSelection = false;
  
    /**
     * Print information about a TracerEvent.
     *
     * @param ev the trace event.
     */
    public void trace(TracerEvent ev)
    {
      switch(ev.m_styleNode.getXSLToken())
      {
      case Constants.ELEMNAME_TEXTLITERALRESULT:
        if(m_traceElements)
        {
          m_pw.print("Line #"+ev.m_styleNode.getLineNumber()+", "+
                           "Column #"+ev.m_styleNode.getColumnNumber()+" -- "+
                           ev.m_styleNode.getNodeName()+": ");
          ElemTextLiteral etl = (ElemTextLiteral)ev.m_styleNode;
          String chars = new String(etl.getChars(), 0, etl.getChars().length);
          m_pw.println("    "+chars.trim());
        }
        break;
      case Constants.ELEMNAME_TEMPLATE:
        if(m_traceTemplates || m_traceElements)
        {
          ElemTemplate et = (ElemTemplate)ev.m_styleNode;
          m_pw.print("Line #"+et.getLineNumber()+", "+
                             "Column #"+et.getColumnNumber()+": "+
                             et.getNodeName()+" ");
          if(null != et.getMatch())
          {
            m_pw.print("match='"+et.getMatch().getPatternString()+"' ");
          }
          if(null != et.getName())
          {
            m_pw.print("name='"+et.getName()+"' ");
          }
          m_pw.println();
        }
        break;
      default:
        if(m_traceElements)
        {
          m_pw.println("Line #"+ev.m_styleNode.getLineNumber()+", "+
                             "Column #"+ev.m_styleNode.getColumnNumber()+": "+
                             ev.m_styleNode.getNodeName());
        }
  
      }
    }
  
    /**
     * Method that is called just after the formatter listener is called.
     *
     * @param ev the generate event.
     */
    public void selected(SelectionEvent ev)
      throws org.xml.sax.SAXException
    {
      if(m_traceSelection)
      {
        ElemTemplateElement ete = (ElemTemplateElement)ev.m_styleNode;
        if(ev.m_styleNode.getLineNumber() == 0)
        {
          // You may not have line numbers if the selection is occuring from a
          // default template.
          ElemTemplateElement parent = (ElemTemplateElement)ete.getParentNode();
          if(parent == ete.getStylesheetRoot().getDefaultRootRule())
          {
            m_pw.print("(default root rule) ");
          }
          else if(parent == ete.getStylesheetRoot().getDefaultTextRule())
          {
            m_pw.print("(default text rule) ");
          }
          else if(parent == ete.getStylesheetRoot().getDefaultRule())
          {
            m_pw.print("(default rule) ");
          }
          m_pw.print(ete.getNodeName()+", 
"+ev.m_attributeName+"='"+ev.m_xpath.getPatternString()+"': ");
        }
        else
        {
          m_pw.print("Line #"+ev.m_styleNode.getLineNumber()+", "+
                           "Column #"+ev.m_styleNode.getColumnNumber()+": "+
                           ete.getNodeName()+", 
"+ev.m_attributeName+"='"+ev.m_xpath.getPatternString()+"': ");
        }
        if(ev.m_selection.getType() == ev.m_selection.CLASS_NODESET)
        {
          m_pw.println();
          NodeIterator nl = ev.m_selection.nodeset();
          Node pos = nl.nextNode();
          if(null == pos)
          {
            m_pw.println("     [empty node list]");
          }
          else
          {
            while(null != pos)
            {
              m_pw.println("     "+pos);
              pos = nl.nextNode();
            }
          }
        }
        else
        {
          m_pw.println(ev.m_selection.str());
        }
      }
    }
  
    /**
     * Print information about a Generate event.
     *
     * @param ev the trace event.
     */
    public void generated(GenerateEvent ev)
    {
      if(m_traceGeneration)
      {
        switch(ev.m_eventtype)
        {
        case GenerateEvent.EVENTTYPE_STARTDOCUMENT:
          m_pw.println("STARTDOCUMENT");
          break;
        case GenerateEvent.EVENTTYPE_ENDDOCUMENT:
          m_pw.println("ENDDOCUMENT");
          break;
        case GenerateEvent.EVENTTYPE_STARTELEMENT:
          m_pw.println("STARTELEMENT: "+ev.m_name);
          break;
        case GenerateEvent.EVENTTYPE_ENDELEMENT:
          m_pw.println("ENDELEMENT: "+ev.m_name);
          break;
        case GenerateEvent.EVENTTYPE_CHARACTERS:
          {
            String chars = new String(ev.m_characters, ev.m_start, ev.m_length);
            m_pw.println("CHARACTERS: "+chars);
          }
          break;
        case GenerateEvent.EVENTTYPE_CDATA:
          {
            String chars = new String(ev.m_characters, ev.m_start, ev.m_length);
            m_pw.println("CDATA: "+chars);
          }
          break;
        case GenerateEvent.EVENTTYPE_COMMENT:
          m_pw.println("COMMENT: "+ev.m_data);
          break;
        case GenerateEvent.EVENTTYPE_PI:
          m_pw.println("PI: "+ev.m_name+", "+ev.m_data);
          break;
        case GenerateEvent.EVENTTYPE_ENTITYREF:
          m_pw.println("ENTITYREF: "+ev.m_name);
          break;
        case GenerateEvent.EVENTTYPE_IGNORABLEWHITESPACE:
          m_pw.println("IGNORABLEWHITESPACE");
          break;
        }
      }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/trace/SelectionEvent.java
  
  Index: SelectionEvent.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.trace;
  
  import org.w3c.dom.*;
  
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Event triggered by selection of a node in the style stree.
   */
  public class SelectionEvent implements java.util.EventListener
  {
    /**
     * The node in the style tree where the event occurs.
     */
    public final ElemTemplateElement m_styleNode;
  
    /**
     * The XSLT processor instance.
     */
    public final TransformerImpl m_processor;
  
    /**
     * The current context node.
     */
    public final Node m_sourceNode;
  
    /**
     * The attribute name from which the selection is made.
     */
    public final String m_attributeName;
  
    /**
     * The XPath that executed the selection.
     */
    public final XPath m_xpath;
  
    /**
     * The result of the selection.
     */
    public final XObject m_selection;
  
    /**
     * Create an event originating at the given node of the style tree.
     * @param processor The XSLT Processor.
     * @param sourceNode The current context node.
     * @param mode The current mode.
     * @param m_styleNode node in the style tree reference for the event.
     * Should not be null.  That is not enforced.
     */
    public SelectionEvent(TransformerImpl processor,
                       Node sourceNode,
                       ElemTemplateElement styleNode,
                       String attributeName,
                       XPath xpath,
                       XObject selection)
    {
      this.m_processor = processor;
      this.m_sourceNode = sourceNode;
      this.m_styleNode = styleNode;
      this.m_attributeName = attributeName;
      this.m_xpath = xpath;
      this.m_selection = selection;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/trace/TraceListener.java
  
  Index: TraceListener.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.trace;
  
  import org.w3c.dom.*;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Interface the XSL processor calls when it matches a source node, selects a 
set of source nodes,
   * or generates a result node.
   * If you want an object instance to be called when a trace event occurs, use 
the TransformerImpl setTraceListener method.
   * @see TracerEvent.java
   * @see org.apache.xalan.xslt.TransformerImpl#setTraceListener
   */
  public interface TraceListener extends java.util.EventListener
  {
    /**
     * Method that is called when a trace event occurs.
     * The method is blocking.  It must return before processing continues.
     *
     * @param ev the trace event.
     */
    public void trace(TracerEvent ev);
  
    /**
     * Method that is called just after the formatter listener is called.
     *
     * @param ev the generate event.
     */
    public void selected(SelectionEvent ev)
      throws org.xml.sax.SAXException;
  
    /**
     * Method that is called just after the formatter listener is called.
     *
     * @param ev the generate event.
     */
    public void generated(GenerateEvent ev);
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/trace/TraceManager.java
  
  Index: TraceManager.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.trace;
  
  import java.util.Vector;
  import java.util.TooManyListenersException;
  import org.w3c.dom.Node;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XPath;
  
  /**
   * This class manages trace listeners, and acts as an 
   * interface for the tracing functionality in Xalan.
   */
  public class TraceManager
  {
    private TransformerImpl m_transformer;
    
    /**
     * Constructor for the trace manager.
     */
    public TraceManager(TransformerImpl transformer)
    {
      m_transformer = transformer;
    }
    
    /**
     * List of listeners who are interested in tracing what's
     * being generated.
     */
    private Vector m_traceListeners = null;
  
    /**
     * Add a trace listener for the purposes of debugging and diagnosis.
     * @param tl Trace listener to be added.
     */
    public void addTraceListener(TraceListener tl)
      throws TooManyListenersException
    {
      if(null == m_traceListeners)
        m_traceListeners = new Vector();
      m_traceListeners.addElement(tl);
    }
  
    /**
     * Remove a trace listener.
     * @param tl Trace listener to be removed.
     */
    public void removeTraceListener(TraceListener tl)
    {
      if(null != m_traceListeners)
      {
        m_traceListeners.removeElement(tl);
      }
    }
  
    /**
     * Fire a generate event.
     */
    public void fireGenerateEvent(GenerateEvent te)
    {
      if(null != m_traceListeners)
      {
        int nListeners = m_traceListeners.size();
        for(int i = 0; i < nListeners; i++)
        {
          TraceListener tl = (TraceListener)m_traceListeners.elementAt(i);
          tl.generated(te);
        }
      }
    }
    
    /**
     * Tell if trace listeners are present.
     */
    public boolean hasTraceListeners()
    {
      return (null != m_traceListeners);
    }
    
    /**
     * Fire a trace event.
     */
    public void fireTraceEvent(Node sourceNode,
                               QName mode,
                               ElemTemplateElement styleNode)
    {
      if(hasTraceListeners())
      {
        fireTraceEvent(new TracerEvent(m_transformer,  
                                       sourceNode, mode, styleNode));
      }
    }
  
    
    /**
     * Fire a trace event.
     */
    public void fireTraceEvent(TracerEvent te)
    {
      if(hasTraceListeners())
      {
        int nListeners = m_traceListeners.size();
        for(int i = 0; i < nListeners; i++)
        {
          TraceListener tl = (TraceListener)m_traceListeners.elementAt(i);
          tl.trace(te);
        }
      }
    }
    
    /**
     * Fire a selection event.
     */
    public void fireSelectedEvent(Node sourceNode,
                                  ElemTemplateElement styleNode,
                                  String attributeName,
                                  XPath xpath,
                                  XObject selection)
      throws org.xml.sax.SAXException
    {
      if(hasTraceListeners())
        fireSelectedEvent(new SelectionEvent(m_transformer, sourceNode, 
styleNode, 
                                             attributeName, xpath, selection));
    }
  
    /**
     * Fire a selection event.
     */
    public void fireSelectedEvent(SelectionEvent se)
      throws org.xml.sax.SAXException
    {
      if(hasTraceListeners())
      {
        int nListeners = m_traceListeners.size();
        for(int i = 0; i < nListeners; i++)
        {
          TraceListener tl = (TraceListener)m_traceListeners.elementAt(i);
          tl.selected(se);
        }
      }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/trace/TracerEvent.java
  
  Index: TracerEvent.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.trace;
  
  import org.w3c.dom.*;
  
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.transformer.TransformerImpl;
  import org.apache.xalan.utils.QName;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Parent class of events generated for tracing the
   * progress of the XSL processor.
   */
  public class TracerEvent implements java.util.EventListener
  {
    /**
     * The node in the style tree where the event occurs.
     */
    public final ElemTemplateElement m_styleNode;
  
    /**
     * The XSLT processor instance.
     */
    public final TransformerImpl m_processor;
  
    /**
     * The current context node.
     */
    public final Node m_sourceNode;
  
    /**
     * The current mode.
     */
    public final QName m_mode;
  
    /**
     * Create an event originating at the given node of the style tree.
     * @param processor The XSLT Processor.
     * @param sourceNode The current context node.
     * @param mode The current mode.
     * @param m_styleNode node in the style tree reference for the event.
     * Should not be null.  That is not enforced.
     */
    public TracerEvent(TransformerImpl processor,
                       Node sourceNode,
                       QName mode,
                       ElemTemplateElement styleNode)
    {
      this.m_processor = processor;
      this.m_sourceNode = sourceNode;
      this.m_mode = mode;
      this.m_styleNode = styleNode;
    }
  
    /**
     Returns a string representation of the node.
     The string returned for elements will contain the element name
     and any attributes enclosed in angle brackets.
     The string returned for attributes will be of form, "name=value."
  
     @param n any DOM node. Must not be null.
  
     @return a string representation of the given node.
     */
    public static String printNode(Node n)
    {
      String r = n.hashCode() + " ";
  
      if (n instanceof Element)
      {
        r += "<"+n.getNodeName();
        Node c = n.getFirstChild();
        while (null != c)
        {
          if (c instanceof Attr)
          {
            r += printNode(c) + " ";
          }
          c = c.getNextSibling();
        }
        r += ">";
      }
      else
      {
        if (n instanceof Attr)
        {
          r += n.getNodeName()+"="+n.getNodeValue();
        }
        else
        {
          r += n.getNodeName();
        }
      }
  
      return r;
    }
  
    /**
     Returns a string representation of the node list.
     The string will contain the list of nodes inside square braces.
     Elements will contain the element name
     and any attributes enclosed in angle brackets.
     Attributes will be of form, "name=value."
  
     @param l any DOM node list. Must not be null.
  
     @return a string representation of the given node list.
     */
    public static String printNodeList(NodeList l)
    {
      String r = l.hashCode() + "[";
      int len = l.getLength() - 1;
      int i = 0;
      while (i < len)
      {
        Node n = l.item(i);
        if (null != n)
        {
          r += printNode(n) + ", ";
        }
        ++i;
      }
      if (i == len)
      {
        Node n = l.item(len);
        if (null != n)
        {
          r += printNode(n);
        }
      }
      return r + "]";
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/Counter.java
  
  Index: Counter.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import org.w3c.dom.Node;
  import org.apache.xalan.utils.NodeVector;
  import org.apache.xalan.xpath.NodeSet; // for isNodeAfter support
  import org.apache.xalan.xpath.XPathContext;
  import org.xml.sax.SAXException;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.templates.ElemNumber;
  
  /**
   * <meta name="usage" content="internal"/>
   * A class that does incremental counting for support of xsl:number.
   * This class stores a cache of counted nodes (m_countNodes). 
   * It tries to cache the counted nodes in document order... 
   * the node count is based on its position in the cache list 
   */
  class Counter
  {
    /**
     * Set the maximum ammount the m_countNodes list can 
     * grow to.
     */
    static final int MAXCOUNTNODES = 500;
    
    /**
     * The start count from where m_countNodes counts 
     * from.  In other words, the count of a given node 
     * in the m_countNodes vector is node position + 
     * m_countNodesStartCount.
     */
    int m_countNodesStartCount = 0;
    
    /**
     * A vector of all nodes counted so far.
     */
    NodeSet m_countNodes = new NodeSet();
    
    /**
     * The node from where the counting starts.  This is needed to 
     * find a counter if the node being counted is not immediatly
     * found in the m_countNodes vector.
     */
    Node m_fromNode = null;
    
    /**
     * The owning xsl:number element.
     */
    ElemNumber m_numberElem;
      
    /**
     * Value to store result of last getCount call, for benifit
     * of returning val from CountersTable.getCounterByCounted, 
     * who calls getCount.
     */
    int m_countResult;
  
    /**
     * Construct a counter object.
     */
    Counter(ElemNumber numberElem, NodeSet countNodes)
      throws SAXException
    {
      m_countNodes = countNodes;
      m_numberElem = numberElem;
    }
  
    /**
     * Construct a counter object.
     */
    Counter(ElemNumber numberElem)
      throws SAXException
    {
      m_numberElem = numberElem;
    }
      
    /**
     * Try and find a node that was previously counted. If found, 
     * return a positive integer that corresponds to the count.
     * @param node The node to be counted.
     * @returns The count of the node, or -1 if not found.
     */
    int getPreviouslyCounted(XPathContext support, Node node)
    {
      int n = m_countNodes.size();
      m_countResult = 0;
      for(int i = n-1;i >= 0; i--)
      {
        Node countedNode = (Node)m_countNodes.elementAt(i);
        if(node.equals( countedNode ))
        {
          // Since the list is in backwards order, the count is 
          // how many are in the rest of the list.
          m_countResult = i+1+m_countNodesStartCount;
          break;
        }
        // Try to see if the given node falls after the counted node...
        // if it does, don't keep searching backwards.
        if(support.getDOMHelper().isNodeAfter(countedNode, node))
          break;
      }
      return m_countResult;
    }
      
    /**
     * Get the last node in the list.
     */
    Node getLast()
    {
      int size = m_countNodes.size();
      return (size > 0) ? m_countNodes.elementAt(size-1) : null;
    }
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/CountersTable.java
  
  Index: CountersTable.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import java.util.Hashtable;
  import java.util.Vector;
  import org.w3c.dom.Node;
  import org.xml.sax.SAXException;
  
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.templates.ElemNumber;
  
  /**
   * <meta name="usage" content="internal"/>
   * This is a table of counters, keyed by ElemNumber objects, each 
   * of which has a list of Counter objects.  This really isn't a true 
   * table, it is more like a list of lists (there must be a technical 
   * term for that...).
   */
  public class CountersTable extends Hashtable
  {  
    /**
     * Construct a CountersTable.
     */
    public CountersTable()
    {
    }
    
    /**
     * Get the list of counters that corresponds to 
     * the given ElemNumber object.
     */
    Vector getCounters(ElemNumber numberElem)
    {
      Vector counters = (Vector)this.get(numberElem);
      return (null == counters) ? putElemNumber(numberElem) : counters;
    }
    
    /**
     * Put a counter into the table and create an empty 
     * vector as it's value.
     */
    Vector putElemNumber(ElemNumber numberElem)
    {
      Vector counters = new Vector();
      this.put(numberElem, counters);
      return counters;
    }
    
    /**
     * Place to collect new counters.
     */
    private NodeSet m_newFound = new NodeSet();
    
    /**
     * Add a list of counted nodes that were built in backwards document 
     * order, or a list of counted nodes that are in forwards document 
     * order.
     */
    void appendBtoFList(NodeSet flist, NodeSet blist)
    {
      int n = blist.size();
      for(int i = (n-1); i >= 0; i--)
      {
        flist.addElement(blist.item(i));
      }
    }
    
    // For diagnostics
    int m_countersMade = 0;
      
    /**
     * Count forward until the given node is found, or until 
     * we have looked to the given amount.
     * @node The node to count.
     * @return The node count, or 0 if not found.
     */
    public int countNode(XPathContext support, ElemNumber numberElem, Node node)
      throws SAXException
    {
      int count = 0;
      Vector counters = getCounters(numberElem);
      int nCounters = counters.size();
      // XPath countMatchPattern = numberElem.getCountMatchPattern(support, 
node);
      // XPath fromMatchPattern = numberElem.m_fromMatchPattern;
      
      Node target = numberElem.getTargetNode(support, node);
      if(null != target)
      {
        for(int i = 0; i < nCounters; i++)
        {    
          Counter counter = (Counter)counters.elementAt(i);
          
          count = counter.getPreviouslyCounted(support, target);
          if(count > 0)
            return count;
        }
        
        // In the loop below, we collect the nodes in backwards doc order, so 
        // we don't have to do inserts, but then we store the nodes in forwards 
        // document order, so we don't have to insert nodes into that list, 
        // so that's what the appendBtoFList stuff is all about.  In cases 
        // of forward counting by one, this will mean a single node copy from 
        // the backwards list (m_newFound) to the forwards list 
(counter.m_countNodes).
        count = 0;
        for(; null != target; target = numberElem.getPreviousNode(support, 
target))
        {   
          // First time in, we should not have to check for previous counts, 
          // since the original target node was already checked in the 
          // block above.
          if(0 != count)  
          {
            for(int i = 0; i < nCounters; i++)
            {    
              Counter counter = (Counter)counters.elementAt(i);
              int cacheLen = counter.m_countNodes.size();
              if((cacheLen > 0) && 
counter.m_countNodes.elementAt(cacheLen-1).equals(target))
              {
                count += (cacheLen+counter.m_countNodesStartCount);
                if(cacheLen > 0)
                  appendBtoFList(counter.m_countNodes, m_newFound);
                m_newFound.removeAllElements();
                return count;
              }
            }
          }
          m_newFound.addElement(target);
          count++;
        }
        // If we got to this point, then we didn't find a counter, so make 
        // one and add it to the list.
        Counter counter = new Counter(numberElem);
        m_countersMade++; // for diagnostics
        appendBtoFList(counter.m_countNodes, m_newFound);
        m_newFound.removeAllElements();
        counters.addElement(counter);
      }
      
      return count;
    }
    
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/DecimalToRoman.java
  
  Index: DecimalToRoman.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  /**
   * <meta name="usage" content="internal"/>
   * Structure to help in converting integers to roman numerals
   * @see long2roman
   * @see m_romanConvertTable
   */
  public class DecimalToRoman 
  {      
    public DecimalToRoman(
                          long postValue, String postLetter, 
                          long preValue, String preLetter)
    {
      this.m_postValue = postValue;
      this.m_postLetter = postLetter;
      this.m_preValue = preValue;
      this.m_preLetter = preLetter;
    }
    
    public long  m_postValue;      
    public String m_postLetter;
    public long  m_preValue;      
    public String m_preLetter;
  }
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/KeyIterator.java
  
  Index: KeyIterator.java
  ===================================================================
  package org.apache.xalan.transformer;
  
  import java.util.Vector;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.utils.QName;
  
  import org.apache.xalan.templates.KeyDeclaration;
  
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.axes.DescendantOrSelfWalker;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XPath;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.traversal.NodeFilter;
  import org.w3c.dom.traversal.NodeIterator;
  
  import org.xml.sax.SAXException;
  
  public class KeyIterator extends LocPathIterator
  {
    private QName m_name;
    public QName getName() { return m_name; }
    
    private Vector m_keyDeclarations;
    public Vector getKeyDeclarations() { return m_keyDeclarations; }
    
    public KeyIterator(Node doc, 
                       PrefixResolver nscontext, 
                       QName name, 
                       Vector keyDeclarations, 
                       XPathContext xctxt)
    {
      super(xctxt, nscontext, doc);
      m_name = name;
      m_keyDeclarations = keyDeclarations;
      m_firstWalker = new KeyWalker(this);
      this.setLastUsedWalker(m_firstWalker);
    }
    
    public Node nextNode()
      throws DOMException
    {  
      // If the cache is on, and the node has already been found, then 
      // just return from the list.
      Node n = super.nextNode();
      // System.out.println("--> "+((null == n) ? "null" : n.getNodeName()));
      return n;
    }
  
    
    public void setLookupKey(String lookupKey)
    {
      // System.out.println("setLookupKey - lookupKey: "+lookupKey);
      ((KeyWalker)m_firstWalker).m_lookupKey = lookupKey;
      m_firstWalker.setRoot(getContext());
      this.setLastUsedWalker(m_firstWalker);
      m_next = 0;
    }  
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/KeyManager.java
  
  Index: KeyManager.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import java.util.Vector;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.LocPathIterator;
  
  /**
   * This class manages the key tables.
   */
  public class KeyManager
  {
    /**
     * Table of tables of element keys.
     * @see KeyTable.
     */
    private transient Vector m_key_tables = null;
    
    /**
     * Given a valid element key, return the corresponding node list.
     */
    public LocPathIterator getNodeSetByKey(XPathContext xctxt, 
                                    Node doc, QName name,
                                    String ref, PrefixResolver nscontext)
      throws org.xml.sax.SAXException
    {
      LocPathIterator nl = null;
      ElemTemplateElement template = (ElemTemplateElement)nscontext; // yuck -sb
  
      if(null != template.getStylesheetComposed().getKeysComposed())
      {
        boolean foundDoc = false;
        if(null == m_key_tables)
        {
          m_key_tables = new Vector(4);
        }
        else
        {
          int nKeyTables = m_key_tables.size();
          for(int i = 0; i < nKeyTables; i++)
          {
            KeyTable kt = (KeyTable)m_key_tables.elementAt(i);
            if(doc == kt.getDocKey())
            {
              nl = kt.getNodeSetByKey(name, ref);
              if (nl != null)
              {
                foundDoc = true;
                break;
              }
            }
          }
        }
        if((null == nl) && !foundDoc /* && m_needToBuildKeysTable */ )
        {
          KeyTable kt = new KeyTable(doc, nscontext, name, 
                                     
template.getStylesheetComposed().getKeysComposed(),
                                     xctxt);
          m_key_tables.addElement(kt);
          if(doc == kt.getDocKey())
          {
            foundDoc = true;
            nl = kt.getNodeSetByKey(name, ref);
          }
        }
      }
  
      return nl;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/KeyTable.java
  
  Index: KeyTable.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import org.w3c.dom.Element;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  import java.util.Hashtable;
  import java.util.Vector;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XPathContext; 
  import org.apache.xalan.xpath.XPathContext; 
  import org.apache.xalan.xpath.DOMHelper; 
  import org.apache.xalan.utils.QName; 
  import org.apache.xalan.templates.KeyDeclaration;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.utils.PrefixResolver;
  
  import org.apache.xalan.xpath.LocPathIterator; 
  
  // import org.apache.xalan.dtm.*;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Table of element keys, keyed by document node.  An instance of this 
   * class is keyed by a Document node that should be matched with the 
   * root of the current context.  It contains a table of name mappings 
   * to tables that contain mappings of identifier values to nodes.
   */
  public class KeyTable
  {
    /**
     * The document key.  This table should only be used with contexts
     * whose Document roots match this key.
     */
    private Node m_docKey;
    
    public Node getDocKey()
    {
      return m_docKey;
    }
    
    /**
     * Hashtable of keys.
     * The table is:
     * a) keyed by name,
     * b) with a value that is a KeyIterator.
     */
    private KeyIterator m_keyIter;
  
    /**
     * Build a keys table.
     * @param doc The owner document key (normally the same as startNode).
     * @param startNode The node to start itterating from to build the keys 
index.
     * @param nscontext The stylesheet's namespace context.
     * @param keyDeclarations The stylesheet's xsl:key declarations.
     * @param xmlLiaison The parser liaison for support of getNodeData(useNode).
     */
    public KeyTable(Node doc, PrefixResolver nscontext, 
                    QName name, Vector keyDeclarations, XPathContext xmlLiaison)
      throws org.xml.sax.SAXException
    {    
      m_docKey = doc;
      
      m_keyIter = new KeyIterator(doc, nscontext, 
                                  name, keyDeclarations, xmlLiaison);
      
    } // end buildKeysTable method
    
    
    /**
     * Given a valid element key, return the corresponding node list. 
     * @param The name of the key, which must match the 'name' attribute on 
xsl:key.
     * @param ref The value that must match the value found by the 'match' 
attribute on xsl:key.
     * @return If the name was not declared with xsl:key, this will return 
null, 
     * if the identifier is not found, it will return null, 
     * otherwise it will return a LocPathIterator instance.
     */
    public KeyIterator getNodeSetByKey(QName name, String ref)
    {
      KeyIterator ki;
      try
      {
        ki = (KeyIterator)m_keyIter.clone();
        ki.setLookupKey(ref);
      }
      catch(CloneNotSupportedException cnse)
      {
        ki = null;
      }
      
      return ki;
    }
  
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/KeyWalker.java
  
  Index: KeyWalker.java
  ===================================================================
  package org.apache.xalan.transformer;
  
  import java.util.Vector;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.utils.QName;
  
  import org.apache.xalan.templates.KeyDeclaration;
  
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.axes.DescendantOrSelfWalker;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XPath;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.traversal.NodeFilter;
  import org.w3c.dom.traversal.NodeIterator;
  
  import org.xml.sax.SAXException;
  
  public class KeyWalker extends DescendantOrSelfWalker
  {
    /**
     * Construct a KeyWalker using a LocPathIterator.
     */
    public KeyWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
    
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      m_attrs = null;
      m_foundAttrs = false;
      m_attrPos = 0;
      super.setRoot(root);
    }
    
    NamedNodeMap m_attrs;
    boolean m_foundAttrs;
    int m_attrPos;
    String m_lookupKey;
    
    /**
     * Get the next node in document order on the axes.
     */
    protected Node getNextNode()
    {
      if(!m_foundAttrs)
      {
        m_attrs = getCurrentNode().getAttributes();
        m_foundAttrs = true;
      }
      if(null != m_attrs)
      {
        if(m_attrPos < m_attrs.getLength())
        {
          return m_attrs.item(m_attrPos++);
        }
        else
        {
          m_attrs = null;
        }
      }
      
      Node next = super.getNextNode();
      if(null != next)
        m_foundAttrs = false;
      
      return next;
    }
  
    
    /**
     *  Test whether a specified node is visible in the logical view of a 
     * TreeWalker or NodeIterator. This function will be called by the 
     * implementation of TreeWalker and NodeIterator; it is not intended to 
     * be called directly from user code.
     * @param n  The node to check to see if it passes the filter or not.
     * @return  a constant to determine whether the node is accepted, 
     *   rejected, or skipped, as defined  above .
     */
    public short acceptNode(Node testNode)
    {
      KeyIterator ki = (KeyIterator)m_lpi;
      Vector keys = ki.getKeyDeclarations();
      QName name = ki.getName();
      try
      {
        String lookupKey = m_lookupKey;
        // System.out.println("lookupKey: "+lookupKey);
        int nDeclarations = keys.size();
  
        // Walk through each of the declarations made with xsl:key
        for(int i = 0; i < nDeclarations; i++)
        {
          KeyDeclaration kd = (KeyDeclaration)keys.elementAt(i);
          
          if(!kd.getName().equals(name)) 
            continue;
          
          // See if our node matches the given key declaration according to 
          // the match attribute on xsl:key.
          double score = kd.getMatch().getMatchScore(ki.getXPathContext(), 
testNode);
          
          if(score == kd.getMatch().MATCH_SCORE_NONE)
            continue;
  
          // Query from the node, according the the select pattern in the
          // use attribute in xsl:key.
          XObject xuse = kd.getUse().execute(ki.getXPathContext(), testNode, 
ki.getPrefixResolver());
  
          if(xuse.getType() != xuse.CLASS_NODESET)
          {
            String exprResult = xuse.str();
            if(lookupKey.equals(exprResult))
              return this.FILTER_ACCEPT;
          }
          else
          {
            NodeIterator nl = xuse.nodeset();
            Node useNode;
            while(null != (useNode = nl.nextNode()))
            {
              String exprResult = m_lpi.getDOMHelper().getNodeData(useNode);
              if((null != exprResult) && lookupKey.equals(exprResult))
                return this.FILTER_ACCEPT;
            }
          }
  
        } // end for(int i = 0; i < nDeclarations; i++)
  
      }
      catch(SAXException se)
      {
        // TODO: What to do?
      }
      return this.FILTER_REJECT;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/MsgMgr.java
  
  Index: MsgMgr.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import org.apache.xalan.res.XSLMessages;
  import org.xml.sax.SAXException;
  import org.xml.sax.Locator;
  import org.xml.sax.ErrorHandler;
  import org.w3c.dom.Node;
  import trax.TransformException;
  
  /**
   * This class will manage error messages, warning messages, and other types 
of 
   * message events.
   */
  public class MsgMgr
  {  
    /**
     * Create a message manager object.
     */
    public MsgMgr(TransformerImpl transformer)
    {
      m_transformer = transformer;
    }
    
    private TransformerImpl m_transformer;
    private static XSLMessages m_XSLMessages = new XSLMessages();
  
    /**
     * Warn the user of an problem.
     * This is public for access by extensions.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void message(String msg, boolean terminate)
      throws SAXException
    {
      ErrorHandler errHandler = m_transformer.getErrorHandler();
      if(null != errHandler)
      {
        if(terminate)
          errHandler.fatalError(new TransformException(msg));
        else
          errHandler.warning(new TransformException(msg));
      }
      else
      {
        if(terminate)
          throw new TransformException(msg);
        else
          System.out.println(msg);
      }
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Warn the user of an problem.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void warn(int msg)
      throws SAXException
    {
      warn(null, null, msg, null);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Warn the user of an problem.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void warn(int msg, Object[] args)
      throws SAXException
    {
      warn(null, null, msg, args);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Warn the user of an problem.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void warn(Node styleNode, Node sourceNode, int msg)
      throws SAXException
    {
      warn(styleNode, sourceNode, msg, null);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Warn the user of an problem.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void warn(Node styleNode, Node sourceNode, int msg, Object args[])
      throws SAXException
    {
      String formattedMsg = m_XSLMessages.createWarning(msg, args);
      
      ErrorHandler errHandler = m_transformer.getErrorHandler();
      if(null != errHandler)
        errHandler.warning(new TransformException(formattedMsg));
      else
        System.out.println(formattedMsg);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void error(String msg)
      throws SAXException
    {
      // Locator locator = m_stylesheetLocatorStack.isEmpty()
      //                  ? null :
      //                    ((Locator)m_stylesheetLocatorStack.peek());
      Locator locator = null;
      ErrorHandler errHandler = m_transformer.getErrorHandler();
      if(null != errHandler)
        errHandler.fatalError(new TransformException(msg));
      else
        throw new TransformException(msg);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void error(int msg)
      throws SAXException
    {
      error(null, null, msg, null);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void error(int msg, Object[] args)
      throws SAXException
    {
      error(null, null, msg, args);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void error(int msg, Exception e)
      throws SAXException
    {
      error(msg, null, e);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void error(int msg, Object args[], Exception e)
      throws SAXException
    {
      //msg  = (null == msg) ? XSLTErrorResources.ER_PROCESSOR_ERROR : msg;
      String formattedMsg = m_XSLMessages.createMessage(msg, args);
      // Locator locator = m_stylesheetLocatorStack.isEmpty()
      //                   ? null :
      //                    ((Locator)m_stylesheetLocatorStack.peek());
      Locator locator = null;
      ErrorHandler errHandler = m_transformer.getErrorHandler();
      if(null != errHandler)
        errHandler.fatalError(new TransformException(formattedMsg));
      else
        throw new TransformException(formattedMsg);
    }
  
    /**
      * <meta name="usage" content="internal"/>
    * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void error(Node styleNode, Node sourceNode, int msg)
      throws SAXException
    {
      error(styleNode, sourceNode, msg, null);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Tell the user of an error, and probably throw an
     * exception.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    public void error(Node styleNode, Node sourceNode, int msg, Object args[])
      throws SAXException
    {
      String formattedMsg = m_XSLMessages.createMessage(msg, args);
      // Locator locator = m_stylesheetLocatorStack.isEmpty()
      //                   ? null :
      //                    ((Locator)m_stylesheetLocatorStack.peek());
      Locator locator = null;
      ErrorHandler errHandler = m_transformer.getErrorHandler();
      if(null != errHandler)
        errHandler.warning(new TransformException(formattedMsg));
      else
        throw new TransformException(formattedMsg);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/NodeSortKey.java
  
  Index: NodeSortKey.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import java.util.Locale;
  import org.apache.xalan.xpath.XPath;
  import java.text.Collator;
  import org.apache.xalan.res.XSLTErrorResources;
  
  
  /**
   * <meta name="usage" content="internal"/>
   * Data structure for use by the NodeSorter class.
   */
  class NodeSortKey
  {
    XPath m_selectPat;
    boolean m_treatAsNumbers;
    boolean m_descending;
    boolean m_caseOrderUpper;
    Collator m_col;
    Locale m_locale;
    org.apache.xalan.utils.PrefixResolver m_namespaceContext;
    TransformerImpl m_processor; // needed for error reporting.
  
    NodeSortKey(TransformerImpl transformer, XPath selectPat,
                     boolean treatAsNumbers,
                     boolean descending, String langValue,
                                           boolean caseOrderUpper,
                     org.apache.xalan.utils.PrefixResolver namespaceContext)
      throws org.xml.sax.SAXException
    {
      m_processor = transformer;
      m_namespaceContext = namespaceContext;
      m_selectPat = selectPat;
      m_treatAsNumbers = treatAsNumbers;
      m_descending = descending;
          m_caseOrderUpper = caseOrderUpper;
      if(null != langValue && m_treatAsNumbers == false)
      {
        m_locale = new Locale(langValue.toUpperCase(),
                              Locale.getDefault().getDisplayCountry());
        if(null == m_locale)
        {
          // m_processor.warn("Could not find locale for <sort 
xml:lang="+langValue);
          m_locale = Locale.getDefault();
        }
      }
      else
      {
        m_locale = Locale.getDefault();
      }
  
      m_col = Collator.getInstance(m_locale);
      if(null == m_col)
      {
        m_processor.getMsgMgr().warn(
          XSLTErrorResources.WG_CANNOT_FIND_COLLATOR, new Object[] 
{langValue}); //"Could not find Collator for <sort xml:lang="+langValue);
        m_col = Collator.getInstance();
      }
    }
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/NodeSorter.java
  
  Index: NodeSorter.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import java.util.Vector;
  import java.text.NumberFormat;
  import java.text.CollationKey;
  import org.w3c.dom.Node;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.utils.NodeVector;
  import org.xml.sax.SAXException;
  
  /**
   * <meta name="usage" content="internal"/>
   * This class can sort vectors of DOM nodes according to a select pattern.
   */
  class NodeSorter
  {
    XPathContext m_execContext;
    
    Vector m_keys; // vector of NodeSortKeys
    
    /**
     * TODO: Adjust this for locale.
     */
    NumberFormat m_formatter = NumberFormat.getNumberInstance();   
    
    /**
     * Construct a NodeSorter, passing in the XSL Processor 
     * so it can know how to get the node data according to 
     * the proper whitespace rules.
     */
    public NodeSorter(XPathContext p)
    {
      m_execContext = p;
    }
    
    /**
     * Given a vector of nodes, sort each node according to 
     * the criteria in the keys.
     * @param v an vector of Nodes.
     * @param keys a vector of NodeSortKeys.
     */
    public void sort(NodeVector v, Vector keys, XPathContext support) 
      throws org.xml.sax.SAXException
   {    
      m_keys = keys;
      // QuickSort2(v, 0, v.size() - 1 );
      int n = v.size();
      
      // Create a vector of node compare elements
      // based on the input vector of nodes
      Vector nodes = new Vector();
      for (int i = 0; i<n; i++) 
      {
        NodeCompareElem elem = new NodeCompareElem((Node)v.elementAt(i)); 
        nodes.addElement(elem);
      }
      Vector scratchVector = new Vector();
      mergesort(nodes, scratchVector, 0, n - 1, support);
      
      // return sorted vector of nodes
      for (int i = 0; i<n; i++) 
      {
        v.setElementAt(((NodeCompareElem)nodes.elementAt(i)).m_node, i);
      }
      // old code...
      //NodeVector scratchVector = new NodeVector(n);
      //mergesort(v, scratchVector, 0, n - 1, support);
    }
    
    /**
     * Return the results of a compare of two nodes.
     * TODO: Optimize compare -- cache the getStringExpr results, key by 
m_selectPat + hash of node.
     */
    int compare(NodeCompareElem n1, NodeCompareElem n2, int kIndex, 
XPathContext support)
      throws SAXException
    {
      int result = 0;
     
      NodeSortKey k = (NodeSortKey)m_keys.elementAt(kIndex); 
      if(k.m_treatAsNumbers)
      {
                  double n1Num, n2Num;
            if (kIndex ==0)
        { 
          n1Num = ((Double)n1.m_key1Value).doubleValue();
          n2Num = ((Double)n2.m_key1Value).doubleValue();
        }
            else if (kIndex ==1)
        { 
          n1Num = ((Double)n1.m_key2Value).doubleValue();
          n2Num = ((Double)n2.m_key2Value).doubleValue();
        }
        /* Leave this in case we decide to use an array later 
        if (kIndex < maxkey)
        { 
        double n1Num = (double)n1.m_keyValue[kIndex];
        double n2Num = (double)n2.m_keyValue[kIndex];
        }*/
        else
        {
          // Get values dynamically
          XObject r1 = k.m_selectPat.execute(m_execContext, n1.m_node, 
k.m_namespaceContext);
          XObject r2 = k.m_selectPat.execute(m_execContext, n2.m_node, 
k.m_namespaceContext);
      
          double d = r1.num();
          // Can't use NaN for compare. They are never equal. Use zero instead.
          // That way we can keep elements in document order. 
          n1Num = Double.isNaN(d)? 0.0 : d;
          d = r2.num();
          n2Num = Double.isNaN(d)? 0.0 : d;
        } 
        
        if((n1Num == n2Num) && ((kIndex+1) < m_keys.size()))
        {
          result = compare(n1, n2, kIndex+1, support);
        }
        else
        {
          double diff = n1Num - n2Num;
          // process order parameter 
          result = (int)((diff < 0.0) 
                         ? (k.m_descending ? 1 : -1) 
                           : (diff > 0.0) ? (k.m_descending ? -1 : 1)
                                            : 0);
        }
      }// end treat as numbers 
      else
      {
                  CollationKey n1String, n2String;
            if (kIndex == 0)
        {
          n1String = (CollationKey)n1.m_key1Value;
          n2String = (CollationKey)n2.m_key1Value;
        }
            else if (kIndex == 1)
        {
          n1String = (CollationKey)n1.m_key2Value;
          n2String = (CollationKey)n2.m_key2Value;
        }       
        /* Leave this in case we decide to use an array later
        if (kIndex < maxkey)
        {
          String n1String = (String)n1.m_keyValue[kIndex];
          String n2String = (String)n2.m_keyValue[kIndex];
        }*/
        else
        {
          // Get values dynamically
          XObject r1 = k.m_selectPat.execute(m_execContext, n1.m_node, 
k.m_namespaceContext);
          XObject r2 = k.m_selectPat.execute(m_execContext, n2.m_node, 
k.m_namespaceContext);
      
          n1String = k.m_col.getCollationKey(r1.str());
          n2String = k.m_col.getCollationKey(r2.str());
        }
      
        // Use collation keys for faster compare, but note that whitespaces 
        // etc... are treated differently from if we were comparing Strings.
        result = n1String.compareTo(n2String);
              
        //Process caseOrder parameter
        if (k.m_caseOrderUpper)
            {
              String tempN1 = n1String.getSourceString().toLowerCase();
                    String tempN2 = n2String.getSourceString().toLowerCase();
                    if (tempN1.equals(tempN2))
                    {
                      //java defaults to upper case is greater.
                      result = result == 0 ? 0 : -result;       
                    }   
            }
        
        //Process order parameter
        if(k.m_descending)
        {
          result = -result;
        }
      }//end else
        
      if(0 == result)
      {
        if((kIndex+1) < m_keys.size())
        {
          result = compare(n1, n2, kIndex+1, support);
        }
      }
      if(0 == result)
      {
        // I shouldn't have to do this except that there seems to 
        // be a glitch in the mergesort
        
        // if(r1.getType() == r1.CLASS_NODESET)
        // {
          result = support.getDOMHelper().isNodeAfter(n1.m_node, n2.m_node) ? 
-1 : 1;
        // }
      }
      return result;
    }
    
    /**
     * This implements a standard Mergesort, as described in 
     * Robert Sedgewick's Algorithms book.  This is a better 
     * sort for our purpose than the Quicksort because it 
     * maintains the original document order of the input if 
     * the order isn't changed by the sort.
     */
    void mergesort(Vector a, Vector b, int l, int r, XPathContext support)
      throws SAXException
    {
      if((r-l)>0)
      {
        int m = (r+l) / 2;
        mergesort(a, b, l, m, support);
        mergesort(a, b, m+1, r, support);
        int i, j, k;
        for(i = m; i >= l; i--)
        {
          // b[i] = a[i];
          // Use insert if we need to increment vector size.
          if (i >= b.size())
            b.insertElementAt(a.elementAt(i), i);
          else
            b.setElementAt(a.elementAt(i), i);
        }
        i=l;
        for(j = (m + 1); j <= r; j++)
        {
          // b[r+m+1-j] = a[j];
          if (r+m+1-j>= b.size())
            b.insertElementAt(a.elementAt(j), r+m+1-j);
          else
            b.setElementAt(a.elementAt(j), r+m+1-j);
        }
        j=r;
        int compVal;
        for(k = l; k <= r; k++)
        {
          // if(b[i] < b[j])
          if (i == j)
            compVal = -1;
          else
            compVal = compare((NodeCompareElem)b.elementAt(i), 
(NodeCompareElem)b.elementAt(j), 0, support);
          
          if(compVal < 0)
          {
            // a[k]=b[i];
            a.setElementAt(b.elementAt(i), k);
            i++;          
          }
          else if(compVal > 0)
          {
            // a[k]=b[j]; 
            a.setElementAt(b.elementAt(j), k);
            j--;          
          }  
        }
      }
    }
    
    /** This is a generic version of C.A.R Hoare's Quick Sort 
     * algorithm.  This will handle arrays that are already
     * sorted, and arrays with duplicate keys.<BR>
     *
     * If you think of a one dimensional array as going from
     * the lowest index on the left to the highest index on the right
     * then the parameters to this function are lowest index or
     * left and highest index or right.  The first time you call
     * this function it will be with the parameters 0, a.length - 1.
     *
     * @param a       an integer array
     * @param lo0     left boundary of array partition
     * @param hi0     right boundary of array partition
     */
  /*  private void QuickSort2(Vector v, int lo0, int hi0, XPathContext support)
      throws org.xml.sax.SAXException,
             java.net.MalformedURLException, 
             java.io.FileNotFoundException, 
             java.io.IOException
    {
      int lo = lo0;
      int hi = hi0;
  
      if ( hi0 > lo0)
      {
        // Arbitrarily establishing partition element as the midpoint of
        // the array.
        Node midNode = (Node)v.elementAt( ( lo0 + hi0 ) / 2 );
  
        // loop through the array until indices cross
        while( lo <= hi )
        {
          // find the first element that is greater than or equal to 
          // the partition element starting from the left Index.
          while( (lo < hi0) && (compare((Node)v.elementAt(lo), midNode, 0, 
support) < 0) )
          {
            ++lo;
          } // end while
  
          // find an element that is smaller than or equal to 
          // the partition element starting from the right Index.
          while( (hi > lo0) && (compare((Node)v.elementAt(hi), midNode, 0, 
support) > 0) )
          {
            --hi;
          }
  
          // if the indexes have not crossed, swap
          if( lo <= hi ) 
          {
            swap(v, lo, hi);
            ++lo;
            --hi;
          }
        }
  
        // If the right index has not reached the left side of array
        // must now sort the left partition.
        if( lo0 < hi )
        {
          QuickSort2( v, lo0, hi, support );
        }
  
        // If the left index has not reached the right side of array
        // must now sort the right partition.
        if( lo < hi0 )
        {
          QuickSort2( v, lo, hi0, support );
        }
      }
    } // end QuickSort2  */
  
    /**
     * Simple function to swap two elements in 
     * a vector.
     */
    private void swap(Vector v, int i, int j)
    {
      Node node = (Node)v.elementAt(i); 
      v.setElementAt(v.elementAt(j), i);
      v.setElementAt(node, j);
    }
    
    class NodeCompareElem
    {
      Node m_node;
      // This maxkey value was chosen arbitrarily. We are assuming that the    
      // maxkey + 1 keys will only hit fairly rarely and therefore, we
      // will get the node values for those keys dynamically.
      int maxkey = 2;
      // Keep this in case we decide to use an array. Right now
      // using two variables is cheaper.
      //Object[] m_KeyValue = new Object[2];
          Object m_key1Value;
          Object m_key2Value;
      
      NodeCompareElem(Node node) throws org.xml.sax.SAXException
      {
        m_node = node;
        if (!m_keys.isEmpty())
        { 
                    NodeSortKey k1 = (NodeSortKey)m_keys.elementAt(0);
          XObject r = k1.m_selectPat.execute(m_execContext, node, 
k1.m_namespaceContext);
          double d ;
          if(k1.m_treatAsNumbers)
          {  
            d = r.num();
            // Can't use NaN for compare. They are never equal. Use zero 
instead.  
            m_key1Value = new Double(Double.isNaN(d)? 0.0 : d);
          }  
          else
            m_key1Value = k1.m_col.getCollationKey(r.str());
                  
                    if (m_keys.size()>1)
                    {
                            NodeSortKey k2 = (NodeSortKey)m_keys.elementAt(1);
            XObject r2 = k2.m_selectPat.execute(m_execContext, node, 
k2.m_namespaceContext);
            if(k2.m_treatAsNumbers)
            {
              d = r2.num();
              m_key2Value = new Double(Double.isNaN(d)? 0.0 : d);
            }  
            else
              m_key2Value = k2.m_col.getCollationKey(r2.str());  
                    }     
          /* Leave this in case we decide to use an array later
          while (kIndex <= m_keys.size() && kIndex < maxkey)
          {  
            NodeSortKey k = (NodeSortKey)m_keys.elementAt(kIndex);
            XObject r = k.m_selectPat.execute(m_execContext, node, 
k.m_namespaceContext);
            if(k.m_treatAsNumbers)    
              m_KeyValue[kIndex] = r.num();
            else
              m_KeyValue[kIndex] = r.str();
          } */
                  
        } // end if not empty    
      }  
    } // end NodeCompareElem class
  
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/NumeratorFormatter.java
  
  Index: NumeratorFormatter.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  package org.apache.xalan.transformer;
  
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  import java.util.Locale;
  import java.util.NoSuchElementException;
  
  /**
   * <meta name="usage" content="internal"/>
   * Converts enumerated numbers into strings, using the XSL conversion 
attributes.
   * Having this in a class helps avoid being forced to extract the attributes 
repeatedly.
   */
  class NumeratorFormatter
  {
    protected Element m_xslNumberElement;
    NumberFormatStringTokenizer m_formatTokenizer;
    Locale m_locale;
    java.text.NumberFormat m_formatter;
    TransformerImpl m_processor;
  
    /**
     * Table to help in converting decimals to roman numerals.
     * @see TransformerImpl#DecimalToRoman
     * @see TransformerImpl#long2roman
     */
    private final static DecimalToRoman m_romanConvertTable[] =
    {
      new DecimalToRoman(1000, "M", 900, "CM"),
      new DecimalToRoman(500, "D", 400, "CD"),
      new DecimalToRoman(100L, "C", 90L, "XC"),
      new DecimalToRoman(50L, "L", 40L, "XL"),
      new DecimalToRoman(10L, "X", 9L, "IX"),
      new DecimalToRoman(5L, "V", 4L, "IV"),
      new DecimalToRoman(1L, "I", 1L, "I")
    };
  
    /**
     * Chars for converting integers into alpha counts.
     * @see TransformerImpl#int2alphaCount
     */
    private final static char[] m_alphaCountTable =
    {
      'Z', // z for zero
    'A' , 'B' , 'C' , 'D' , 'E' , 'F' ,
      'G' , 'H' , 'I' , 'J' , 'K' , 'L' ,
      'M' , 'N' , 'O' , 'P' , 'Q' , 'R' ,
      'S' , 'T' , 'U' , 'V' , 'W' , 'X' ,
      'Y'
    };
  
    /**
     * Construct a NumeratorFormatter using an element
     * that contains XSL number conversion attributes -
     * format, letter-value, xml:lang, digit-group-sep,
     * n-digits-per-group, and sequence-src.
     */
    NumeratorFormatter(Element xslNumberElement, TransformerImpl processor)
    {
      m_xslNumberElement = xslNumberElement;
      m_processor = processor;
  
    } // end NumeratorFormatter(Element) constructor
  
    /**
     * Convert a long integer into alphabetic counting, in other words
     * count using the sequence A B C ... Z AA AB AC.... etc.
     * @param val Value to convert -- must be greater than zero.
     * @param table a table containing one character for each digit in the radix
     * @return String representing alpha count of number.
     * @see TransformerImpl#DecimalToRoman
     *
     * Note that the radix of the conversion is inferred from the size
     * of the table.
     */
    protected String int2alphaCount(int val, char [] table)
    {
  
      int radix = table.length;
  
      // Create a buffer to hold the result
      // TODO:  size of the table can be detereined by computing
      // logs of the radix.  For now, we fake it.
      char buf[] = new char[100];
  
      // next character to set in the buffer
      int charPos = buf.length -1 ;    // work backward through buf[]
  
      // index in table of the last character that we stored
      int lookupIndex = 1;  // start off with anything other than zero to make 
correction work
  
      //                                                Correction number
      //
      //        Correction can take on exactly two values:
      //
      //                0       if the next character is to be emitted is usual
      //
      //      radix - 1
      //                        if the next char to be emitted should be one 
less than
      //                        you would expect
      //
      // For example, consider radix 10, where 1="A" and 10="J"
      //
      // In this scheme, we count: A, B, C ...   H, I, J (not A0 and certainly
      // not AJ), A1
      //
      // So, how do we keep from emitting AJ for 10?  After correctly emitting 
the
      // J, lookupIndex is zero.  We now compute a correction number of 9 
(radix-1).
      // In the following line, we'll compute (val+correction) % radix, which 
is,
      // (val+9)/10.  By this time, val is 1, so we compute (1+9) % 10, which
      // is 10 % 10 or zero.  So, we'll prepare to emit "JJ", but then we'll
      // later suppress the leading J as representing zero (in the mod system,
      // it can represent either 10 or zero).  In summary, the correction value 
of
      // "radix-1" acts like "-1" when run through the mod operator, but with 
the
      // desireable characteristic that it never produces a negative number.
  
      int correction = 0;
  
      // TODO:  throw error on out of range input
  
      do
      {
        // most of the correction calculation is explained above,  the reason 
for the
        // term after the "|| " is that it correctly propagates carries across
        // multiple columns.
        correction = ((lookupIndex == 0) ||
                      (correction != 0 && lookupIndex == radix-1 )) ? (radix-1) 
: 0;
  
        // index in "table" of the next char to emit
        lookupIndex  = (val+correction) % radix;
  
        // shift input by one "column"
        val = (val / radix);
  
        // if the next value we'd put out would be a leading zero, we're done.
        if (lookupIndex == 0 && val == 0)
          break;
  
        // put out the next character of output
        buf[charPos--] = table[lookupIndex];
      }
        while (val > 0);
  
      return new String(buf, charPos+1, (buf.length - charPos -1));
    }
  
    /**
     * Convert a long integer into roman numerals.
     * @param val Value to convert.
     * @param prefixesAreOK true_ to enable prefix notation (e.g. 4 = "IV"),
     * false_ to disable prefix notation (e.g. 4 = "IIII").
     * @return Roman numeral string.
     * @see DecimalToRoman
     * @see m_romanConvertTable
     */
    String long2roman(long val, boolean prefixesAreOK)
    {
      if(val <= 0)
      {
        return "#E("+val+")";
      }
  
      String roman = "";
      int place = 0;
      if (val <= 3999L)
      {
        do
        {
          while (val >= m_romanConvertTable[place].m_postValue)
          {
            roman += m_romanConvertTable[place].m_postLetter;
            val -= m_romanConvertTable[place].m_postValue;
          }
          if (prefixesAreOK)
          {
            if (val >= m_romanConvertTable[place].m_preValue)
            {
              roman += m_romanConvertTable[place].m_preLetter;
              val -= m_romanConvertTable[place].m_preValue;
            }
          }
          place++;
        }
          while (val > 0);
      }
      else
      {
        roman = "#error";
      }
      return roman;
    } // end long2roman
  
    /**
     * This class returns tokens using non-alphanumberic
     * characters as delimiters.
     */
    class NumberFormatStringTokenizer
    {
      private int currentPosition;
      private int maxPosition;
      private String str;
  
    /**
       * Construct a NumberFormatStringTokenizer.
       */
      NumberFormatStringTokenizer(String str) 
    {
        this.str = str;
        maxPosition = str.length();
      }
    
    /**
       * Reset tokenizer so that nextToken() starts from the beginning.
       */
    void reset()
    {
      currentPosition = 0;
      }
  
    /**
       * Returns the next token from this string tokenizer.
       *
       * @return     the next token from this string tokenizer.
       * @exception  NoSuchElementException  if there are no more tokens in this
       *               tokenizer's string.
       */
      String nextToken()
      {
        if (currentPosition >= maxPosition)
        {
          throw new NoSuchElementException();
        }
  
        int start = currentPosition;
        while ((currentPosition < maxPosition) &&
               Character.isLetterOrDigit(str.charAt(currentPosition)))
        {
          currentPosition++;
        }
        if ((start == currentPosition) &&
            (!Character.isLetterOrDigit(str.charAt(currentPosition))))
        {
          currentPosition++;
        }
        return str.substring(start, currentPosition);
      }
      
    /**
       * Tells if <code>nextToken</code> will throw an exception 
     * if it is called.
       *
       * @return true if <code>nextToken</code> can be called 
     * without throwing an exception.
       */
      boolean hasMoreTokens()
      {
        return (currentPosition >= maxPosition) ? false : true;
      }
      
    /**
       * Calculates the number of times that this tokenizer's
       * <code>nextToken</code> method can be called before it generates an
       * exception.
       *
       * @return  the number of tokens remaining in the string using the current
       *          delimiter set.
       * @see     java.util.StringTokenizer#nextToken()
       */
      int countTokens()
      {
        int count = 0;
        int currpos = currentPosition;
  
        while (currpos < maxPosition)
        {
          int start = currpos;
          while ((currpos < maxPosition) &&
                 Character.isLetterOrDigit(str.charAt(currpos)))
          {
            currpos++;
          }
          if ((start == currpos) &&
              (Character.isLetterOrDigit(str.charAt(currpos)) == false))
          {
            currpos++;
          }
          count++;
        }
        return count;
      }
    } // end NumberFormatStringTokenizer
  
  }
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/ResultNameSpace.java
  
  Index: ResultNameSpace.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  /**
   * <meta name="usage" content="internal"/>
   * A representation of a result namespace.  One of these will
   * be pushed on the result tree namespace stack for each
   * result tree element.
   */
  public class ResultNameSpace
  {
    public ResultNameSpace m_next = null;
    public String m_prefix;
    public String m_uri; // if null, then Element namespace is empty.
  
    /**
     * Construct a namespace for placement on the
     * result tree namespace stack.
     */
    public ResultNameSpace(String prefix, String uri)
    {
      m_prefix = prefix;
      m_uri = uri;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/ResultTreeFrag.java
  
  Index: ResultTreeFrag.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import org.w3c.dom.Document;
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.DOMException;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.res.XSLMessages;
  
  /**
   * <meta name="usage" content="internal"/>
   * Container of a result tree fragment.
   */
  public class ResultTreeFrag implements DocumentFragment
  {
    Document m_docFactory;
    NodeSet m_children;
    XPathContext m_xsupport;
  
    public ResultTreeFrag(Document docFactory, XPathContext support)
    {
      m_xsupport = support;
      m_docFactory = docFactory;
      m_children = new NodeSet();
    }
  
    public ResultTreeFrag(Document docFactory, NodeSet children,
                          XPathContext support)
    {
      m_xsupport = support;
      m_docFactory = docFactory;
      m_children = children;
    }
  
    /**
     * Throw an error.
     */
    void error(int msg)
    {
                   throw new RuntimeException(XSLMessages.createMessage(msg, 
null));
    }
  
    /**
     * The name of this node, depending on its type; see the table above.
     */
    public final String getNodeName()
    {
      return "#document-fragment";
    }
  
    /**
     * The value of this node, depending on its type; see the table above.
     * @exception DOMException
     *   NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
     * @exception DOMException
     *   DOMSTRING_SIZE_ERR: Raised when it would return more characters than
     *   fit in a <code>DOMString</code> variable on the implementation
     *   platform.
     */
      public String             getNodeValue()
        throws DOMException
      {
        return "";
      }
  
      /**
       * DocumentFragments never have a nodeValue.
       * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR)
       */
      public void setNodeValue(String x)
        throws DOMException
      {
        // No action.
      }
  
    /**
     * A code representing the type of the underlying object, as defined above.
     */
    public final short getNodeType()
    {
      return Node.DOCUMENT_FRAGMENT_NODE;
    }
  
    /**
     * The parent of this node. All nodes, except <code>Document</code>,
     * <code>DocumentFragment</code>, and <code>Attr</code> may have a parent.
     * However, if a node has just been created and not yet added to the tree,
     * or if it has been removed from the tree, this is <code>null</code>.
     */
    public Node               getParentNode()
    {
      return null;
    }
  
    /**
     * A <code>NodeList</code> that contains all children of this node. If there
     * are no children, this is a <code>NodeList</code> containing no nodes.
     * The content of the returned <code>NodeList</code> is "live" in the sense
     * that, for instance, changes to the children of the node object that
     * it       was created from are immediately reflected in the nodes 
returned by
     * the <code>NodeList</code> accessors; it is not a static snapshot of the
     * content of the node. This is true for every <code>NodeList</code>,
     * including the ones returned by the <code>getElementsByTagName</code>
     * method.
     */
    public NodeList           getChildNodes()
    {
      return m_children;
    }
  
    /**
     * The first child of this node. If there is no such node, this returns
     * <code>null</code>.
     */
    public Node               getFirstChild()
    {
      int nChildren = m_children.getLength();
      return (nChildren > 0) ? m_children.item(0) : null;
    }
  
    /**
     * The last child of this node. If there is no such node, this returns
     * <code>null</code>.
     */
    public Node               getLastChild()
    {
      int nChildren = m_children.getLength();
      return (nChildren > 0) ? m_children.item(nChildren-1) : null;
    }
  
    /**
     * The node immediately preceding this node. If there is no such node, this
     * returns <code>null</code>.
     */
    public Node               getPreviousSibling()
    {
      return null;
    }
  
    /**
     * The node immediately following this node. If there is no such node, this
     * returns <code>null</code>.
     */
    public Node               getNextSibling()
    {
      return null;
    }
  
    /**
     * A <code>NamedNodeMap</code> containing the attributes of this node (if it
     * is an <code>Element</code>) or <code>null</code> otherwise.
     */
    public NamedNodeMap       getAttributes()
    {
      return null;
    }
  
    /**
     * The <code>Document</code> object associated with this node. This is also
     * the <code>Document</code> object used to create new nodes. When this
     * node is a <code>Document</code> this is <code>null</code>.
     */
    public Document getOwnerDocument()
    {
      return m_docFactory;
    }
  
    /**
     * Inserts the node <code>newChild</code> before the existing child node
     * <code>refChild</code>. If <code>refChild</code> is <code>null</code>,
     * insert <code>newChild</code> at the end of the list of children.
     * <br>If <code>newChild</code> is a <code>DocumentFragment</code> object,
     * all of its children are inserted, in the same order, before
     * <code>refChild</code>. If the <code>newChild</code> is already in the
     * tree, it is first removed.
     * @param newChild The node to insert.
     * @param refChild The reference node, i.e., the node before which the new
     *   node must be inserted.
     * @return The node being inserted.
     * @exception DOMException
     *   HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not
     *   allow children of the type of the <code>newChild</code> node, or if
     *   the node to insert is one of this node's ancestors.
     *   <br>WRONG_DOCUMENT_ERR: Raised if <code>newChild</code> was created
     *   from a different document than the one that created this node.
     *   <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
     *   <br>NOT_FOUND_ERR: Raised if <code>refChild</code> is not a child of
     *   this node.
     */
    public Node insertBefore(Node newChild,
                             Node refChild)
      throws DOMException
    {
      // NodeSet mnl = (NodeSet)m_children;
      // int refIndex = (null == refChild)
      //               ? mnl.getLength() : mnl.indexOf(refChild);
      return newChild;
    }
  
    /**
     * Replaces the child node <code>oldChild</code> with <code>newChild</code>
     * in the list of children, and returns the <code>oldChild</code> node. If
     * the <code>newChild</code> is already in the tree, it is first removed.
     * @param newChild The new node to put in the child list.
     * @param oldChild The node being replaced in the list.
     * @return The node replaced.
     * @exception DOMException
     *   HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not
     *   allow children of the type of the <code>newChild</code> node, or it
     *   the node to put in is one of this node's ancestors.
     *   <br>WRONG_DOCUMENT_ERR: Raised if <code>newChild</code> was created
     *   from a different document than the one that created this node.
     *   <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
     *   <br>NOT_FOUND_ERR: Raised if <code>oldChild</code> is not a child of
     *   this node.
     */
    public Node               replaceChild(Node newChild,
                                           Node oldChild)
      throws DOMException
    {
      NodeSet mnl = (NodeSet)m_children;
      int newChildIndex = mnl.indexOf(newChild);
      if(newChildIndex > -1)
      {
        mnl.removeElementAt(newChildIndex);
      }
      else
      {
        // throw exception.
      }
      int refIndex = (null == oldChild)
                     ? -1 : mnl.indexOf(oldChild);
      if(refIndex > -1)
      {
        mnl.removeElement(oldChild);
        mnl.setElementAt(newChild, refIndex);
      }
      else
      {
        // Throw exception.
      }
      return oldChild;
    }
  
    /**
     * Removes the child node indicated by <code>oldChild</code> from the list
     * of children, and returns it.
     * @param oldChild The node being removed.
     * @return The node removed.
     * @exception DOMException
     *   NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
     *   <br>NOT_FOUND_ERR: Raised if <code>oldChild</code> is not a child of
     *   this node.
     */
    public Node removeChild(Node oldChild)
      throws DOMException
    {
      NodeSet mnl = (NodeSet)m_children;
      mnl.removeElement(oldChild);
      return oldChild;
    }
  
    /**
     * Adds the node <code>newChild</code> to the end of the list of children of
     * this node. If the <code>newChild</code> is already in the tree, it is
     * first removed.
     * @param newChild The node to add.If it is a  <code>DocumentFragment</code>
     *   object, the entire contents of the document fragment are moved into
     *   the child list of this node
     * @return The node added.
     * @exception DOMException
     *   HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not
     *   allow children of the type of the <code>newChild</code> node, or if
     *   the node to append is one of this node's ancestors.
     *   <br>WRONG_DOCUMENT_ERR: Raised if <code>newChild</code> was created
     *   from a different document than the one that created this node.
     *   <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
     */
    public Node appendChild(Node newChild)
      throws DOMException
    {
      NodeSet mnl = (NodeSet)m_children;
      mnl.addElement(newChild);
      return newChild;
    }
  
    /**
     *  This is a convenience method to allow easy determination of whether a
     * node has any children.
     * @return  <code>true</code> if the node has any children,
     *   <code>false</code> if the node has no children.
     */
    public boolean hasChildNodes()
    {
      return m_children.getLength() > 0;
    }
  
    /**
     * Returns a duplicate of this node, i.e., serves as a generic copy
     * constructor for nodes. The duplicate node has no parent (
     * <code>parentNode</code> returns <code>null</code>.).
     * <br>Cloning an <code>Element</code> copies all attributes and their
     * values, including those generated by the  XML processor to represent
     * defaulted attributes, but this method does not copy any text it contains
     * unless it is a deep clone, since the text is contained in a child
     * <code>Text</code> node. Cloning any other type of node simply returns a
     * copy of this node.
     * @param deep If <code>true</code>, recursively clone the subtree under the
     *   specified node; if <code>false</code>, clone only the node itself (and
     *   its attributes, if it is an <code>Element</code>).
     * @return The duplicate node.
     */
    public Node cloneNode(boolean deep)
    {
      ResultTreeFrag newFrag = new ResultTreeFrag(m_docFactory, m_xsupport);
      if(deep)
      {
        int n = m_children.getLength();
        for(int i = 0; i < n; i++)
        {
          newFrag.appendChild(m_children.item(i).cloneNode(deep));
        }
      }
      return newFrag;
    }
  
    /** Unimplemented. */
    public void               normalize()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"normalize not 
supported!");
    }
  
    /** Unimplemented. */
    public boolean            supports(String feature,
                                       String version)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"supports not 
supported!");
      return false;
    }
  
    /** Unimplemented. */
    public String             getNamespaceURI()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getNamespaceURI 
not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public String             getPrefix()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getPrefix not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public void               setPrefix(String prefix)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"setPrefix not 
supported!");
    }
  
    /** Unimplemented. */
    public String       getLocalName()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getLocalName not 
supported!");
      return null;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/ResultTreeHandler.java
  
  Index: ResultTreeHandler.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import org.w3c.dom.*;
  import java.util.Stack;
  import java.util.Enumeration;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.ext.LexicalHandler;
  import org.xml.sax.Locator;
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.SAXException;
  import org.xml.sax.Attributes;
  import org.xml.sax.helpers.NamespaceSupport;
  import org.apache.xalan.utils.DOMBuilder;
  import org.apache.xalan.utils.TreeWalker;
  import org.apache.xalan.utils.RawCharacterHandler;
  import org.apache.xalan.utils.MutableAttrListImpl;
  import org.apache.xalan.utils.StringToStringTable;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.templates.Constants;
  import org.apache.xalan.templates.Stylesheet;
  import org.apache.xalan.templates.StylesheetRoot;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xml.serialize.SerializerFactory;
  import org.apache.xml.serialize.OutputFormat;
  import org.apache.xml.serialize.Method;
  import org.apache.xalan.trace.GenerateEvent;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.DOMHelper;
  
  /**
   * This class is a layer between the direct calls to the result 
   * tree content handler, and the transformer.  For one thing, 
   * we have to delay the call to
   * getContentHandler().startElement(name, atts) because of the
   * xsl:attribute and xsl:copy calls.  In other words,
   * the attributes have to be fully collected before you
   * can call startElement.
   */
  public class ResultTreeHandler 
    implements ContentHandler, RawCharacterHandler, LexicalHandler
  {
    /**
     * Create a new result tree handler.  The real content 
     * handler will be the ContentHandler of the transformer.
     */
    public ResultTreeHandler(TransformerImpl transformer)
    {
      m_transformer = transformer;
    }
  
    /**
     * Create a new result tree handler.  The real content 
     * handler will be the ContentHandler passed as an argument.
     */
    public ResultTreeHandler(TransformerImpl transformer,
                             ContentHandler realHandler)
    {
      m_transformer = transformer;
      m_contentHandler = realHandler;
    }
      
    /**
     * Given a result tree fragment, walk the tree and
     * output it to the result stream.
     */
    public void outputResultTreeFragment(XObject obj, 
                                         XPathContext support)
      throws SAXException
    {
      DocumentFragment docFrag = obj.rtree(support);
      NodeList nl = docFrag.getChildNodes();
      int nChildren = nl.getLength();
      TreeWalker tw = new TreeWalker(this);
      for(int i = 0; i < nChildren; i++)
      {
        flushPending(); // I think.
        tw.traverse(nl.item(i));
      }
    }
    
    /**
     * Clone an element with or without children.
     * TODO: Fix or figure out node clone failure!
     * the error condition is severe enough to halt processing.
     */
    public void cloneToResultTree(Stylesheet stylesheetTree, Node node,
                                  boolean shouldCloneWithChildren,
                                  boolean overrideStrip,
                                  boolean shouldCloneAttributes)
      throws SAXException
    {
      boolean stripWhiteSpace = false;
      XPathContext xctxt = this.m_transformer.getXPathContext();
      DOMHelper dhelper = xctxt.getDOMHelper();
  
      switch(node.getNodeType())
      {
      case Node.TEXT_NODE:
        {
          // If stripWhiteSpace is false, then take this as an override and
          // just preserve the space, otherwise use the XSL whitespace rules.
          if(!overrideStrip)
          {
            // stripWhiteSpace = isLiteral ? true : shouldStripSourceNode(node);
            stripWhiteSpace = false;
          }
          Text tx = (Text)node;
          String data = null;
          // System.out.println("stripWhiteSpace = "+stripWhiteSpace+", 
"+tx.getData());
          if(stripWhiteSpace)
          {
            if(!dhelper.isIgnorableWhitespace(tx))
            {
              data = tx.getData();
              if((null != data) && (0 == data.trim().length()))
              {
                data = null;
              }
            }
          }
          else
          {
            Node parent = node.getParentNode();
            if(null != parent)
            {
              if( Node.DOCUMENT_NODE != parent.getNodeType())
              {
                data = tx.getData();
                if((null != data) && (0 == data.length()))
                {
                  data = null;
                }
              }
            }
            else
            {
              data = tx.getData();
              if((null != data) && (0 == data.length()))
              {
                data = null;
              }
            }
          }
  
          if(null != data)
          {
            // TODO: Hack around the issue of comments next to literals.
            // This would be, when a comment is present, the whitespace
            // after the comment must be added to the literal.  The
            // parser should do this, but XML4J doesn't seem to.
            // <foo>some lit text
            //     <!-- comment -->
            //     </foo>
            // Loop through next siblings while they are comments, then,
            // if the node after that is a ignorable text node, append
            // it to the text node just added.
            if(dhelper.isIgnorableWhitespace(tx))
            {
              ignorableWhitespace(data.toCharArray(), 0, data.length());
            }
            else
            {
              characters(data.toCharArray(), 0, data.length());
            }
          }
        }
        break;
      case Node.DOCUMENT_NODE:
        // Can't clone a document, but refrain from throwing an error
        // so that copy-of will work
        break;
      case Node.ELEMENT_NODE:
        {
          Attributes atts;
          if(shouldCloneAttributes)
          {
            addAttributes( node );
            processNSDecls(node);
          }
          String ns = dhelper.getNamespaceOfNode(node);
          String localName = dhelper.getLocalNameOfNode(node);
          startElement (ns, localName, node.getNodeName());
        }
        break;
      case Node.CDATA_SECTION_NODE:
        {
          String data = ((CDATASection)node).getData();
          cdata(data.toCharArray(), 0, data.length());
        }
        break;
      case Node.ATTRIBUTE_NODE:
        {
          String ns = dhelper.getNamespaceOfNode(node);
          String localName = dhelper.getLocalNameOfNode(node);
          addAttribute(ns, localName, node.getNodeName(), "CDATA", 
                       ((Attr)node).getValue());
        }
        break;
      case Node.COMMENT_NODE:
        {
          comment(((Comment)node).getData());
        }
        break;
      case Node.DOCUMENT_FRAGMENT_NODE:
        {
          
          m_transformer.getMsgMgr().error(null, node, 
XSLTErrorResources.ER_NO_CLONE_OF_DOCUMENT_FRAG); //"No clone of a document 
fragment!");
        }
        break;
      case Node.ENTITY_REFERENCE_NODE:
        {
          EntityReference er = (EntityReference)node;
          entityReference(er.getNodeName());
        }
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:
        {
          ProcessingInstruction pi = (ProcessingInstruction)node;
          processingInstruction(pi.getTarget(), pi.getData());
        }
        break;
      default:
        m_transformer.getMsgMgr().error(XSLTErrorResources.ER_CANT_CREATE_ITEM, 
new Object[] {node.getNodeName()}); //"Can not create item in result tree: 
"+node.getNodeName());
      }
  
    } // end cloneToResultTree function
    
  
  
    /**
     * Check to see if the output prefix should be excluded.
     */
    private String excludePrefix(String name)
    {
      if(null != m_stylesheetRoot) // Just extra defensive
      {
        int indexOfNSSep = name.indexOf(':');
        if(indexOfNSSep > 0)
        {
          String prefix = name.substring(0, indexOfNSSep);
          if(m_stylesheetRoot.containsExcludeResultPrefix(prefix))
            name = name.substring(indexOfNSSep+1);
        }
      }
      return name;
    }
  
  
    /**
     * Flush the pending element.
     */
    public void flushPending()
      throws SAXException
    {
      if(m_pendingStartDoc && (null != m_pendingElementName))
      {
        if(!m_stylesheetRoot.isOutputMethodSet())
        {
          if(m_pendingElementName.equalsIgnoreCase("html") 
             && (null == m_nsSupport.getURI("")))
          {
            // System.out.println("Setting the method automatically to HTML");
            SerializerFactory factory = 
SerializerFactory.getSerializerFactory(Method.HTML);
            OutputFormat oformat = m_stylesheetRoot.getOutputFormat();
            oformat.setMethod(Method.HTML);
            // m_flistener = factory.makeSerializer(oformat).asContentHandler();
          }
        }
      }
  
      if(m_pendingStartDoc && m_mustFlushStartDoc)
      {
        m_pendingStartDoc = false;
        
        getContentHandler().startDocument();
        m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                                            
GenerateEvent.EVENTTYPE_STARTDOCUMENT));
      }
  
      if((null != m_pendingElementName) && m_mustFlushStartDoc)
      {
        /*
        if(null != m_stylesheetRoot.getCDataSectionElems())
        {
        if(isCDataResultElem(m_pendingElementName))
        {
        m_cdataStack.push(TRUE);
        }
        else
        {
        m_cdataStack.push(FALSE);
        }
        }
        */      
        if(!m_nsDeclsHaveBeenAdded)
          addNSDeclsToAttrs();
  
        getContentHandler().startElement(m_pendingElementNS, 
                                                       m_pendingElementLName, 
                                                       m_pendingElementName, 
                                                       m_pendingAttributes);
        m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                          
GenerateEvent.EVENTTYPE_STARTELEMENT,
                                                          m_pendingElementName, 
m_pendingAttributes));
        clearPendingElement();
      }
    }
    
    /**
     * To fullfill the FormatterListener interface... not action
     * for the moment.
     */
    public void setDocumentLocator (Locator locator)
    {
    }
    
    public boolean getFoundStartDoc() { return m_foundStartDoc; }
    private boolean m_foundStartDoc = false;
  
    public boolean getFoundEndDoc() { return m_foundEndDoc; }
    private boolean m_foundEndDoc = false;
  
    /**
     * Bottleneck the startDocument event.
     */
    public void startDocument ()
      throws SAXException
    {
      // m_uniqueNSValue = 0;
      m_foundStartDoc = true;
      m_pendingStartDoc = true;
      m_mustFlushStartDoc = false;
      // m_flistener.startDocument();
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_STARTDOCUMENT));
    }
  
    /**
     * Bottleneck the endDocument event.
     */
    public void endDocument ()
      throws SAXException
    {
      m_foundEndDoc = true;
      m_mustFlushStartDoc = true;
      flushPending();
      getContentHandler().endDocument();
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_ENDDOCUMENT));
      // m_variableStacks.popCurrentContext();
    }
  
    /**
     * Bottleneck the startElement event.  This is used to "pend" an
     * element, so that attributes can still be added to it before 
     * the real "startElement" is called on the result tree listener.
     */
    public void startElement (String ns, String localName, String name)
      throws SAXException
    {
      flushPending();
      m_nsSupport.pushContext();
      setPendingElementName (ns, localName, name);
      m_mustFlushStartDoc = true;
    }
  
    /**
     * Bottleneck the startElement event.  This is used to "pend" an
     * element, so that attributes can still be added to it before 
     * the real "startElement" is called on the result tree listener.
     */
    public void startElement (String ns, String localName, String name, 
                              Attributes atts)
      throws SAXException
    {
      flushPending();
      m_nsSupport.pushContext();
      m_pendingAttributes.clear(); // Is this needed?? -sb
      m_pendingAttributes.addAttributes(atts);
      setPendingElementName (ns, localName, name);
      m_mustFlushStartDoc = true;
    }
  
    /**
     * Bottleneck the endElement event.
     */
    public void endElement (String ns, String localName, String name)
      throws SAXException
    {
      // name = excludePrefix(name);
      flushPending();
      getContentHandler().endElement(ns, localName, name);
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_ENDELEMENT,
                                                        name, 
(Attributes)null));
      // if(null != m_stylesheetRoot.getCDataSectionElems())
      //  m_cdataStack.pop();
      m_nsSupport.popContext();
    }
  
    /**
     * Bottleneck the characters event.
     */
    public void characters (char ch[], int start, int length)
      throws SAXException
    {
      if(!m_mustFlushStartDoc)
      {
        int n = ch.length;
        for(int i = 0; i < n; i++)
        {
          if(!Character.isSpaceChar(ch[i]))
          {
            m_mustFlushStartDoc = true;
            break;
          }
        }
      }
      if(m_mustFlushStartDoc)
      {
        flushPending();
        /*
        if((null != m_stylesheetRoot.getCDataSectionElems()) &&
        !m_cdataStack.isEmpty() && (m_cdataStack.peek() == TRUE))
        {
        boolean isLexHandler = (m_flistener instanceof LexicalHandler);
        if(isLexHandler)
        ((LexicalHandler)m_flistener).startCDATA();
  
        m_flistener.characters(ch, start, length);
  
        if(isLexHandler)
        ((LexicalHandler)m_flistener).endCDATA();
  
        if(null != m_traceListeners)
        fireGenerateEvent(new GenerateEvent(m_transformer,
        GenerateEvent.EVENTTYPE_CDATA,
        ch, start, length));
        }
        else
        */
        {
          getContentHandler().characters(ch, start, length);
          m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                            
GenerateEvent.EVENTTYPE_CHARACTERS,
                                                            ch, start, length));
        }
      }
    }
  
    /**
     * Bottleneck the characters event.
     */
    public void charactersRaw (char ch[], int start, int length)
      throws SAXException
    {
      m_mustFlushStartDoc = true;
      flushPending();
      /*
      if(m_flistener instanceof org.apache.xml.serialize.BaseSerializer)
      {
      ((org.apache.xml.serialize.BaseSerializer)m_flistener).characters(new 
String( ch, start, length ), false, true);
      }
      else
      */
      if(getContentHandler() instanceof RawCharacterHandler)
      {
        ((RawCharacterHandler)getContentHandler()).charactersRaw(ch, start, 
length);
      }
      else if(getContentHandler() instanceof DOMBuilder)
      {
        ((RawCharacterHandler)getContentHandler()).charactersRaw(ch, start, 
length);
      }
      else
      {
        getContentHandler().characters(ch, start, length);
      }
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_CHARACTERS,
                                                        ch, start, length));
    }
  
    /**
     * Bottleneck the ignorableWhitespace event.
     */
    public void ignorableWhitespace (char ch[], int start, int length)
      throws SAXException
    {
      if(m_mustFlushStartDoc)
      {
        flushPending();
        getContentHandler().ignorableWhitespace(ch, start, length);
        m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                          
GenerateEvent.EVENTTYPE_IGNORABLEWHITESPACE,
                                                          ch, start, length));
      }
    }
  
    /**
     * Bottleneck the processingInstruction event.
     */
    public void processingInstruction (String target, String data)
      throws SAXException
    {
      m_mustFlushStartDoc = true;
      flushPending();
      getContentHandler().processingInstruction(target, data);
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_PI,
                                                        target, data));
    }
  
    /**
     * Bottleneck the comment event.
     */
    public void comment(String data) throws SAXException
    {
      m_mustFlushStartDoc = true;
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).comment(data.toCharArray(), 0, 
data.length());
      }
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_COMMENT,
                                                        data));
    }
  
    /**
     * Bottleneck the comment event.
     */
    public void comment(char ch[], int start, int length) throws SAXException
    {
      m_mustFlushStartDoc = true;
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).comment(ch, start, length);
      }
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_COMMENT,
                                                        new String(ch, start, 
length)));
    }
  
  
    /**
     * Bottleneck the comment event.
     */
    public void entityReference(String name) throws SAXException
    {
      m_mustFlushStartDoc = true;
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).startEntity(name);
        ((LexicalHandler)getContentHandler()).endEntity(name);
      }
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_ENTITYREF,
                                                        name));
    }
  
    /**
     * Start an entity.
     */
    public void startEntity(String name) throws SAXException
    {
      m_mustFlushStartDoc = true;
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).startEntity(name);
      }
    }
  
    /**
     * End an entity.
     */
    public void endEntity(String name) throws SAXException
    {
      m_mustFlushStartDoc = true;
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).endEntity(name);
      }
      m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                        
GenerateEvent.EVENTTYPE_ENTITYREF,
                                                        name));
    }
  
    /**
     * Start the DTD.
     */
    public void startDTD(String s1, String s2, String s3) throws SAXException
    {
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).startDTD(s1, s2, s3);
      }
    }
  
    /**
     * End the DTD.
     */
    public void endDTD() throws SAXException
    {
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).endDTD();
      }
    }
    
    /**
     * Tell if a given element name should output it's text
     * as cdata.
     * TODO: This is handling the cdata elems as strings instead
     * of qnames... this needs to be fixed.
     */
    boolean isCDataResultElem(String elementName)
    {
      boolean is = false;
      /*
      OutputFormat outputFormat = m_stylesheetRoot.getOutput();
      if(null == outputFormat)
        return is;
      String[] cdataElems = outputFormat.getCDataElements();
      if(null != cdataElems)
      {
        String elemNS = null;
        String elemLocalName = null;
        int indexOfNSSep = elementName.indexOf(':');
        if(indexOfNSSep > 0)
        {
          String prefix = elementName.substring(0, indexOfNSSep);
          if(prefix.equals("xml"))
          {
            elemNS = QName.S_XMLNAMESPACEURI;
          }
          else
          {
            elemNS = getURI(prefix);
          }
          if(null == elemNS)
          {
            throw new 
RuntimeException(XSLMessages.createMessage(XSLTErrorResources.ER_PREFIX_MUST_RESOLVE,
 new Object[]{prefix}));//"Prefix must resolve to a namespace: "+prefix);
          }
        }
        elemLocalName = (indexOfNSSep < 0) ? elementName : 
elementName.substring(indexOfNSSep+1);
        int n = cdataElems.length;
        for(int i = 0; i < n; i++)
        {
          // This needs to be a qname!
          QName qname = cdataElems[i];
          is = qname.equals(elemNS, elemLocalName);
          if(is)
            break;
        }
      }
      */
      return is;
    }
  
    /**
     * Start the CDATACharacters.
     */
    public void startCDATA() throws SAXException
    {
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).startCDATA();
      }
    }
  
    /**
     * End the CDATA characters.
     */
    public void endCDATA() throws SAXException
    {
      flushPending();
      if(getContentHandler() instanceof LexicalHandler)
      {
        ((LexicalHandler)getContentHandler()).endCDATA();
      }
    }
  
    /**
     * Bottleneck the cdata event.
     */
    public void cdata (char ch[], int start, int length)
      throws SAXException
    {
      m_mustFlushStartDoc = true;
      flushPending();
      /*
      if((null != m_stylesheetRoot.getCDataSectionElems()) &&
      !m_cdataStack.isEmpty() && (m_cdataStack.peek() == TRUE))
      {
      // boolean isLexH = (getContentHandler() instanceof LexicalHandler);
  
      if(getContentHandler() instanceof LexicalHandler)
      ((LexicalHandler)getContentHandler()).startCDATA();
  
      getContentHandler().characters(ch, start, length);
  
      if(getContentHandler() instanceof LexicalHandler)
      ((LexicalHandler)getContentHandler()).endCDATA();
  
      if(null != m_traceListeners)
      fireGenerateEvent(new GenerateEvent(m_transformer,
      GenerateEvent.EVENTTYPE_CDATA,
      ch, start, length));
      }
      else
      */
      {
        getContentHandler().characters(ch, start, length);
        m_transformer.getTraceManager().fireGenerateEvent(new 
GenerateEvent(m_transformer,
                                                          
GenerateEvent.EVENTTYPE_CHARACTERS,
                                                          ch, start, length));
      }
  
      /*
      if(getContentHandler() instanceof FormatterListener)
      {
      ((FormatterListener)getContentHandler()).cdata(ch, start, length);
      }
      else
      {
      // Bad but I think it's better than dropping it.
      getContentHandler().characters(ch, start, length);
      }
      ((FormatterListener)getContentHandler()).cdata(ch, start, length);
      if(null != m_traceListeners)
      fireGenerateEvent(new GenerateEvent(this,
      GenerateEvent.EVENTTYPE_CDATA,
      ch, start, length));
      }
      */
    }
      
    /**
     * Receive notification of a skipped entity.
     *
     * <p>The Parser will invoke this method once for each entity
     * skipped.  Non-validating processors may skip entities if they
     * have not seen the declarations (because, for example, the
     * entity was declared in an external DTD subset).  All processors
     * may skip external entities, depending on the values of the
     * http://xml.org/sax/features/external-general-entities and the
     * http://xml.org/sax/features/external-parameter-entities
     * properties.</p>
     *
     * @param name The name of the skipped entity.  If it is a 
     *        parameter entity, the name will begin with '%'.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void skippedEntity (String name)
      throws SAXException
    {
    }
    
    /**
     * Add the attributes that have been declared to the attribute list.
     * (Seems like I shouldn't have to do this...)
     */
    protected void addNSDeclsToAttrs()
    {
      Enumeration prefixes = m_nsSupport.getDeclaredPrefixes();
      while (prefixes.hasMoreElements()) 
      {
        String prefix = (String)prefixes.nextElement();
        boolean isDefault = (prefix.length() == 0);
        String name;
        if(isDefault)
        {
          prefix = "xml";
          name = "xmlns";
        }
        else
          name="xmlns:"+prefix;
        
        // System.out.println("Adding xmlns: "+name);
          
        // System.out.println("calling addAttribute(null, null, "+name+", 
'CDATA', "+
        //                   m_nsSupport.getURI(prefix)+");");
        m_pendingAttributes.addAttribute("http://www.w3.org/2000/xmlns/";, 
                                         prefix, 
                                         name, "CDATA", 
m_nsSupport.getURI(prefix));
      }
      m_nsDeclsHaveBeenAdded = true;
    }
  
    /**
     * Copy <KBD>xmlns:</KBD> attributes in if not already in scope.
     */
    public void processNSDecls(Node src)
      throws SAXException
    {
      int type;
      // Vector nameValues = null;
      // Vector alreadyProcessedPrefixes = null;
      Node parent = src;
      while (parent != null
             && ((type = parent.getNodeType()) == Node.ELEMENT_NODE
                 || (type == Node.ENTITY_REFERENCE_NODE)))
      {
        if (type == Node.ELEMENT_NODE)
        {
          NamedNodeMap nnm = parent.getAttributes();
          int nAttrs = nnm.getLength();
          for (int i = 0;  i < nAttrs;  i++)
          {
            Node attr = nnm.item(i);
            String aname = attr.getNodeName();
            if (QName.isXMLNSDecl(aname))
            {
              String prefix = QName.getPrefixFromXMLNSDecl(aname);
              String desturi = getURI(prefix);
              String srcURI = attr.getNodeValue();
              if(!srcURI.equalsIgnoreCase(desturi))
              {
                this.startPrefixMapping(prefix, srcURI);
              }
            }
          }
        }
        parent = parent.getParentNode();
      }
    }
      
    /**
     * Given a prefix, return the namespace,
     */
    public String getURI(String prefix)
    {
      return m_nsSupport.getURI(prefix);
    }
  
    /**
     * Given a namespace, try and find a prefix.
     */
    public String getPrefix(String namespace)
    {
      // This Enumeration business may be too slow for our purposes...
      Enumeration enum = m_nsSupport.getPrefixes();
      while(enum.hasMoreElements())
      {
        String prefix = (String)enum.nextElement();
        if(m_nsSupport.getURI(prefix).equals(namespace))
          return prefix;
      }
      return null;
    }  
  
    /**
     * Begin the scope of a prefix-URI Namespace mapping.
     *
     * <p>The information from this event is not necessary for
     * normal Namespace processing: the SAX XML reader will 
     * automatically replace prefixes for element and attribute
     * names when the http://xml.org/sax/features/namespaces
     * feature is true (the default).</p>
     *
     * <p>There are cases, however, when applications need to
     * use prefixes in character data or in attribute values,
     * where they cannot safely be expanded automatically; the
     * start/endPrefixMapping event supplies the information
     * to the application to expand prefixes in those contexts
     * itself, if necessary.</p>
     *
     * <p>Note that start/endPrefixMapping events are not
     * guaranteed to be properly nested relative to each-other:
     * all startPrefixMapping events will occur before the
     * corresponding startElement event, and all endPrefixMapping
     * events will occur after the corresponding endElement event,
     * but their order is not guaranteed.</p>
     *
     * @param prefix The Namespace prefix being declared.
     * @param uri The Namespace URI the prefix is mapped to.
     * @exception org.xml.sax.SAXException The client may throw
     *            an exception during processing.
     * @see #endPrefixMapping
     * @see #startElement
     */
    public void startPrefixMapping (String prefix, String uri)
      throws SAXException
    {
      // System.out.println("startPrefixMapping("+prefix+", "+uri+")");
      String existingURI = m_nsSupport.getURI(prefix);
      if((null == existingURI) || !existingURI.equals(uri))
      {
        m_nsSupport.declarePrefix(prefix, uri);
        getContentHandler().startPrefixMapping(prefix, uri);
      }
    }
  
    /**
     * End the scope of a prefix-URI mapping.
     *
     * <p>See startPrefixMapping for details.  This event will
     * always occur after the corresponding endElement event,
     * but the order of endPrefixMapping events is not otherwise
     * guaranteed.</p>
     *
     * @param prefix The prefix that was being mapping.
     * @exception org.xml.sax.SAXException The client may throw
     *            an exception during processing.
     * @see #startPrefixMapping
     * @see #endElement
     */
    public void endPrefixMapping (String prefix)
      throws SAXException
    {
      getContentHandler().endPrefixMapping(prefix);
    }
    
    /**
     * Use the SAX2 helper class to track result namespaces.
     */
    private NamespaceSupport m_nsSupport = new NamespaceSupport();
    
    /**
     * Get the NamespaceSupport object.
     */
    public NamespaceSupport getNamespaceSupport()
    {
      return m_nsSupport;
    }
    
    /**
     * The transformer object.
     */
    private TransformerImpl m_transformer;
    
    /**
     * The content handler.  May be null, in which 
     * case, we'll defer to the content handler in the 
     * transformer.
     */
    private ContentHandler m_contentHandler;
    
    /**
     * Return the current content handler, which may be a content
     * handler stored in this object, or it may delegate to the 
     * content handler in the transformer.
     *
     * @return The current content handler, or null if none
     *         has been registered.
     * @see #setContentHandler
     */
    public ContentHandler getContentHandler()
    {
      return (null == m_contentHandler) 
             ? m_transformer.getContentHandler() : m_contentHandler;
    }
  
    
    /**
     * The root of a linked set of stylesheets.
     */
    private StylesheetRoot m_stylesheetRoot = null;
      
    /**
     * This is used whenever a unique namespace is needed.
     */
    private int m_uniqueNSValue = 0;
    
    /**
     * Get a unique namespace value.
     */
    public int getUniqueNSValue()
    {
      return m_uniqueNSValue++;
    }
    
    private static final String S_NAMESPACEPREFIX = "ns";
    
    /**
     * Get new unique namespace prefix.
     */
    public String getNewUniqueNSPrefix()
    {
      return S_NAMESPACEPREFIX+String.valueOf(getUniqueNSValue());
    }
  
    private boolean m_mustFlushStartDoc = false;
    
    /**
     * The pending element, namespace, and local name.
     */
    private String m_pendingElementName;
    private String m_pendingElementNS; 
    private String m_pendingElementLName;
    
    /**
     * Set the pending element name.  We have to delay the call to
     * m_flistener.startElement(name, atts) because of the
     * xsl:attribute and xsl:copy calls.  In other words,
     * the attributes have to be fully collected before you
     * can call startElement.
     */
    private void setPendingElementName (String ns, String localName, String 
name)
    {
      m_pendingElementName = name;
      m_pendingElementNS = ns; 
      m_pendingElementLName = localName;
    }  
    
    /**
     * Get the pending element name.  We have to delay the call to
     * m_flistener.startElement(name, atts) because of the
     * xsl:attribute and xsl:copy calls.  In other words,
     * the attributes have to be fully collected before you
     * can call startElement.
     */
    public String getPendingElementName()
    {
      return m_pendingElementName;
    }
    
    /**
     * Clear the pending element values.  This needs to be called 
     * after the real startElement event is sent to the listener.
     */
    private void clearPendingElement()
    {
      m_pendingAttributes.clear();
      m_nsDeclsHaveBeenAdded = false;
      m_pendingElementName = null;
      m_pendingElementNS = null; 
      m_pendingElementLName = null;
    }
  
    /**
     * Flag to tell if a StartDocument event is pending.
     */
    private boolean m_pendingStartDoc = false;
  
    /**
     * The pending attributes.  We have to delay the call to
     * m_flistener.startElement(name, atts) because of the
     * xsl:attribute and xsl:copy calls.  In other words,
     * the attributes have to be fully collected before you
     * can call startElement.
     */
    private MutableAttrListImpl m_pendingAttributes = new MutableAttrListImpl();
    
    /**
     * Flag to try and get the xmlns decls to the attribute list 
     * before other attributes are added.
     */
    private boolean m_nsDeclsHaveBeenAdded = false;
    
    
    /**
     * Get the pending attributes.  We have to delay the call to
     * m_flistener.startElement(name, atts) because of the
     * xsl:attribute and xsl:copy calls.  In other words,
     * the attributes have to be fully collected before you
     * can call startElement.
     */
    public MutableAttrListImpl getPendingAttributes()
    {
      return m_pendingAttributes;
    }
    
    /**
     * Add an attribute to the end of the list.
     * 
     * <p>Do not pass in xmlns decls to this function!
     *
     * <p>For the sake of speed, this method does no checking
     * to see if the attribute is already in the list: that is
     * the responsibility of the application.</p>
     *
     * @param uri The Namespace URI, or the empty string if
     *        none is available or Namespace processing is not
     *        being performed.
     * @param localName The local name, or the empty string if
     *        Namespace processing is not being performed.
     * @param rawName The raw XML 1.0 name, or the empty string
     *        if raw names are not available.
     * @param type The attribute type as a string.
     * @param value The attribute value.
     */
    public void addAttribute (String uri, String localName, String rawName,
                              String type, String value)
    {
      if(!m_nsDeclsHaveBeenAdded)
        addNSDeclsToAttrs();
      m_pendingAttributes.addAttribute(uri, localName, rawName, type, value);
    }
    
    /**
     * Copy an DOM attribute to the created output element, executing
     * attribute templates as need be, and processing the xsl:use
     * attribute.
     */
    public void addAttribute( Attr attr )
      throws SAXException
    {
      DOMHelper helper = m_transformer.getXPathContext().getDOMHelper();
      addAttribute (helper.getNamespaceOfNode(attr), 
                    helper.getLocalNameOfNode(attr), 
                    attr.getNodeName(),
                    "CDATA", 
                    attr.getValue());
    } // end copyAttributeToTarget method
    
    /**
     * Copy DOM attributes to the result element.
     */
    public void addAttributes( Node src )
      throws SAXException
    {
      NamedNodeMap nnm = src.getAttributes();
      int nAttrs = nnm.getLength();
      for (int i = 0;  i < nAttrs;  i++)
      {
        addAttribute((Attr)nnm.item(i));
      }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/StackGuard.java
  
  Index: StackGuard.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Text;
  import org.w3c.dom.Element;
  import java.io.PrintWriter;
  import java.io.StringWriter;
  import org.xml.sax.SAXException;
  import org.apache.xalan.templates.ElemTemplateElement;
  
  /**
   * Class to guard against recursion getting too deep.
   */
  public class StackGuard
  {
    /**
     * Used for infinite loop check. If the value is -1, do not
     * check for infinite loops. Anyone who wants to enable that 
     * check should change the value of this variable to be the
     * level of recursion that they want to check. Be careful setting 
     * this variable, if the number is too low, it may report an 
     * infinite loop situation, when there is none.
     * Post version 1.0.0, we'll make this a runtime feature.   
     */
    private static int m_recursionLimit = -1;
    
    /**
     * Get the recursion limit.
     * Used for infinite loop check. If the value is -1, do not
     * check for infinite loops. Anyone who wants to enable that 
     * check should change the value of this variable to be the
     * level of recursion that they want to check. Be careful setting 
     * this variable, if the number is too low, it may report an 
     * infinite loop situation, when there is none.
     * Post version 1.0.0, we'll make this a runtime feature.   
     */
    public int getRecursionLimit()
    {
      return m_recursionLimit;
    }
    
    /**
     * Get the recursion limit.
     * Used for infinite loop check. If the value is -1, do not
     * check for infinite loops. Anyone who wants to enable that 
     * check should change the value of this variable to be the
     * level of recursion that they want to check. Be careful setting 
     * this variable, if the number is too low, it may report an 
     * infinite loop situation, when there is none.
     * Post version 1.0.0, we'll make this a runtime feature.   
     */
    public void setRecursionLimit(int limit)
    {
      m_recursionLimit = limit;
    }
  
    Node m_xslRule;
    Node m_sourceXML;
  
    java.util.Stack stack = new java.util.Stack();
  
    public StackGuard()
    {
    }
  
    public StackGuard(ElemTemplateElement xslTemplate, Node sourceXML)
    {
      m_xslRule = xslTemplate;
      m_sourceXML = sourceXML;
    }
  
    public boolean equals(Object obj)
    {
      if(((StackGuard)obj).m_xslRule.equals(m_xslRule) &&
         ((StackGuard)obj).m_sourceXML.equals(m_sourceXML))
      {
        return true;
      }
      return false;
    }
  
    public void print(PrintWriter pw)
    {
      // for the moment, these diagnostics are really bad...
      if(m_sourceXML instanceof Text)
      {
        Text tx = (Text)m_sourceXML;
        pw.println(tx.getData());
      }
      else if(m_sourceXML instanceof Element)
      {
        Element elem = (Element)m_sourceXML;
        pw.println(elem.getNodeName());
      }
    }
  
    public void checkForInfinateLoop(StackGuard guard)
      throws SAXException
    {
      int nRules = stack.size();
      int loopCount = 0;
      for(int i = (nRules - 1); i >= 0; i--)
      {
        if(stack.elementAt(i).equals(guard))
        {
          loopCount++;
        }
        if(loopCount >= m_recursionLimit)
        {
          // Print out really bad diagnostics.
          StringWriter sw = new StringWriter();
          PrintWriter pw = new PrintWriter(sw);
          pw.println("Infinite loop diagnosed!  Stack trace:");
          int k;
          for(k = 0; k < nRules; k++)
          {
            pw.println("Source Elem #"+k+" ");
            StackGuard guardOnStack = (StackGuard)stack.elementAt(i);
            guardOnStack.print(pw);
          }
          pw.println("Source Elem #"+k+" ");
          guard.print(pw);
          pw.println("End of infinite loop diagnosis.");
          throw new SAXException(sw.getBuffer().toString());
        }
      }
    }
  
    public void push(ElemTemplateElement xslTemplate, Node sourceXML)
      throws SAXException
    {
      StackGuard guard = new StackGuard(xslTemplate, sourceXML);
      checkForInfinateLoop(guard);
      stack.push(guard);
    }
  
    public void pop()
    {
      stack.pop();
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/TransformerImpl.java
  
  Index: TransformerImpl.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  // Java imports
  import java.util.Stack;
  import java.util.Vector;
  import java.util.Enumeration;
  import java.io.StringWriter;
  import java.io.IOException;
  import java.io.UnsupportedEncodingException;
  
  // Xalan imports
  import org.apache.xalan.res.XSLTErrorResources;
  
  import org.apache.xalan.stree.SourceTreeHandler;
  
  import org.apache.xalan.templates.Constants;
  import org.apache.xalan.templates.ElemAttributeSet;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.templates.StylesheetComposed;
  import org.apache.xalan.templates.ElemForEach;
  import org.apache.xalan.templates.StylesheetRoot;
  import org.apache.xalan.templates.Stylesheet;
  import org.apache.xalan.templates.ElemWithParam;
  import org.apache.xalan.templates.ElemSort;
  import org.apache.xalan.templates.AVT;
  import org.apache.xalan.templates.ElemVariable;
  import org.apache.xalan.templates.ElemParam;
  
  import org.apache.xalan.trace.TraceManager;
  
  import org.apache.xalan.utils.DOMBuilder;
  import org.apache.xalan.utils.NodeVector;
  import org.apache.xalan.utils.BoolStack;
  import org.apache.xalan.utils.QName;
  
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XRTreeFrag;
  import org.apache.xalan.xpath.Arg;
  import org.apache.xalan.xpath.XPathAPI;
  import org.apache.xalan.xpath.VariableStack;
  import org.apache.xalan.xpath.XPathParser;
  
  // Back support for liaisons
  import org.apache.xalan.xpath.DOM2Helper;
  
  // Serializer Imports
  import org.apache.xml.serialize.OutputFormat;
  import org.apache.xml.serialize.Serializer;
  import org.apache.xml.serialize.SerializerFactory;
  import org.apache.xml.serialize.Method;
  
  // DOM Imports
  import org.w3c.dom.Attr;
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.Document;
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.Node;
  
  // SAX2 Imports
  import org.xml.sax.ContentHandler;
  import org.xml.sax.helpers.XMLFilterImpl;
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  import org.xml.sax.XMLReader;
  import org.xml.sax.Locator;
  import org.xml.sax.helpers.XMLReaderFactory;
  import org.xml.sax.ext.DeclHandler;
  import org.xml.sax.ext.LexicalHandler;
  
  // TRaX Imports
  import trax.Result;
  import trax.Transformer;
  import trax.TransformException;
  import trax.URIResolver;
  
  /**
   * <meta name="usage" content="advanced"/>
   * The Xalan workhorse -- Collaborates with the XPath xcontext, the DOM,
   * and the XPath engine, to transform a source tree of nodes into a result 
tree
   * according to instructions and templates specified by a stylesheet tree.
   * We suggest you use one of the
   * static XSLTProcessorFactory getProcessor() methods to instantiate the 
processor
   * and return an interface that greatly simplifies the process of manipulating
   * TransformerImpl.
   *
   * <p>The methods <code>process(...)</code> are the primary public entry 
points.
   * The best way to perform transformations is to use the
   * [EMAIL PROTECTED] XSLTProcessor#process(XSLTInputSource, XSLTInputSource, 
XSLTResultTarget)} method,
   * but you may use any of process methods defined in TransformerImpl.</p>
   * 
   * <p>Please note that this class is not safe per instance over multiple 
   * threads.  If you are in a multithreaded environment, you should 
   * keep a pool of these objects, or create a new one each time.  In a 
   * multithreaded environment, the right way to do things is to create a 
   * StylesheetRoot via processStylesheet, and then reuse this object 
   * over multiple threads.</p>
   *
   * <p>If you reuse the processor instance, you should call reset() between 
transformations.</p>
   * @see XSLTProcessorFactory
   * @see XSLTProcessor
   */
  public class TransformerImpl extends XMLFilterImpl implements Transformer
  {
    //==========================================================
    // SECTION: Constructors
    //==========================================================
  
    /**
     * Construct a TransformerImpl.
     *
     * @param stylesheet The root of the stylesheet tree.
     */
    public TransformerImpl(StylesheetRoot stylesheet)
    {
      setStylesheet(stylesheet);
      setXPathContext(new XPathContext(this));
    }
    
    /**
     * Reset the state.  This needs to be called after a process() call
     * is invoked, if the processor is to be used again.
     */
    public void reset()
    {
      m_stylesheetRoot = null;
      // m_rootDoc = null;
      // if(null != m_countersTable)
      //  System.out.println("Number counters made: 
"+m_countersTable.m_countersMade);
      m_countersTable = null;
      // m_resultNameSpaces = new Stack();
      m_stackGuard = new StackGuard();
      getXPathContext().reset();
    }
        
    // ========= Transformer Interface Implementation ==========
    
    /**
     * Process the source tree to SAX parse events.
     * @param xmlSource  The input for the source tree.
     */
    public void transform( InputSource xmlSource)
      throws TransformException
    {
      String liaisonClassName = 
System.getProperty("org.apache.xalan.source.liaison");
  
      if(null != liaisonClassName)
      {
        try 
        {
          DOM2Helper liaison =  
(DOM2Helper)(Class.forName(liaisonClassName).newInstance());
          liaison.parse(xmlSource);
          getXPathContext().setDOMHelper(liaison);
          transformNode(liaison.getDocument());
        } 
        catch (SAXException se) 
        {
          throw new TransformException(se);
        } 
        catch (ClassNotFoundException e1) 
        {
          throw new TransformException("XML Liaison class " + liaisonClassName +
            " specified but not found", e1);
        } 
        catch (IllegalAccessException e2) 
        {
            throw new TransformException("XML Liaison class " + 
liaisonClassName +
              " found but cannot be loaded", e2);
        } 
        catch (InstantiationException e3) 
        {
            throw new TransformException("XML Liaison class " + 
liaisonClassName +
              " loaded but cannot be instantiated (no empty public 
constructor?)",
              e3);
        } 
        catch (ClassCastException e4) 
        {
            throw new TransformException("XML Liaison class " + 
liaisonClassName +
              " does not implement DOM2Helper", e4);
        }
      }
      else
      {
        try
        {
          // Get an already set XMLReader, or create one.
          XMLReader reader = this.getXMLReader();
          if(null == reader)
          {
            reader = XMLReaderFactory.createXMLReader();
          }
          try
          {
            reader.setFeature("http://xml.org/sax/features/namespace-prefixes";, 
true);
          }
          catch(SAXException se)
          {
            // What can we do?
            // TODO: User diagnostics.
          }
          
          // Get the input content handler, which will handle the 
          // parse events and create the source tree.
          ContentHandler inputHandler = getInputContentHandler();
          reader.setContentHandler( inputHandler );
          reader.setProperty("http://xml.org/sax/properties/lexical-handler";, 
inputHandler);
          
          getXPathContext().setPrimaryReader(reader);
          
          // Kick off the parse.  When the ContentHandler gets 
          // the startDocument event, it will call transformNode( node ).
          reader.parse( xmlSource );
        }
        catch(SAXException se)
        {
          throw new TransformException(se);
        }
        catch(IOException ioe)
        {
          throw new TransformException(ioe);
        }
      }
    }
    
    /**
     * Process the an input source to a DOM node.  FOR INTERNAL USE ONLY.
     * @param xmlSource  The input for the source tree.
     */
    public Node parseToNode( InputSource xmlSource)
      throws TransformException
    {
      // Duplicate code from above... but slightly different.  
      // TODO: Work on this...
      
      Node doc = null;
      String liaisonClassName = 
System.getProperty("org.apache.xalan.source.liaison");
  
      if(null != liaisonClassName)
      {
        try 
        {
          DOM2Helper liaison =  
(DOM2Helper)(Class.forName(liaisonClassName).newInstance());
          liaison.parse(xmlSource);
          getXPathContext().setDOMHelper(liaison);
          doc = liaison.getDocument();
        } 
        catch (SAXException se) 
        {
          throw new TransformException(se);
        } 
        catch (ClassNotFoundException e1) 
        {
          throw new TransformException("XML Liaison class " + liaisonClassName +
            " specified but not found", e1);
        } 
        catch (IllegalAccessException e2) 
        {
            throw new TransformException("XML Liaison class " + 
liaisonClassName +
              " found but cannot be loaded", e2);
        } 
        catch (InstantiationException e3) 
        {
            throw new TransformException("XML Liaison class " + 
liaisonClassName +
              " loaded but cannot be instantiated (no empty public 
constructor?)",
              e3);
        } 
        catch (ClassCastException e4) 
        {
            throw new TransformException("XML Liaison class " + 
liaisonClassName +
              " does not implement DOM2Helper", e4);
        }
      }
      else
      {
        try
        {
          // Get an already set XMLReader, or create one.
          XMLReader reader = this.getXMLReader();
          if(null == reader)
          {
            reader = XMLReaderFactory.createXMLReader();
          }
          try
          {
            reader.setFeature("http://xml.org/sax/features/namespace-prefixes";, 
true);
          }
          catch(SAXException se)
          {
            // What can we do?
            // TODO: User diagnostics.
          }
          
          // TODO: Handle Xerces DOM parser.
          
          // Get the input content handler, which will handle the 
          // parse events and create the source tree.
          ContentHandler inputHandler = getInputContentHandler();
          
          Class inputHandlerClass = ((Object)inputHandler).getClass();
          inputHandler = (ContentHandler)inputHandlerClass.newInstance();
          
          reader.setContentHandler( inputHandler );
          reader.setProperty("http://xml.org/sax/properties/lexical-handler";, 
inputHandler);
          
          getXPathContext().setPrimaryReader(reader);
                  
          // ...and of course I need a standard way to get a node...
          if(inputHandler instanceof org.apache.xalan.stree.SourceTreeHandler)
          {
            // Kick off the parse.  When the ContentHandler gets 
            // the startDocument event, it will call transformNode( node ).
            reader.parse( xmlSource );
            
            doc = 
((org.apache.xalan.stree.SourceTreeHandler)inputHandler).getRoot();
          }
        }
        catch(java.lang.IllegalAccessException iae)
        {
          throw new TransformException(iae);
        }
        catch(InstantiationException ie)
        {
          throw new TransformException(ie);
        }
        catch(SAXException se)
        {
          throw new TransformException(se);
        }
        catch(IOException ioe)
        {
          throw new TransformException(ioe);
        }
      }
      return doc;
    }
    
    /**
     * Create a ContentHandler from a Result object.
     */
    ContentHandler createResultContentHandler(Result outputTarget)
      throws TransformException
    {
      ContentHandler handler;
      
      // If the Result object contains a Node, then create 
      // a ContentHandler that will add nodes to the input node.
      Node outputNode = outputTarget.getNode();
      if(null != outputNode)
      {
        int type = outputNode.getNodeType();
  
        Document doc = (Node.DOCUMENT_NODE == type) 
                       ? (Document)outputNode : outputNode.getOwnerDocument();
        
        handler = (Node.DOCUMENT_FRAGMENT_NODE == type) ?
                  new DOMBuilder(doc, (DocumentFragment)outputNode) :
                  new DOMBuilder(doc, outputNode);
      }
      // Otherwise, create a ContentHandler that will serialize the 
      // result tree to either a stream or a writer.
      else
      {      
        // Get the output format that was set by the user, otherwise get the 
        // output format from the stylesheet.
        OutputFormat format = (null == m_outputFormat) 
                              ? getStylesheet().getOutputComposed() :
                                m_outputFormat;
        
        String method = format.getMethod();
        if(null == method)
          method = Method.XML;
        SerializerFactory sfactory = 
SerializerFactory.getSerializerFactory(method);
        
        try
        {
          Serializer serializer 
            = (null != outputTarget.getCharacterStream()) ?
              sfactory.makeSerializer(outputTarget.getCharacterStream(), 
format) :
              sfactory.makeSerializer(outputTarget.getByteStream(), format);
          handler = serializer.asContentHandler();
        }
        catch(UnsupportedEncodingException uee)
        {
          throw new TransformException(uee);
        }
        catch(IOException ioe)
        {
          throw new TransformException(ioe);
        }
        
      }
      return handler;
    }
  
    /**
     * Process the source tree to the output result.
     * @param xmlSource  The input for the source tree.
     * @param outputTarget The output source target.
     */
    public void transform( InputSource xmlSource, Result outputTarget)
      throws TransformException
    {
      ContentHandler handler = createResultContentHandler(outputTarget);
      this.setContentHandler(handler);
      transform( xmlSource );
    }
  
    /**
     * Process the source node to the output result, if the 
     * processor supports the "http://xml.org/trax/features/dom/input"; 
     * feature.
     * @param node  The input source node, which can be any valid DOM node.
     * @param outputTarget The output source target.
     */
    public void transformNode( Node node, Result outputTarget)
      throws TransformException
    {
      ContentHandler handler = createResultContentHandler(outputTarget);
      this.setContentHandler(handler);
      transformNode( node );
    }
    
    /**
     * Process the source node to the output result, if the 
     * processor supports the "http://xml.org/trax/features/dom/input"; 
     * feature.
     * @param node  The input source node, which can be any valid DOM node.
     * @param outputTarget The output source target.
     */
    public void transformNode( Node node )
      throws TransformException
    {
      try
      {
        pushGlobalVars(node);
        this.transformNode(null, null, node, null);
        if((null != m_resultTreeHandler) && 
!m_resultTreeHandler.getFoundEndDoc())
        {
          m_resultTreeHandler.endDocument();
          this.m_resultTreeHandler.flushPending();
        }
      }
      catch(SAXException se)
      {
        throw new TransformException(se);
      }
    }
    
    /**
     * The content handler for the source input tree.
     */
    ContentHandler m_inputContentHandler;
    
    /**
     * Get a SAX2 ContentHandler for the input.
     * @return A valid ContentHandler, which should never be null, as 
     * long as getFeature("http://xml.org/trax/features/sax/input";) 
     * returns true.
     */
    public ContentHandler getInputContentHandler()
    {
      if(null == m_inputContentHandler)
        m_inputContentHandler = new SourceTreeHandler(this);
  
      return m_inputContentHandler;
    }
    
     /**
     * Get a SAX2 DeclHandler for the input.
     * @return A valid DeclHandler, which should never be null, as 
     * long as getFeature("http://xml.org/trax/features/sax/input";) 
     * returns true.
     */
    public DeclHandler getInputDeclHandler()
    {
      if(m_inputContentHandler instanceof DeclHandler)
        return (DeclHandler)m_inputContentHandler;
      else
        return null;
    }
   
     /**
     * Get a SAX2 LexicalHandler for the input.
     * @return A valid LexicalHandler, which should never be null, as 
     * long as getFeature("http://xml.org/trax/features/sax/input";) 
     * returns true.
     */
    public LexicalHandler getInputLexicalHandler()
    {
      if(m_inputContentHandler instanceof LexicalHandler)
        return (LexicalHandler)m_inputContentHandler;
      else
        return null;
    }
    
    /**
     * The output format object set by the user.  May be null.
     */
    private OutputFormat m_outputFormat;
  
    /**
     * Set the output properties for the transformation.  These 
     * properties will override properties set in the templates 
     * with xsl:output.
     * 
     * @see org.xml.serialize.OutputFormat
     */
    public void setOutputFormat(OutputFormat oformat)
    {
      m_outputFormat = oformat;
    }
      
    /**
     * Set a parameter for the templates.
     * @param name The name of the parameter.
     * @param namespace The namespace of the parameter.
     * @value The value object.  This can be any valid Java object 
     * -- it's up to the processor to provide the proper 
     * coersion to the object, or simply pass it on for use 
     * in extensions.
     */
    public void setParameter(String name, String namespace, Object value)
    {
      VariableStack varstack = getXPathContext().getVarStack();
      QName qname = new QName(namespace, name);
      XObject xobject = XObject.create(value);
      varstack.pushVariable(qname, xobject);
    }
    
    /**
     * Reset the parameters to a null list.  
     */
    public void resetParameters()
    {
    }
    
    /**
     * Given a template, search for
     * the arguments and push them on the stack.  Also,
     * push default arguments on the stack.
     * You <em>must</em> call popContext() when you are
     * done with the arguments.
     */
    public void pushParams(Stylesheet stylesheetTree,
                    ElemTemplateElement xslCallTemplateElement,
                    Node sourceNode, QName mode)
      throws SAXException
    {
      // The trick here is, variables need to be executed outside the context 
      // of the current stack frame.
      
      XPathContext xctxt = getXPathContext();
      VariableStack vars = xctxt.getVarStack();
      if(1 == vars.getCurrentStackFrameIndex())
      {
        vars.pushElemFrame();
      }
  
      for(ElemTemplateElement child = 
xslCallTemplateElement.getFirstChildElem();
          null != child; child = child.getNextSiblingElem())
      {
        // Is it an xsl:with-param element?
        if(Constants.ELEMNAME_WITHPARAM == child.getXSLToken())
        {
          ElemWithParam xslParamElement = (ElemWithParam)child;
  
          // Get the argument value as either an expression or 
          // a result tree fragment.
          XObject var;
          if(null != xslParamElement.getSelect())
          {
            var = xslParamElement.getSelect().execute(getXPathContext(), 
sourceNode,
                                                      xslParamElement);
          }
          else
          {
            // Use result tree fragment
            DocumentFragment df = transformToRTF(stylesheetTree, 
                                                 xslParamElement,
                                                 sourceNode, mode);
            var = new XRTreeFrag(df);
          }
          
          vars.push(new Arg(xslParamElement.getName(), 
                                                           var, true));
        }
      }
      
    } // end pushParams method
    
    /**
     * Internal -- push the global variables onto 
     * the context's variable stack.
     */
    protected void pushGlobalVars(Node contextNode)
      throws SAXException
    {
      // I'm a little unhappy with this, as it seems like 
      // this will make all the variables for all stylesheets 
      // in scope, when really only the current stylesheet's 
      // global variables should be in scope.  Have to think on 
      // this more...
      XPathContext xctxt = getXPathContext();
      VariableStack vs = xctxt.getVarStack();
      if(1 == vs.getCurrentStackFrameIndex())
      {
        vs.pushElemFrame();
      }
      StylesheetRoot sr = getStylesheet();
  
      Enumeration vars = sr.getVariablesComposed();
      while(vars.hasMoreElements())
      {
        ElemVariable v = (ElemVariable)vars.nextElement();
        Object val = vs.getVariable(v.getName());
        if(null != val)
          continue;
        XObject xobj = v.getValue(this, contextNode);
        vs.pushVariable(v.getName(), xobj);
      }
      vars = sr.getParamsComposed();
      while(vars.hasMoreElements())
      {
        ElemParam v = (ElemParam)vars.nextElement();
        Object val = vs.getVariable(v.getName());
        if(null != val)
          continue;
        XObject xobj = v.getValue(this, contextNode);
        vs.pushVariable(v.getName(), xobj);
      }
      vs.markGlobalStackFrame();
    }
  
    
    /**
     * Set an object that will be used to resolve URIs used in 
     * document(), etc.
     * @param resolver An object that implements the URIResolver interface, 
     * or null.
     */
    public void setURIResolver(URIResolver resolver)
    {
    }
    
    /**
     * The XMLReader used to parse the source tree.
     */
    private XMLReader m_reader;
    
    /**
     * Set an XML parser for the source tree.  Note that if 
     * Transformer.setXMLReader is not called, the parser set 
     * with Processor.setXMLReader will be used.
     */
    public void setXMLReader(XMLReader reader)
    {
      m_reader = reader;
    }
  
    /**
     * Get the XML parser used for the source tree.  Note that 
     * if Transformer.setXMLReader is not called, the parser set 
     * with Processor.setXMLReader will be used.
     */
    public XMLReader getXMLReader()
    {
      return m_reader;
    }
    
    // ======== End Transformer Implementation ========  
      
    /**
     * <meta name="usage" content="advanced"/>
     * Given a stylesheet element, create a result tree fragment from it's
     * contents.
     * @param stylesheetTree The stylesheet object that holds the fragment.
     * @param templateParent The template element that holds the fragment.
     * @param sourceNode The current source context node.
     * @param mode The mode under which the template is operating.
     * @return An object that represents the result tree fragment.
     */
    public DocumentFragment transformToRTF(
                                          Stylesheet stylesheetTree,
                                          ElemTemplateElement templateParent,
                                          Node sourceNode, QName mode)
      throws SAXException
    {
      XPathContext xctxt = getXPathContext();
      Document docFactory = xctxt.getDOMHelper().getDOMFactory();
  
      // Create a ResultTreeFrag object.
      ResultTreeFrag resultFragment 
        = new ResultTreeFrag(docFactory, xctxt);
  
      // Create a DOMBuilder object that will handle the SAX events 
      // and build the ResultTreeFrag nodes.
      ContentHandler rtfHandler = new DOMBuilder(docFactory, resultFragment);
  
      // Save the current result tree handler.
      ResultTreeHandler savedRTreeHandler = this.m_resultTreeHandler;
      
      // And make a new handler for the RTF.
      this.m_resultTreeHandler = new ResultTreeHandler(this, rtfHandler);
  
      // Do the transformation of the child elements.
      executeChildTemplates(templateParent, sourceNode, mode);
      
      // Make sure everything is flushed!
      this.m_resultTreeHandler.flushPending();
  
      // Restore the previous result tree handler.
      this.m_resultTreeHandler = savedRTreeHandler;
  
      return resultFragment;
    }  
    
    /** 
     * <meta name="usage" content="advanced"/>
     * Take the contents of a template element, process it, and
     * convert it to a string.
     * 
     * @exception SAXException Might be thrown from the  document() function, or
     *      from xsl:include or xsl:import.
     * @param transformer The XSLT transformer instance.
     * @param sourceNode The current source node context.
     * @param mode The current mode.
     * @return The stringized result of executing the elements children.
     */
    public String transformToString(ElemTemplateElement elem, 
                                   Node sourceNode,
                                   QName mode)
      throws SAXException
    {    
      // Save the current result tree handler.
      ResultTreeHandler savedRTreeHandler = this.m_resultTreeHandler;
      
      // Create a Serializer object that will handle the SAX events 
      // and build the ResultTreeFrag nodes.
      ContentHandler shandler;
      StringWriter sw;
      try
      {
        SerializerFactory sfactory = 
SerializerFactory.getSerializerFactory("text");
        sw = new StringWriter();
        OutputFormat format = new OutputFormat();
        format.setPreserveSpace(true);
        Serializer serializer = sfactory.makeSerializer(sw, format);
        shandler = serializer.asContentHandler();
      }
      catch(IOException ioe)
      {
        throw new SAXException(ioe);
      }
  
      // And make a new handler that will write to the RTF.
      this.m_resultTreeHandler = new ResultTreeHandler(this, shandler);
      
      this.m_resultTreeHandler.startDocument();
  
      // Do the transformation of the child elements.
      executeChildTemplates(elem, sourceNode, mode);
      
      // Make sure everything is flushed!
      this.m_resultTreeHandler.flushPending();
      
      this.m_resultTreeHandler.endDocument();
      
      // Restore the previous result tree handler.
      this.m_resultTreeHandler = savedRTreeHandler;
      
      return sw.toString();
    }
          
    /** 
     * <meta name="usage" content="advanced"/>
     * Perform a query if needed, and call transformNode for each child.
     * 
     * @exception SAXException Thrown in a variety of circumstances.
     * @param stylesheetTree The owning stylesheet tree.
     * @param xslInstruction The stylesheet element context (depricated -- I do 
     *      not think we need this).
     * @param template The owning template context.
     * @param sourceNodeContext The current source node context.
     * @param mode The current mode.
     * @param selectPattern The XPath with which to perform the selection.
     * @param xslToken The current XSLT instruction (depricated -- I do not     
     *     think we want this).
     * @param tcontext The TransformerImpl context.
     * @param selectStackFrameIndex The stack frame context for executing the
     *                              select statement.
     */
    public void transformSelectedNodes(StylesheetComposed stylesheetTree, 
                                       ElemTemplateElement xslInstruction, // 
xsl:apply-templates or xsl:for-each
                                       ElemTemplateElement template, // The 
template to copy to the result tree
                                       Node sourceNodeContext, QName mode, 
                                       XPath selectPattern, 
                                       int selectStackFrameIndex)
      throws SAXException
    {
      // Get the xsl:sort keys, if any.
      Vector keys = processSortKeys(xslInstruction, sourceNodeContext);
      
      XPathContext xctxt = getXPathContext();
        
      NodeIterator sourceNodes;
      VariableStack varstack = xctxt.getVarStack();
      
      // Was a select attribute specified?
      if(null == selectPattern)
      {
        if(null == m_selectDefault)
        {
          m_selectDefault = new XPath();
          XPathParser parser = new XPathParser();
          parser.initXPath(m_selectDefault, "node()", template);
        }
        selectPattern = m_selectDefault;
      }
      
      // Save where-ever it is that the stack frame index may be pointing to.
      int savedCurrentStackFrameIndex = varstack.getCurrentStackFrameIndex();
  
      // Make sure the stack frame index for variables is pointing to the right 
place.
      varstack.setCurrentStackFrameIndex(selectStackFrameIndex);
      
      try
      {
        XObject result = selectPattern.execute(xctxt, sourceNodeContext, 
                                               xslInstruction);
        sourceNodes = result.nodeset();
        if(TransformerImpl.S_DEBUG)
          getTraceManager().fireSelectedEvent(sourceNodeContext,
                                              xslInstruction, "select", 
selectPattern, result);
      }
      finally
      {
        varstack.setCurrentStackFrameIndex(savedCurrentStackFrameIndex);
      }
  
      // Of we now have a list of source nodes, sort them if needed, 
      // and then call transformNode on each of them.
      if(null != sourceNodes)
      {
        // Sort if we need to.
        if(null != keys)
        {
          NodeSorter sorter = new NodeSorter(xctxt);
          
          NodeSet nodeList;
          if(sourceNodes instanceof NodeSet)
          {
            nodeList = ((NodeSet)sourceNodes);
            nodeList.setShouldCacheNodes(true);
            nodeList.runTo(-1);
          }
          else
          {
            nodeList = new NodeSet(sourceNodes);
            sourceNodes = nodeList;
          }
          sorter.sort(nodeList, keys, xctxt);
          nodeList.setCurrentPos(0);
        }
        
        // Push the ContextNodeList on a stack, so that select="position()"
        // and the like will work.
        // System.out.println("pushing context node list...");
        xctxt.pushContextNodeList((NodeSet)sourceNodes );
        try
        {   
          // Do the transformation on each.
          Node context;
          while(null != (context = sourceNodes.nextNode())) 
          {
            transformNode(xslInstruction, template, context, mode);
          }
        }
        finally
        {
          xctxt.popContextNodeList();
        }
      }
      
    }
    
    /** 
     * <meta name="usage" content="advanced"/>
     * Given an element and mode, find the corresponding
     * template and process the contents.
     * 
     * @param stylesheetTree The current Stylesheet object.
     * @param xslInstruction The calling element.
     * @param template The template to use if xsl:for-each, or null.
     * @param selectContext The selection context.
     * @param child The source context node.
     * @param mode The current mode, may be null.
     * @exception SAXException 
     * @return true if applied a template, false if not.
     */
    public boolean transformNode(
                                  ElemTemplateElement xslInstruction, // 
xsl:apply-templates or xsl:for-each
                                  ElemTemplateElement template, // may be null
                                  Node child,
                                  QName mode
                                  )
      throws SAXException
    {    
      int nodeType = child.getNodeType();
  
      // To find templates, use the the root of the import tree if 
      // this element is not an xsl:apply-imports or starting from the root, 
      // otherwise use the root of the stylesheet tree.
      // TODO: Not sure apply-import handling is correct right now.  -sb
      StylesheetComposed stylesheetTree = (null == template) 
                                          ? getStylesheet() 
                                            : template.getStylesheetComposed();
  
      XPathContext xctxt = getXPathContext();
      boolean isDefaultTextRule = false;
      
      if(null == template)
      {
        // Find the XSL template that is the best match for the 
        // element.        
        template = stylesheetTree.getTemplateComposed(xctxt, 
                                                      child, mode,
                                                      
getQuietConflictWarnings());
        
        // If that didn't locate a node, fall back to a default template rule.
        // See http://www.w3.org/TR/xslt#built-in-rule.
        if(null == template)
        {
          StylesheetRoot root = m_stylesheetRoot;
          switch(nodeType)
          {
          case Node.DOCUMENT_FRAGMENT_NODE:
          case Node.ELEMENT_NODE:
            template = root.getDefaultRule();
            break;
          case Node.CDATA_SECTION_NODE:
          case Node.TEXT_NODE:
          case Node.ATTRIBUTE_NODE:
            template = root.getDefaultTextRule();
            isDefaultTextRule = true;
            break;
          case Node.DOCUMENT_NODE:
            template = root.getDefaultRootRule();
            break;
          default:
            // No default rules for processing instructions and the like.
            return false;
          }   
        }
      }
      
      // If we are processing the default text rule, then just clone 
      // the value directly to the result tree.
      if(isDefaultTextRule)
      {
        switch(nodeType)
        {
        case Node.CDATA_SECTION_NODE:
        case Node.TEXT_NODE:
          getResultTreeHandler().cloneToResultTree(stylesheetTree, child, 
false, false, false);
          break;
        case Node.ATTRIBUTE_NODE:
          {
            String val = ((Attr)child).getValue();
            getResultTreeHandler().characters(val.toCharArray(), 0, 
val.length());
          }
          break;
        }
      }
      else
      {
        // Fire a trace event for the template.
        if(TransformerImpl.S_DEBUG)
          getTraceManager().fireTraceEvent(child, mode, template);
        
        // And execute the child templates.
        executeChildTemplates(template, child, mode);
      }
      return true;
    }
  
    /** 
     * <meta name="usage" content="advanced"/>
     * Execute each of the children of a template element.
     * 
     * @param transformer The XSLT transformer instance.
     * @param sourceNode The current context node.
     * @param mode The current mode.
     * @exception SAXException Might be thrown from the  document() function, or
     *      from xsl:include or xsl:import.
     */
    public void executeChildTemplates(ElemTemplateElement elem, 
                                Node sourceNode,
                                QName mode)
      throws SAXException
    {    
      // Does this element have any children?
      ElemTemplateElement firstChild = elem.getFirstChildElem();
      if(null == firstChild)
        return;
      
      XPathContext xctxt = getXPathContext();
  
      // Check for infinite loops if we have to.
      boolean check = (getRecursionLimit() > -1);
      if (check)
        getStackGuard().push(elem, sourceNode);
      
      // We need to push an element frame in the variables stack, 
      // so all the variables can be popped at once when we're done.
      VariableStack varstack = getXPathContext().getVarStack();
      varstack.pushElemFrame();
      
      Locator savedLocator = xctxt.getSAXLocator();
      try
      {
        // Loop through the children of the template, calling execute on 
        // each of them.
        for (ElemTemplateElement t = firstChild; t != null; 
             t = t.getNextSiblingElem()) 
        {
          xctxt.setSAXLocator(t);
          t.execute(this, sourceNode, mode);
        }
      }
      finally
      {
        xctxt.setSAXLocator(savedLocator);
        // Pop all the variables in this element frame.
        varstack.popElemFrame();
      }
      
      // Check for infinite loops if we have to
      if (check)
        getStackGuard().pop();
    }
        
    /**
     * <meta name="usage" content="advanced"/>
     * Get the keys for the xsl:sort elements.
     */
    private Vector processSortKeys(ElemTemplateElement xslInstruction,
                                   Node sourceNodeContext)
      throws SAXException
    {
      Vector keys = null;
      int tok = xslInstruction.getXSLToken();
      if((Constants.ELEMNAME_APPLY_TEMPLATES == tok) ||
         (Constants.ELEMNAME_FOREACH == tok))
      {
        XPathContext xctxt = getXPathContext();
        ElemForEach foreach = (ElemForEach)xslInstruction;
        int nElems = foreach.getSortElemCount();
        
        if(nElems > 0)
          keys = new Vector();
        
        // March backwards, collecting the sort keys.
        for(int i = 0; i < nElems; i++)
        {
          ElemSort sort = foreach.getSortElem(i);
          String langString = (null != sort.getLang())
                              ? sort.getLang().evaluate(xctxt, 
                                                        sourceNodeContext, 
                                                        xslInstruction, 
                                                        new StringBuffer())
                                : null;
          String dataTypeString 
            = sort.getDataType().evaluate(xctxt, 
                                          sourceNodeContext, 
                                          xslInstruction, 
                                          new StringBuffer());
          boolean treatAsNumbers 
            = ((null != dataTypeString)&& 
               dataTypeString.equals(Constants.ATTRVAL_DATATYPE_NUMBER)) ? 
              true : false;
          String orderString 
            = sort.getOrder().evaluate(xctxt, sourceNodeContext, 
                                       xslInstruction, 
                                       new StringBuffer());
          boolean descending = ((null != orderString) &&  
                                
orderString.equals(Constants.ATTRVAL_ORDER_DESCENDING))? 
                               true : false;
  
          AVT caseOrder = sort.getCaseOrder();
          boolean caseOrderUpper;
          if(null != caseOrder)
          {
            String caseOrderString 
              = caseOrder.evaluate(xctxt, 
                                   sourceNodeContext, 
                                   xslInstruction, 
                                   new StringBuffer());
            caseOrderUpper = ((null != caseOrderString)&& 
                              
caseOrderString.equals(Constants.ATTRVAL_CASEORDER_UPPER)) ? 
                             true : false;
          }
          else
          {
            caseOrderUpper = false;
          }
  
          keys.addElement(new NodeSortKey(this, sort.getSelect(), 
                                          treatAsNumbers, 
                                          descending, langString, 
                                          caseOrderUpper,xslInstruction));
        }
      }
      return keys;
    }
    
    //==========================================================
    // SECTION: Member variables
    //==========================================================
    
    /**
     * The root of a linked set of stylesheets.
     */
    private StylesheetRoot m_stylesheetRoot = null;
    
    /**
     * Set the stylesheet for this processor.  If this is set, then the
     * process calls that take only the input .xml will use
     * this instead of looking for a stylesheet PI.  Also,
     * setting the stylesheet is needed if you are going
     * to use the processor as a SAX ContentHandler.
     */
    public void setStylesheet(StylesheetRoot stylesheetRoot)
    {
      m_stylesheetRoot = stylesheetRoot;
    }
  
    /**
     * Get the current stylesheet for this processor.
     */
    public StylesheetRoot getStylesheet()
    {
      return m_stylesheetRoot;
    }
    
    /**
     * Used for default selection.
     */
    private XPath m_selectDefault;
  
    /**
     * If this is set to true, do not warn about pattern
     * match conflicts.
     */
    private boolean m_quietConflictWarnings = false;
    
    /**
     * Get quietConflictWarnings property.
     */
    public boolean getQuietConflictWarnings()
    {
      return m_quietConflictWarnings;
    }
  
    /**
     * If the quietConflictWarnings property is set to
     * true, warnings about pattern conflicts won't be
     * printed to the diagnostics stream.
     * True by default.
     * @param b true if conflict warnings should be suppressed.
     */
    public void setQuietConflictWarnings(boolean b)
    {
      m_quietConflictWarnings = b;
    }
  
    /**
     * The liason to the XML parser, so the XSL processor
     * can handle included files, and the like, and do the
     * initial parse of the XSL document.
     */
    private XPathContext m_xcontext;
    
    /**
     * Set the execution context for XPath.
     */
    public void setXPathContext(XPathContext xcontext)
    {
      m_xcontext = xcontext;
    }
  
    /**
     * Get the XML Parser Liaison that this processor uses.
     */
    public XPathContext getXPathContext()
    {
      return m_xcontext;
    }
  
    /**
     * Object to guard agains infinite recursion when
     * doing queries.
     */
    private StackGuard m_stackGuard = new StackGuard();
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the object used to guard the stack from 
     * recursion.
     */
    public StackGuard getStackGuard()
    {  
      return m_stackGuard;
    }  
    
    /**
     * Get the recursion limit.
     * Used for infinite loop check. If the value is -1, do not
     * check for infinite loops. Anyone who wants to enable that 
     * check should change the value of this variable to be the
     * level of recursion that they want to check. Be careful setting 
     * this variable, if the number is too low, it may report an 
     * infinite loop situation, when there is none.
     * Post version 1.0.0, we'll make this a runtime feature.   
     */
    public int getRecursionLimit()
    {
      return m_stackGuard.getRecursionLimit();
    }
    
    /**
     * Get the recursion limit.
     * Used for infinite loop check. If the value is -1, do not
     * check for infinite loops. Anyone who wants to enable that 
     * check should change the value of this variable to be the
     * level of recursion that they want to check. Be careful setting 
     * this variable, if the number is too low, it may report an 
     * infinite loop situation, when there is none.
     * Post version 1.0.0, we'll make this a runtime feature.   
     */
    public void setRecursionLimit(int limit)
    {
      m_stackGuard.setRecursionLimit(limit);
    }
  
  
    /**
     * Output handler to bottleneck SAX events.
     */
    private ResultTreeHandler m_resultTreeHandler = new ResultTreeHandler(this);
    
    /**
     * Get the ResultTreeHandler object.
     */
    public ResultTreeHandler getResultTreeHandler()
    {
      return m_resultTreeHandler;
    }
    
    private KeyManager m_keyManager = new KeyManager();
    
    /**
     * Get the KeyManager object.
     */
    public KeyManager getKeyManager()
    {
      return m_keyManager;
    }
  
    /**
     * Stack for the purposes of flagging infinite recursion with
     * attribute sets.
     */
    private Stack m_attrSetStack = null;
    
    /**
     * Check to see if this is a recursive attribute definition.
     */
    public boolean isRecursiveAttrSet(ElemAttributeSet attrSet)
    {
      if(null == m_attrSetStack)
      {
        m_attrSetStack = new Stack();
      }
      if(!m_attrSetStack.empty())
      {
        int loc = m_attrSetStack.search(this);
        if(loc > -1)
        {
          return true;
        }
      }
      return false;
    }
    
    /**
     * Push an executing attribute set, so we can check for 
     * recursive attribute definitions.
     */
    public void pushElemAttributeSet(ElemAttributeSet attrSet)
    {
      m_attrSetStack.push(attrSet);
    }
    
    /**
     * Pop the current executing attribute set.
     */
    public void popElemAttributeSet()
    {
      m_attrSetStack.pop();
    }
    
  
    /**
     * The table of counters for xsl:number support.
     * @see ElemNumber
     */
    private CountersTable m_countersTable = null;
    
    /**
     * Get the table of counters, for optimized xsl:number support.
     */
    public CountersTable getCountersTable()
    {
      if(null == m_countersTable)
        m_countersTable = new CountersTable();
      return m_countersTable;
    }
  
    /**
     * Is > 0 when we're processing a for-each
     */
    private BoolStack m_currentTemplateRuleIsNull = new BoolStack();
    
    /**
     * Tell if the current template rule is null.
     */
    public boolean currentTemplateRuleIsNull()
    {
      return ((!m_currentTemplateRuleIsNull.isEmpty()) 
              && (m_currentTemplateRuleIsNull.peek() == true));
    }
    
    /**
     * Push true if the current template rule is null, false 
     * otherwise.
     */
    public void pushCurrentTemplateRuleIsNull(boolean b)
    {
      m_currentTemplateRuleIsNull.push(b);
    }
    
    /**
     * Push true if the current template rule is null, false 
     * otherwise.
     */
    public void popCurrentTemplateRuleIsNull()
    {
      m_currentTemplateRuleIsNull.pop();
    }
    
    private MsgMgr m_msgMgr;
    
    /**
     * Return the message manager.
     */
    public MsgMgr getMsgMgr()
    {
      if(null == m_msgMgr)
        m_msgMgr = new MsgMgr(this);
      return m_msgMgr;
    }
    
    /**
     * This is a compile-time flag to turn off calling 
     * of trace listeners. Set this to false for optimization purposes.
     */
    public static final boolean S_DEBUG = true;
    
    /**
     * The trace manager.
     */
    private TraceManager m_traceManager = new TraceManager(this);
    
    /**
     * Get an instance of the trace manager for this transformation. 
     * This object can be used to set trace listeners on various 
     * events during the transformation.
     */
    public TraceManager getTraceManager()
    {
      return m_traceManager;
    }
  
    
  
  } // end TransformerImpl class
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/TreeWalker2Result.java
  
  Index: TreeWalker2Result.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  
  import org.apache.xalan.utils.TreeWalker;
  import org.apache.xalan.utils.MutableAttrListImpl;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.xpath.DOMHelper;
  
  /**
   * <meta name="usage" content="internal"/>
   * Handle a walk of a tree, but screen out attributes for 
   * the result tree.
   */
  public class TreeWalker2Result extends TreeWalker
  {
    TransformerImpl m_transformer;
    ElemTemplateElement m_elem;
    ResultTreeHandler m_handler;
    Node m_startNode;
    
    /**
     * Constructor.
     */
    public TreeWalker2Result(TransformerImpl transformer, 
                             ResultTreeHandler handler, ElemTemplateElement 
elem) 
    {
      super(handler);
      m_transformer = transformer;
      m_elem = elem;
      m_handler = handler;
    }
    
      
    /**
     * Perform a pre-order traversal non-recursive style.
     */
    public void traverse(Node pos) throws SAXException 
    {
      m_startNode = pos;
      super.traverse(pos);
    }
    
    protected void startNode(Node node)
      throws SAXException 
    {
      if((Node.ELEMENT_NODE == node.getNodeType()) && (m_startNode == node))
      {
        DOMHelper dhelper = m_transformer.getXPathContext().getDOMHelper();
        String elemName = node.getNodeName();
        String localName = dhelper.getLocalNameOfNode(node);
        String namespace = dhelper.getNamespaceOfNode(node);
        m_handler.startElement (namespace, localName, elemName);
          
        for(Node parent = node; parent != null; parent = parent.getParentNode())
        {
          if(Node.ELEMENT_NODE != parent.getNodeType())
            continue;
        
          NamedNodeMap atts = ((Element)parent).getAttributes();
  
          int n = atts.getLength();
          for(int i = 0; i < n; i++)
          {
            String nsDeclPrefix = null;
            Attr attr = (Attr)atts.item(i);
            String name = attr.getName();
            String value = attr.getValue();
            
            if (name.startsWith("xmlns:"))
            {
              // get the namespace prefix 
              nsDeclPrefix = name.substring(name.indexOf(":") + 1);
            }
            else if(name.equals("xmlns"))
            {
              nsDeclPrefix="";
            }
            
            if((nsDeclPrefix == null) && (node != parent))
              continue;
            /*
            else if(nsDeclPrefix != null)
            {
              String desturi = m_processor.getURI(nsDeclPrefix);
              // Look for an alias for this URI. If one is found, use it as the 
result URI   
              String aliasURI = m_elem.m_stylesheet.lookForAlias(value);
              if(aliasURI.equals(desturi)) // TODO: Check for extension 
namespaces
              {
                continue;
              }
            }
            */
            m_handler.addAttribute(dhelper.getNamespaceOfNode(attr),
                                   dhelper.getLocalNameOfNode(attr),
                                   name, "CDATA", value);
            // Make sure namespace is not in the excluded list then
            // add to result tree
            /*
            if(!m_handler.getPendingAttributes().contains(name))
            {
              if(nsDeclPrefix == null)
              {  
                m_handler.addAttribute(name, "CDATA", value);
              }
              else
              {
                String desturi 
                  = m_handler.getURI(nsDeclPrefix);
                if(null == desturi)
                {
                  m_handler.addAttribute(name, "CDATA", value);
                }
                else if(!desturi.equals(value))
                {
                  m_handler.addAttribute(name, "CDATA", value);
                }
              }
            }
            */
          }
  
        }
        // m_handler.processResultNS(m_elem);           
        
      }
      else
      {
        super.startNode(node);
      }
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/transformer/XSLInfiniteLoopException.java
  
  Index: XSLInfiniteLoopException.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.transformer;
  
  class XSLInfiniteLoopException
  {
    XSLInfiniteLoopException()
    {
      super();
    }
  
    public String getMessage()
    {
      return "Processing Terminated.";
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/AttList.java
  
  Index: AttList.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  
  
  /**
   * <meta name="usage" content="internal"/>
   * Wraps a DOM attribute list in a SAX Attributes.
   */
  public class AttList implements Attributes
  {
    NamedNodeMap m_attrs;
    int m_lastIndex;
    
    public AttList(NamedNodeMap attrs)
    {
      m_attrs = attrs;
      m_lastIndex = m_attrs.getLength() - 1;
    }
    
    public int getLength ()
    {
      return m_attrs.getLength();
    }
    
    /**
     * Look up an attribute's Namespace URI by index.
     *
     * @param index The attribute index (zero-based).
     * @return The Namespace URI, or the empty string if none
     *         is available, or null if the index is out of
     *         range.
     */
    public String getURI (int index)
    {
          return null;
    }
  
    /**
     * Look up an attribute's local name by index.
     *
     * @param index The attribute index (zero-based).
     * @return The local name, or the empty string if Namespace
     *         processing is not being performed, or null
     *         if the index is out of range.
     */
    public String getLocalName (int index)
    {
          return null;
    }
  
    public String getQName (int i)
    {
      return ((Attr)m_attrs.item(i)).getName();
    }
    
    public String getType (int i)
    {
      return "CDATA";  // for the moment
    }
    
    public String getValue (int i)
    {
      return ((Attr)m_attrs.item(i)).getValue();
    }
    
    public String getType (String name)
    {
      return "CDATA";  // for the moment
    }
    
    /**
     * Look up an attribute's type by Namespace name.
     *
     * @param uri The Namespace URI, or the empty String if the
     *        name has no Namespace URI.
     * @param localName The local name of the attribute.
     * @return The attribute type as a string, or null if the
     *         attribute is not in the list or if Namespace
     *         processing is not being performed.
     */
    public String getType (String uri, String localName)
    {
      return "CDATA";  // for the moment
    }
  
    
    public String getValue (String name)
    {
      return ((Attr)m_attrs.getNamedItem(name)).getValue();
    }
    
    /**
     * Look up an attribute's value by Namespace name.
     *
     * @param uri The Namespace URI, or the empty String if the
     *        name has no Namespace URI.
     * @param localName The local name of the attribute.
     * @return The attribute value as a string, or null if the
     *         attribute is not in the list.
     */
    public String getValue (String uri, String localName)
    {
      return ((Attr)m_attrs.getNamedItem(localName)).getValue();
    }
    
    /**
     * Look up the index of an attribute by Namespace name.
     *
     * @param uri The Namespace URI, or the empty string if
     *        the name has no Namespace URI.
     * @param localName The attribute's local name.
     * @return The index of the attribute, or -1 if it does not
     *         appear in the list.
     */
    public int getIndex (String uri, String localPart)
    {
      return 0;
    }
  
  
    /**
     * Look up the index of an attribute by raw XML 1.0 name.
     *
     * @param rawName The raw (prefixed) name.
     * @return The index of the attribute, or -1 if it does not
     *         appear in the list.
     */
    public int getIndex (String rawName)
    {
      return 0;
    }
    
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/BoolStack.java
  
  Index: BoolStack.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.util.EmptyStackException;
  
  /**
   * <meta name="usage" content="internal"/>
   * Simple stack for boolean values.
   */
  public final class BoolStack
  {
        private boolean m_values[];
        private int m_allocatedSize;
        private int m_index;
  
        /**
        * Default constructor.  Note that the default 
        * block size is very small, for small lists.
        */
        public BoolStack()
        {
                this(32);
        }
  
        /**
        * Construct a IntVector, using the given block size.
        */
        public BoolStack(int size)
        {
                m_allocatedSize = size;
                m_values = new boolean[size];
                m_index = -1; 
        }
  
        /**
        * Get the length of the list.
        */
        public int size()
        {
                return m_index+1;
        }
  
        /**
        * Pushes an item onto the top of this stack. 
        *
        * @param   i   the int to be pushed onto this stack.
        * @return  the <code>item</code> argument.
        */
        public boolean push(boolean val) 
        {
                if (m_index == m_allocatedSize-1)
                        grow();
  
                return (m_values[++m_index] = val);
        }
  
        /**
        * Removes the object at the top of this stack and returns that 
        * object as the value of this function. 
        *
        * @return     The object at the top of this stack.
        * @exception  EmptyStackException  if this stack is empty.
        */
        public boolean pop() 
        {
                try
                {
                        return m_values[m_index--];
                }
                catch (ArrayIndexOutOfBoundsException  e)
                {
                        throw new EmptyStackException();
                }
        }
  
        /**
        * Looks at the object at the top of this stack without removing it 
        * from the stack. 
        *
        * @return     the object at the top of this stack. 
        * @exception  EmptyStackException  if this stack is empty.
        */
        public boolean peek() 
        {
                try
                {
                        return m_values[m_index];
                }
                catch (ArrayIndexOutOfBoundsException  e)
                {
                        throw new EmptyStackException();
                }
        }
  
        /**
        * Tests if this stack is empty.
        *
        * @return  <code>true</code> if this stack is empty;
        *          <code>false</code> otherwise.
        */
        public boolean isEmpty() 
        {
                return (m_index == -1);
        }
  
        /**
        * Grows the size of the stack
        *
        */
  
        private void grow()
        {
                m_allocatedSize*=2;
  
                boolean newVector [] = new boolean[m_allocatedSize];
                System.arraycopy(m_values, 0 , newVector, 0, m_index+1);
  
                m_values = newVector;
        }
  }
  
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/DOMBuilder.java
  
  Index: DOMBuilder.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.util.Stack;
  
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  import org.xml.sax.ext.LexicalHandler;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.SAXException;
  import org.xml.sax.Locator;
  import org.xml.sax.Attributes;
  
  import org.w3c.dom.*; // we pretty much use everything in the DOM here.
  
  /**
   * <meta name="usage" content="general"/>
   * This class takes SAX events (in addition to some extra events 
   * that SAX doesn't handle yet) and adds the result to a document 
   * or document fragment.
   */
  public class DOMBuilder implements ContentHandler, LexicalHandler
  {
    Document m_doc;
    Node m_currentNode = null;
    public DocumentFragment m_docFrag = null;
    Stack m_elemStack = new Stack();
      
    /**
     * DOMBuilder instance constructor... it will add the DOM nodes 
     * to the document fragment.
     */
    public DOMBuilder(Document doc, Node node)
    {
      m_doc = doc;
      m_currentNode = node;
    }
  
    /**
     * DOMBuilder instance constructor... it will add the DOM nodes 
     * to the document fragment.
     */
    public DOMBuilder(Document doc, DocumentFragment docFrag)
    {
      m_doc = doc;
      m_docFrag = docFrag;
    }
  
    /**
     * DOMBuilder instance constructor... it will add the DOM nodes 
     * to the document.
     */
    public DOMBuilder(Document doc)
    {
      m_doc = doc;
    }
    
    /**
     * Get the root node of the DOM being created.  This 
     * is either a Document or a DocumentFragment.
     */
    public Node getRootNode()
    {
      return (null != m_docFrag) ? (Node)m_docFrag : (Node)m_doc;
    }
    
    /**
     * Return null since there is no Writer for this class.
     */
    public java.io.Writer getWriter()
    {
      return null;
    }
  
    /**
     * Append a node to the current container.
     */
    private void append(Node newNode)
      throws SAXException
    {
      if(null != m_currentNode)
      {
        m_currentNode.appendChild(newNode);
        // System.out.println(newNode.getNodeName());
      }
      else if(null != m_docFrag)
      {
        m_docFrag.appendChild(newNode);
      }
      else
      {
        boolean ok = true;
        int type = newNode.getNodeType();
        if(type == Node.TEXT_NODE)
        {
          String data = newNode.getNodeValue();
          if((null != data) && (data.trim().length() > 0))
          {
            throw new 
SAXException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CANT_OUTPUT_TEXT_BEFORE_DOC,
 null)); //"Warning: can't output text before document element!  Ignoring...");
          }
          ok = false;
        }
        else if(type == Node.ELEMENT_NODE)
        {
          if(m_doc.getDocumentElement() != null)
          {
            throw new 
SAXException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CANT_HAVE_MORE_THAN_ONE_ROOT,
 null)); //"Can't have more than one root on a DOM!");
          }
        }
        if(ok)
          m_doc.appendChild(newNode);
      }
    }
    
    /**
     * Receive an object for locating the origin of SAX document events.
     *
     * <p>SAX parsers are strongly encouraged (though not absolutely
     * required) to supply a locator: if it does so, it must supply
     * the locator to the application by invoking this method before
     * invoking any of the other methods in the ContentHandler
     * interface.</p>
     *
     * <p>The locator allows the application to determine the end
     * position of any document-related event, even if the parser is
     * not reporting an error.  Typically, the application will
     * use this information for reporting its own errors (such as
     * character content that does not match an application's
     * business rules).  The information returned by the locator
     * is probably not sufficient for use with a search engine.</p>
     *
     * <p>Note that the locator will return correct information only
     * during the invocation of the events in this interface.  The
     * application should not attempt to use it at any other time.</p>
     *
     * @param locator An object that can return the location of
     *                any SAX document event.
     * @see org.xml.sax.Locator
     */
    public void setDocumentLocator (Locator locator)
    {
      // No action for the moment.
    }
  
    /**
     * Receive notification of the beginning of a document.
     *
     * <p>The SAX parser will invoke this method only once, before any
     * other methods in this interface or in DTDHandler (except for
     * setDocumentLocator).</p>
     *
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void startDocument ()
      throws SAXException
    {
      // No action for the moment.
    }
  
  
    /**
     * Receive notification of the end of a document.
     *
     * <p>The SAX parser will invoke this method only once, and it will
     * be the last method invoked during the parse.  The parser shall
     * not invoke this method until it has either abandoned parsing
     * (because of an unrecoverable error) or reached the end of
     * input.</p>
     *
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void endDocument ()
      throws SAXException
    {
      // No action for the moment.
    }
  
  
    /**
     * Receive notification of the beginning of an element.
     *
     * <p>The Parser will invoke this method at the beginning of every
     * element in the XML document; there will be a corresponding
     * endElement() event for every startElement() event (even when the
     * element is empty). All of the element's content will be
     * reported, in order, before the corresponding endElement()
     * event.</p>
     *
     * <p>If the element name has a namespace prefix, the prefix will
     * still be attached.  Note that the attribute list provided will
     * contain only attributes with explicit values (specified or
     * defaulted): #IMPLIED attributes will be omitted.</p>
     *
     * @param name The element type name.
     * @param atts The attributes attached to the element, if any.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #endElement
     * @see org.xml.sax.Attributes 
     */
    public void startElement (String ns, String localName, 
                              String name, Attributes atts)
      throws SAXException
    {
      Element elem = m_doc.createElement(name);
      append(elem); 
      int nAtts = atts.getLength();       
      for(int i = 0; i < nAtts; i++)
      {
        elem.setAttribute(atts.getQName(i), atts.getValue(i));
      }
      m_elemStack.push(elem);
      m_currentNode = elem;
    }
    
    /**
     * Receive notification of the end of an element.
     *
     * <p>The SAX parser will invoke this method at the end of every
     * element in the XML document; there will be a corresponding
     * startElement() event for every endElement() event (even when the
     * element is empty).</p>
     *
     * <p>If the element name has a namespace prefix, the prefix will
     * still be attached to the name.</p>
     *
     * @param name The element type name
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void endElement (String ns, String localName,
                            String name)
      throws SAXException
    {
      m_elemStack.pop();
      if(!m_elemStack.isEmpty())
      {
        m_currentNode = (Element)m_elemStack.peek();
      }
      else
      {
        m_currentNode = null;
      }
    }
  
    /**
     * Receive notification of character data.
     *
     * <p>The Parser will call this method to report each chunk of
     * character data.  SAX parsers may return all contiguous character
     * data in a single chunk, or they may split it into several
     * chunks; however, all of the characters in any single event
     * must come from the same external entity, so that the Locator
     * provides useful information.</p>
     *
     * <p>The application must not attempt to read from the array
     * outside of the specified range.</p>
     *
     * <p>Note that some parsers will report whitespace using the
     * ignorableWhitespace() method rather than this one (validating
     * parsers must do so).</p>
     *
     * @param ch The characters from the XML document.
     * @param start The start position in the array.
     * @param length The number of characters to read from the array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #ignorableWhitespace 
     * @see org.xml.sax.Locator
     */
    public void characters (char ch[], int start, int length)
      throws SAXException
    {
      if(m_inCData)
      {
        cdata (ch, start, length);
        return;
      }
  
      String s = new String(ch, start, length);
      Text text = m_doc.createTextNode(s);
      append(text);
    }
  
    /**
     * If available, when the disable-output-escaping attribute is used, 
     * output raw text without escaping.  A PI will be inserted in front 
     * of the node with the name "lotusxsl-next-is-raw" and a value of
     * "formatter-to-dom".
     */
    public void charactersRaw (char ch[], int start, int length)
      throws SAXException
    {
      String s = new String(ch, start, length);
      append(m_doc.createProcessingInstruction("xslt-next-is-raw", 
"formatter-to-dom"));
      append(m_doc.createTextNode(s));
    }
    
    /**
     * Report the beginning of an entity.
     *
     * The start and end of the document entity are not reported.
     * The start and end of the external DTD subset are reported
     * using the pseudo-name "[dtd]".  All other events must be
     * properly nested within start/end entity events.
     *
     * @param name The name of the entity.  If it is a parameter
     *        entity, the name will begin with '%'.
     * @exception SAXException The application may raise an exception.
     * @see #endEntity
     * @see org.xml.sax.misc.DeclHandler#internalEntityDecl
     * @see org.xml.sax.misc.DeclHandler#externalEntityDecl
     */
    public void startEntity (String name)
      throws SAXException
    {
      // Almost certainly the wrong behavior...
      // entityReference(name);
    }
  
    /**
     * Report the end of an entity.
     *
     * @param name The name of the entity that is ending.
     * @exception SAXException The application may raise an exception.
     * @see #startEntity
     */
    public void endEntity (String name)
      throws SAXException
    {
    }
  
    /**
     * Receive notivication of a entityReference.
     */
    public void entityReference(String name)
      throws SAXException
    {
      append(m_doc.createEntityReference(name));
    }
  
    /**
     * Receive notification of ignorable whitespace in element content.
     *
     * <p>Validating Parsers must use this method to report each chunk
     * of ignorable whitespace (see the W3C XML 1.0 recommendation,
     * section 2.10): non-validating parsers may also use this method
     * if they are capable of parsing and using content models.</p>
     *
     * <p>SAX parsers may return all contiguous whitespace in a single
     * chunk, or they may split it into several chunks; however, all of
     * the characters in any single event must come from the same
     * external entity, so that the Locator provides useful
     * information.</p>
     *
     * <p>The application must not attempt to read from the array
     * outside of the specified range.</p>
     *
     * @param ch The characters from the XML document.
     * @param start The start position in the array.
     * @param length The number of characters to read from the array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #characters
     */
    public void ignorableWhitespace (char ch[], int start, int length)
      throws SAXException
    {
      String s = new String(ch, start, length);
      append(m_doc.createTextNode(s));
    }
  
  
    /**
     * Receive notification of a processing instruction.
     *
     * <p>The Parser will invoke this method once for each processing
     * instruction found: note that processing instructions may occur
     * before or after the main document element.</p>
     *
     * <p>A SAX parser should never report an XML declaration (XML 1.0,
     * section 2.8) or a text declaration (XML 1.0, section 4.3.1)
     * using this method.</p>
     *
     * @param target The processing instruction target.
     * @param data The processing instruction data, or null if
     *        none was supplied.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void processingInstruction (String target, String data)
      throws SAXException
    {
      append(m_doc.createProcessingInstruction(target, data));
   }
    
    /**
     * Report an XML comment anywhere in the document.
     *
     * This callback will be used for comments inside or outside the
     * document element, including comments in the external DTD
     * subset (if read).
     *
     * @param ch An array holding the characters in the comment.
     * @param start The starting position in the array.
     * @param length The number of characters to use from the array.
     * @exception SAXException The application may raise an exception.
     */
    public void comment(char ch[], int start, int length) throws SAXException
    {
      append( m_doc.createComment(new String(ch, start, length)) );
    }  
    
    protected boolean m_inCData = false;
    
    /**
     * Report the start of a CDATA section.
     *
     * @exception SAXException The application may raise an exception.
     * @see #endCDATA
     */
    public void startCDATA ()
      throws SAXException
    {
      m_inCData = true;
    }
  
    /**
     * Report the end of a CDATA section.
     *
     * @exception SAXException The application may raise an exception.
     * @see #startCDATA
     */
    public void endCDATA ()
      throws SAXException
    {
      m_inCData = false;
    }
    
    /**
     * Receive notification of cdata.
     *
     * <p>The Parser will call this method to report each chunk of
     * character data.  SAX parsers may return all contiguous character
     * data in a single chunk, or they may split it into several
     * chunks; however, all of the characters in any single event
     * must come from the same external entity, so that the Locator
     * provides useful information.</p>
     *
     * <p>The application must not attempt to read from the array
     * outside of the specified range.</p>
     *
     * <p>Note that some parsers will report whitespace using the
     * ignorableWhitespace() method rather than this one (validating
     * parsers must do so).</p>
     *
     * @param ch The characters from the XML document.
     * @param start The start position in the array.
     * @param length The number of characters to read from the array.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see #ignorableWhitespace 
     * @see org.xml.sax.Locator
     */
    public void cdata (char ch[], int start, int length)
      throws SAXException
    {
      String s = new String(ch, start, length);
      append(m_doc.createCDATASection(s));
    }
    
    /**
     * Report the start of DTD declarations, if any.
     *
     * Any declarations are assumed to be in the internal subset
     * unless otherwise indicated.
     *
     * @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.
     * @exception SAXException The application may raise an
     *            exception.
     * @see #endDTD
     * @see #startEntity
     */
    public void startDTD (String name, String publicId,
                                   String systemId)
      throws SAXException
    {
      // Do nothing for now.
    }
  
    /**
     * Report the end of DTD declarations.
     *
     * @exception SAXException The application may raise an exception.
     * @see #startDTD
     */
    public void endDTD ()
      throws SAXException
    {
      // Do nothing for now.
    }
  
    /**
     * Begin the scope of a prefix-URI Namespace mapping.
     *
     * <p>The information from this event is not necessary for
     * normal Namespace processing: the SAX XML reader will 
     * automatically replace prefixes for element and attribute
     * names when the http://xml.org/sax/features/namespaces
     * feature is true (the default).</p>
     *
     * <p>There are cases, however, when applications need to
     * use prefixes in character data or in attribute values,
     * where they cannot safely be expanded automatically; the
     * start/endPrefixMapping event supplies the information
     * to the application to expand prefixes in those contexts
     * itself, if necessary.</p>
     *
     * <p>Note that start/endPrefixMapping events are not
     * guaranteed to be properly nested relative to each-other:
     * all startPrefixMapping events will occur before the
     * corresponding startElement event, and all endPrefixMapping
     * events will occur after the corresponding endElement event,
     * but their order is not guaranteed.</p>
     *
     * @param prefix The Namespace prefix being declared.
     * @param uri The Namespace URI the prefix is mapped to.
     * @exception org.xml.sax.SAXException The client may throw
     *            an exception during processing.
     * @see #endPrefixMapping
     * @see #startElement
     */
    public void startPrefixMapping (String prefix, String uri)
          throws SAXException
    {
    }
  
    /**
     * End the scope of a prefix-URI mapping.
     *
     * <p>See startPrefixMapping for details.  This event will
     * always occur after the corresponding endElement event,
     * but the order of endPrefixMapping events is not otherwise
     * guaranteed.</p>
     *
     * @param prefix The prefix that was being mapping.
     * @exception org.xml.sax.SAXException The client may throw
     *            an exception during processing.
     * @see #startPrefixMapping
     * @see #endElement
     */
    public void endPrefixMapping (String prefix)
          throws SAXException
    {
    }
    
    /**
     * Receive notification of a skipped entity.
     *
     * <p>The Parser will invoke this method once for each entity
     * skipped.  Non-validating processors may skip entities if they
     * have not seen the declarations (because, for example, the
     * entity was declared in an external DTD subset).  All processors
     * may skip external entities, depending on the values of the
     * http://xml.org/sax/features/external-general-entities and the
     * http://xml.org/sax/features/external-parameter-entities
     * properties.</p>
     *
     * @param name The name of the skipped entity.  If it is a 
     *        parameter entity, the name will begin with '%'.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     */
    public void skippedEntity (String name)
          throws SAXException
    {
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/DefaultErrorHandler.java
  
  Index: DefaultErrorHandler.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import org.xml.sax.*;
  
  /**
   * <meta name="usage" content="general"/>
   * Implement SAX error handler for default reporting.
   */
  public class DefaultErrorHandler implements ErrorHandler 
  {
    String m_xmlID = null;
  
    public DefaultErrorHandler(String identifier)
    {
      m_xmlID = identifier;
    }
  
    /**
     * Receive notification of a warning.
     *
     * <p>SAX parsers will use this method to report conditions that
     * are not errors or fatal errors as defined by the XML 1.0
     * recommendation.  The default behaviour is to take no action.</p>
     *
     * <p>The SAX parser must continue to provide normal parsing events
     * after invoking this method: it should still be possible for the
     * application to process the document through to the end.</p>
     *
     * @param exception The warning information encapsulated in a
     *                  SAX parse exception.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.SAXParseException 
     */
    public void warning (SAXParseException exception)
      throws SAXException
    {
      System.out.println("Parser warning: "+exception.getMessage());
    }
  
  
    /**
     * Receive notification of a recoverable error.
     *
     * <p>This corresponds to the definition of "error" in section 1.2
     * of the W3C XML 1.0 Recommendation.  For example, a validating
     * parser would use this callback to report the violation of a
     * validity constraint.  The default behaviour is to take no
     * action.</p>
     *
     * <p>The SAX parser must continue to provide normal parsing events
     * after invoking this method: it should still be possible for the
     * application to process the document through to the end.  If the
     * application cannot do so, then the parser should report a fatal
     * error even if the XML 1.0 recommendation does not require it to
     * do so.</p>
     *
     * @param exception The error information encapsulated in a
     *                  SAX parse exception.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.SAXParseException 
     */
    public void error (SAXParseException exception)
      throws SAXException
    {
      System.out.println("Parser error: "+exception.getMessage());
    }
  
    /**
     * Receive notification of a non-recoverable error.
     *
     * <p>This corresponds to the definition of "fatal error" in
     * section 1.2 of the W3C XML 1.0 Recommendation.  For example, a
     * parser would use this callback to report the violation of a
     * well-formedness constraint.</p>
     *
     * <p>The application must assume that the document is unusable
     * after the parser has invoked this method, and should continue
     * (if at all) only for the sake of collecting addition error
     * messages: in fact, SAX parsers are free to stop reporting any
     * other events once this method has been invoked.</p>
     *
     * @param exception The error information encapsulated in a
     *                  SAX parse exception.  
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @see org.xml.sax.SAXParseException
     */
    public void fatalError (SAXParseException exception)
      throws SAXException
    {
      // System.out.println("Parser fatal error: "+exception.getMessage());
      String id = (exception.getPublicId() != exception.getPublicId()) 
                  ? exception.getPublicId() : (null != exception.getSystemId()) 
                                              ? exception.getSystemId() : 
m_xmlID;
      System.out.println(id+"; Line "+exception.getLineNumber()
                         +"; Column "+exception.getColumnNumber());
      throw exception;
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/ElemDesc.java
  
  Index: ElemDesc.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.util.Hashtable;
  
  /**
   * <meta name="usage" content="internal"/>
   * This class is in support of FormatterToHTML, and acts as a sort 
   * of element representative for HTML elements.
   */
  class ElemDesc
  {
    int m_flags;
    Hashtable m_attrs = null;
    
    static final int EMPTY = (1 << 1);
    static final int FLOW = (1 << 2);
    static final int BLOCK = (1 << 3);
    static final int BLOCKFORM = (1 << 4);
    static final int BLOCKFORMFIELDSET = (1 << 5);
    static final int CDATA = (1 << 6);
    static final int PCDATA = (1 << 7);
    static final int RAW = (1 << 8);
    static final int INLINE = (1 << 9);
    static final int INLINEA = (1 << 10);
    static final int INLINELABEL = (1 << 11);
    static final int FONTSTYLE = (1 << 12);
    static final int PHRASE = (1 << 13);
    static final int FORMCTRL = (1 << 14);
    static final int SPECIAL = (1 << 15);
    static final int ASPECIAL = (1 << 16);
    static final int HEADMISC = (1 << 17);
    static final int HEAD = (1 << 18);
    static final int LIST = (1 << 19);
    static final int PREFORMATTED = (1 << 20);
    static final int WHITESPACESENSITIVE = (1 << 21);
  
    static final int ATTRURL = (1 << 1);
    static final int ATTREMPTY = (1 << 2);
  
    ElemDesc(int flags)
    {
      m_flags = flags;
    }
    
    boolean is(int flags)
    {
      // int which = (m_flags & flags);
      return (m_flags & flags) != 0;
    }
    
    void setAttr(String name, int flags)
    {
      if(null == m_attrs)
        m_attrs = new Hashtable();
      
      m_attrs.put(name, new Integer(flags));
    }
    
    boolean isAttrFlagSet(String name, int flags)
    {
      if(null != m_attrs)
      {
        Integer _flags = (Integer)m_attrs.get(name);
        if(null != _flags)
        {
          return (_flags.intValue() & flags) != 0;
        }
      }
      return false;
    }
    
    
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/Heap.java
  
  Index: Heap.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2000 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.util.Vector;
  
  public class Heap extends Vector
  {
    private HeapObject m_a[] = new HeapObject[50];
    private int m_n;
    
    public Heap()
    {
    }
    
    public void insert(HeapObject obj)
    {
      m_n++;
      m_a[m_n] = obj;
      upheap(m_n);
    }
      
    private void upheap(int k)
    {
      HeapObject v = m_a[k]; 
      m_a[0] = m_sentinel;
      while (m_a[k/2].getHeapValue() < v.getHeapValue()) 
      {
        m_a[k] = m_a[k/2];
        k = k/2;
      }
      m_a[k] = v;
    }
    
    public HeapObject remove()
    {
      HeapObject v = m_a[1];
      m_a[1] = m_a[m_n--];
      downheap(1);
      return v;
    }
    
    private void downheap(int k)
    {
      HeapObject v = m_a[k];
      while (k <= m_n/2) 
      {
        int j = k+k;
        if (j < m_n && m_a[j].getHeapValue() < m_a[j+1].getHeapValue()) 
          j++;
        if (v.getHeapValue() >= m_a[j].getHeapValue()) 
          break;
        m_a[k] = m_a[j]; k = j;
      }
      m_a[k] = v;
    }
     
    HeapObject replace(HeapObject v)
    {
      m_a[0] = v;
      downheap(0);
      return m_a[0];
    }
    
    void change()
    {
    }
    
    void delete()
    {
    }
    
    class Sentinel implements HeapObject
    {
      public int getHeapValue()
      {
        return Short.MAX_VALUE;
      }
    }
    
    final Sentinel m_sentinel = new Sentinel();
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/HeapObject.java
  
  Index: HeapObject.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2000 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  public interface HeapObject
  {
    int getHeapValue();
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/IntStack.java
  
  Index: IntStack.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.util.EmptyStackException;
  
  /**
   * <meta name="usage" content="internal"/>
   * Implement an array of simple integers.
   */
  public class IntStack extends IntVector
  {
    /**
     * Default constructor.  Note that the default 
     * block size is very small, for small lists.
     */
    public IntStack()
    {
      super(); 
    }
  
    /**
     * Construct a IntVector, using the given block size.
     */
    public IntStack(int blocksize)
    {
      super(blocksize); 
    }
    
    /**
     * Pushes an item onto the top of this stack. 
     *
     * @param   i   the int to be pushed onto this stack.
     * @return  the <code>item</code> argument.
     * @since   JDK1.0
     */
    public int push(int i) 
    {
      addElement(i);
  
      return i;
    }
  
    /**
     * Removes the object at the top of this stack and returns that 
     * object as the value of this function. 
     *
     * @return     The object at the top of this stack.
     * @exception  EmptyStackException  if this stack is empty.
     * @since      JDK1.0
     */
    public int pop() 
    {
      int       i;
      int       len = size();
  
      i = peek();
      removeElementAt(len - 1);
  
      return i;
    }
  
  /**
     * Quickly pops a number of items from the stack. 
     *
     * @exception  EmptyStackException  if this stack is empty.
     */
    public void quickPop(int n) 
    {
      m_firstFree -= n;
    }
  
  
    /**
     * Looks at the object at the top of this stack without removing it 
     * from the stack. 
     *
     * @return     the object at the top of this stack. 
     * @exception  EmptyStackException  if this stack is empty.
     * @since      JDK1.0
     */
    public int peek() 
    {
      int       len = size();
  
      if (len == 0)
        throw new EmptyStackException();
      return elementAt(len - 1);
    }
  
  /**
     * Sets an object at a the top of the statck 
     *
     * @exception  EmptyStackException  if this stack is empty.
     * @since      JDK1.0
     */
    public void setTop(int val) 
    {
      int       len = size();
      if (len == 0)
        throw new EmptyStackException();
    setElementAt(val, len - 1);
    }
  
    /**
     * Tests if this stack is empty.
     *
     * @return  <code>true</code> if this stack is empty;
     *          <code>false</code> otherwise.
     * @since   JDK1.0
     */
    public boolean empty() 
    {
      return size() == 0;
    }
  
    /**
     * Returns where an object is on this stack. 
     *
     * @param   o   the desired object.
     * @return  the distance from the top of the stack where the object is]
     *          located; the return value <code>-1</code> indicates that the
     *          object is not on the stack.
     * @since   JDK1.0
     */
    public int search(int o) 
    {
      int i = lastIndexOf(o);
  
      if (i >= 0) 
      {
        return size() - i;
      }
      return -1;
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/IntVector.java
  
  Index: IntVector.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="internal"/>
   * A very simple table that stores a list of int.
   */
  public class IntVector
  {
    private int m_blocksize;
    public int m_map[];  // expose to package for direct access.
    protected int m_firstFree = 0;
    private int m_mapSize;
  
    /**
     * Default constructor.  Note that the default 
     * block size is very small, for small lists.
     */
    public IntVector()
    {
      m_blocksize = 32;
      m_mapSize = m_blocksize;
      m_map = new int[m_blocksize]; 
    }
  
    /**
     * Construct a IntVector, using the given block size.
     */
    public IntVector(int blocksize)
    {
      m_blocksize = blocksize;
      m_mapSize = blocksize;
      m_map = new int[blocksize]; 
    }
    
    /**
     * Get the length of the list.
     */
    public final int size()
    {
      return m_firstFree;
    }
  
    /**
     * Append a int onto the vector.
     */
    public final void addElement(int value)
    {
      if((m_firstFree+1) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        int newMap[] = new int[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      m_map[m_firstFree] = value;
      m_firstFree++;
    }
  
    /**
     * Inserts the specified node in this vector at the specified index. 
     * Each component in this vector with an index greater or equal to 
     * the specified index is shifted upward to have an index one greater 
     * than the value it had previously. 
     */
    public final void insertElementAt(int value, int at)
    {
      if((m_firstFree+1) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        int newMap[] = new int[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      if(at <= (m_firstFree-1))
      {
        System.arraycopy(m_map, at, m_map, at+1, m_firstFree-at);
      }
      m_map[at] = value;
      m_firstFree++;
    }
  
    /**
     * Inserts the specified node in this vector at the specified index. 
     * Each component in this vector with an index greater or equal to 
     * the specified index is shifted upward to have an index one greater 
     * than the value it had previously. 
     */
    public final void removeAllElements()
    {
      for(int i = 0; i < m_firstFree; i++)
      {
        m_map[i] = java.lang.Integer.MIN_VALUE;
      }
      m_firstFree = 0;
    }
    
    /**
     * Removes the first occurrence of the argument from this vector. 
     * If the object is found in this vector, each component in the vector 
     * with an index greater or equal to the object's index is shifted 
     * downward to have an index one smaller than the value it had 
     * previously. 
     */
    public final boolean removeElement(int s)
    {
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i] == s)
        {
          if((i+1) < m_firstFree)
            System.arraycopy(m_map, i+1, m_map, i-1, m_firstFree-i);
          else
            m_map[i] = java.lang.Integer.MIN_VALUE;
          m_firstFree--;
          return true;
        }
      }
      return false;
    }
    
    /**
     * Deletes the component at the specified index. Each component in 
     * this vector with an index greater or equal to the specified 
     * index is shifted downward to have an index one smaller than 
     * the value it had previously. 
     */
    public final void removeElementAt(int i)
    {
      if(i > m_firstFree)
        System.arraycopy(m_map, i+1, m_map, i, m_firstFree);
      else
        m_map[i] = java.lang.Integer.MIN_VALUE;
      m_firstFree--;
    }
    
    /**
     * Sets the component at the specified index of this vector to be the 
     * specified object. The previous component at that position is discarded. 
     * 
     * The index must be a value greater than or equal to 0 and less 
     * than the current size of the vector. 
     */
    public final void setElementAt(int node, int index)
    {
      m_map[index] = node;
    }
  
    /**
     * Get the nth element.
     */
    public final int elementAt(int i)
    {
      return m_map[i];
    }
    
    /**
     * Tell if the table contains the given node.
     */
    public final boolean contains(int s)
    {
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i] == s)
          return true;
      }
      return false;
    }
    
    /**
     * Searches for the first occurence of the given argument, 
     * beginning the search at index, and testing for equality 
     * using the equals method. 
     * @return the index of the first occurrence of the object 
     * argument in this vector at position index or later in the 
     * vector; returns -1 if the object is not found. 
     */
    public final int indexOf(int elem, int index)
    {
      for(int i = index; i < m_firstFree; i++)
      {
        if(m_map[i] == elem)
          return i;
      }
      return java.lang.Integer.MIN_VALUE;
    }
  
    /**
     * Searches for the first occurence of the given argument, 
     * beginning the search at index, and testing for equality 
     * using the equals method. 
     * @return the index of the first occurrence of the object 
     * argument in this vector at position index or later in the 
     * vector; returns -1 if the object is not found. 
     */
    public final int indexOf(int elem)
    {
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i] == elem)
          return i;
      }
      return java.lang.Integer.MIN_VALUE;
    }
  
    /**
     * Searches for the first occurence of the given argument, 
     * beginning the search at index, and testing for equality 
     * using the equals method. 
     * @return the index of the first occurrence of the object 
     * argument in this vector at position index or later in the 
     * vector; returns -1 if the object is not found. 
     */
    public final int lastIndexOf(int elem)
    {
      for(int i = (m_firstFree - 1); i >= 0; i--)
      {
        if(m_map[i] == elem)
          return i;
      }
      return java.lang.Integer.MIN_VALUE;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/MutableAttrListImpl.java
  
  Index: MutableAttrListImpl.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import org.apache.xalan.utils.StringVector;
  import org.xml.sax.Attributes;
  import java.io.Serializable;
  import org.xml.sax.helpers.AttributesImpl;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Implement the SAX Attributes interface, using a single array.
   */
  public class MutableAttrListImpl extends AttributesImpl 
    implements Serializable
  {
  /**
     * Construct a new, empty AttributesImpl object.
     */
    public MutableAttrListImpl ()
    {
      super();
    }
  
  
    /**
     * Copy an existing Attributes object.
     *
     * <p>This constructor is especially useful inside a start
     * element event.</p>
     *
     * @param atts The existing Attributes object.
     */
    public MutableAttrListImpl (Attributes atts)
    {
      super(atts);
    }
    
    /**
     * Add an attribute to the end of the list.
     *
     * <p>For the sake of speed, this method does no checking
     * to see if the attribute is already in the list: that is
     * the responsibility of the application.</p>
     *
     * @param uri The Namespace URI, or the empty string if
     *        none is available or Namespace processing is not
     *        being performed.
     * @param localName The local name, or the empty string if
     *        Namespace processing is not being performed.
     * @param qName The qualified (prefixed) name, or the empty string
     *        if qualified names are not available.
     * @param type The attribute type as a string.
     * @param value The attribute value.
     */
    public void addAttribute (String uri, String localName, String qName,
                              String type, String value)
    {
      if(null == uri)
        uri = "";
  
      int index = this.getIndex(uri, localName);
      if(index >= 0)
        this.setAttribute(index, uri, localName, qName, type, value);
      else
        super.addAttribute(uri, localName, qName, type, value);
    }
    
    /**
     * Add the contents of the attribute list to this list.
     */
    public void addAttributes(Attributes atts)
    {    
      int nAtts = atts.getLength();
      for(int i = 0; i < nAtts; i++)
      {
        String uri = atts.getURI(i);
        if(null == uri)
          uri = "";
        String localName = atts.getLocalName(i);
        String qname = atts.getQName(i);
        int index = this.getIndex(uri, localName);
        if(index >= 0)
          this.setAttribute(index, uri, localName, qname, 
                            atts.getType(i), atts.getValue(i));
        else
          addAttribute(uri, localName, qname, 
                       atts.getType(i),
                       atts.getValue(i));
      }
    }
    
    /**
     * Return true if list contains the given (raw) attribute name.
     */
    public boolean contains(String name)
    {
      return getValue (name) != null;
    }
  
  }
  
  // end of MutableAttrListImpl.java
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/NSInfo.java
  
  Index: NSInfo.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="internal"/>
   * This class holds information about the namespace info
   * of a node.  It is used to optimize namespace lookup in 
   * a generic DOM.
   */
  public class NSInfo
  {
    public NSInfo(boolean hasProcessedNS, boolean hasXMLNSAttrs)
    {
      m_hasProcessedNS = hasProcessedNS;
      m_hasXMLNSAttrs = hasXMLNSAttrs;
      m_namespace = null;
      m_ancestorHasXMLNSAttrs = ANCESTORXMLNSUNPROCESSED;
    }
  
    // Unused at the moment
    public NSInfo(boolean hasProcessedNS, boolean hasXMLNSAttrs, int 
ancestorHasXMLNSAttrs)
    {
      m_hasProcessedNS = hasProcessedNS;
      m_hasXMLNSAttrs = hasXMLNSAttrs;
      m_ancestorHasXMLNSAttrs = ancestorHasXMLNSAttrs;
      m_namespace = null;
    }
  
    public NSInfo(String namespace, boolean hasXMLNSAttrs)
    {
      m_hasProcessedNS = true;
      m_hasXMLNSAttrs = hasXMLNSAttrs;
      m_namespace = namespace;
      m_ancestorHasXMLNSAttrs = ANCESTORXMLNSUNPROCESSED;
    }
  
    public String m_namespace;
    public boolean m_hasXMLNSAttrs;
    public boolean m_hasProcessedNS;
    public int m_ancestorHasXMLNSAttrs;
    
    public static final int ANCESTORXMLNSUNPROCESSED = 0;
    public static final int ANCESTORHASXMLNS = 1;
    public static final int ANCESTORNOXMLNS = 2;
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/NameSpace.java
  
  Index: NameSpace.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.io.Serializable;
  
  /**
   * <meta name="usage" content="advanced"/>
   * A representation of a namespace.  One of these will 
   * be pushed on the namespace stack for each
   * element.
   */
  public class NameSpace implements Serializable
  {
    public NameSpace m_next = null;
    public String m_prefix;
    public String m_uri; // if null, then Element namespace is empty.
    
    /**
     * Construct a namespace for placement on the 
     * result tree namespace stack.
     */
    public NameSpace(String prefix, String uri)
    {
      m_prefix = prefix;
      m_uri = uri;
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/NodeVector.java
  
  Index: NodeVector.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.io.Serializable;
  import org.w3c.dom.Node;
  
  /**
   * <meta name="usage" content="internal"/>
   * A very simple table that stores a list of Nodes.
   */
  public class NodeVector implements Serializable, Cloneable
  {
    private int m_blocksize;
    private Node m_map[];
    protected int m_firstFree = 0;
    private int m_mapSize; // lazy initialization
  
    /**
     * Default constructor.
     */
    public NodeVector()
    {
      m_blocksize = 32;
      m_mapSize = 0;
    }
  
    /**
     * Construct a NodeVector, using the given block size.
     */
    public NodeVector(int blocksize)
    {
      m_blocksize = blocksize;
      m_mapSize = 0;
    }
    
    /**
     * Get a cloned LocPathIterator.
     */
    public Object clone()
      throws CloneNotSupportedException
    {
      NodeVector clone = (NodeVector)super.clone();
      if((null != this.m_map) && (this.m_map == clone.m_map))
      {
        clone.m_map = new Node[this.m_map.length];
        System.arraycopy(this.m_map, 0, clone.m_map, 0, this.m_map.length);
      }
      return clone;
    }
    
    /**
     * Get the length of the list.
     */
    public int size()
    {
      return m_firstFree;
    }
  
    /**
     * Append a Node onto the vector.
     */
    public void addElement(Node value)
    {
      if(null == m_map)
      {
        m_map = new Node[m_blocksize];
        m_mapSize = m_blocksize;
      }
      else if((m_firstFree+1) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        Node newMap[] = new Node[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      m_map[m_firstFree] = value;
      m_firstFree++;
    }
  
    /**
     * Inserts the specified node in this vector at the specified index. 
     * Each component in this vector with an index greater or equal to 
     * the specified index is shifted upward to have an index one greater 
     * than the value it had previously. 
     */
    public void insertElementAt(Node value, int at)
    {
      if(null == m_map)
      {
        m_map = new Node[m_blocksize];
        m_mapSize = m_blocksize;
      }
      else if((m_firstFree+1) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        Node newMap[] = new Node[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      if(at <= (m_firstFree-1))
      {
        System.arraycopy(m_map, at, m_map, at+1, m_firstFree-at);
      }
      m_map[at] = value;
      m_firstFree++;
    }
    
    /**
     * Append the nodes to the list. 
     */
    public void appendNodes(NodeVector nodes)
    {
      int nNodes = nodes.size();
      if(null == m_map)
      {
        m_mapSize = nNodes+m_blocksize;
        m_map = new Node[m_mapSize];
      }
      else if((m_firstFree+nNodes) >= m_mapSize)
      {
        m_mapSize+=(nNodes+m_blocksize);
        Node newMap[] = new Node[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+nNodes);
        m_map = newMap;
      }
      System.arraycopy(nodes.m_map, 0, m_map, m_firstFree, nNodes);
      m_firstFree += nNodes;
    }
  
  
    /**
     * Inserts the specified node in this vector at the specified index. 
     * Each component in this vector with an index greater or equal to 
     * the specified index is shifted upward to have an index one greater 
     * than the value it had previously. 
     */
    public void removeAllElements()
    {
      if(null == m_map)
        return;
      for(int i = 0; i < m_firstFree; i++)
      {
        m_map[i] = null;
      }
      m_firstFree = 0;
    }
    
    /**
     * Removes the first occurrence of the argument from this vector. 
     * If the object is found in this vector, each component in the vector 
     * with an index greater or equal to the object's index is shifted 
     * downward to have an index one smaller than the value it had 
     * previously. 
     */
    public boolean removeElement(Node s)
    {
      if(null == m_map)
        return false;
      
      for(int i = 0; i < m_firstFree; i++)
      {
        Node node = m_map[i];
        if((null != node) && node.equals(s))
        {
          if(i > m_firstFree)
            System.arraycopy(m_map, i+1, m_map, i-1, m_firstFree-i);
          else
            m_map[i] = null;
          m_firstFree--;
          return true;
        }
      }
      return false;
    }
    
    /**
     * Deletes the component at the specified index. Each component in 
     * this vector with an index greater or equal to the specified 
     * index is shifted downward to have an index one smaller than 
     * the value it had previously. 
     */
    public void removeElementAt(int i)
    {
      if(null == m_map)
        return;
      
      if(i > m_firstFree)
        System.arraycopy(m_map, i+1, m_map, i-1, m_firstFree-i);
      else
        m_map[i] = null;
    }
    
    /**
     * Sets the component at the specified index of this vector to be the 
     * specified object. The previous component at that position is discarded. 
     * 
     * The index must be a value greater than or equal to 0 and less 
     * than the current size of the vector. 
     */
    public void setElementAt(Node node, int index)
    {
      if(null == m_map)
      {
        m_map = new Node[m_blocksize];
        m_mapSize = m_blocksize;
      }
      m_map[index] = node;
    }
  
    /**
     * Get the nth element.
     */
    public Node elementAt(int i)
    {
      if(null == m_map)
        return null;
      
      return m_map[i];
    }
    
    /**
     * Tell if the table contains the given node.
     */
    public boolean contains(Node s)
    {
      if(null == m_map)
        return false;
      for(int i = 0; i < m_firstFree; i++)
      {
        Node node = m_map[i];
        if((null != node) && node.equals(s))
          return true;
      }
      return false;
    }
    
    /**
     * Searches for the first occurence of the given argument, 
     * beginning the search at index, and testing for equality 
     * using the equals method. 
     * @return the index of the first occurrence of the object 
     * argument in this vector at position index or later in the 
     * vector; returns -1 if the object is not found. 
     */
    public int indexOf(Node elem, int index)
    {
      if(null == m_map)
        return -1;
      
      for(int i = index; i < m_firstFree; i++)
      {
        Node node = m_map[i];
        if((null != node) && node.equals(elem))
          return i;
      }
      return -1;
    }
  
    /**
     * Searches for the first occurence of the given argument, 
     * beginning the search at index, and testing for equality 
     * using the equals method. 
     * @return the index of the first occurrence of the object 
     * argument in this vector at position index or later in the 
     * vector; returns -1 if the object is not found. 
     */
    public int indexOf(Node elem)
    {
      if(null == m_map)
        return -1;
      
      for(int i = 0; i < m_firstFree; i++)
      {
        Node node = m_map[i];
        if((null != node) && node.equals(elem))
          return i;
      }
      return -1;
    }
  
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/ObjectPool.java
  
  Index: ObjectPool.java
  ===================================================================
  package org.apache.xalan.utils;
  
  import java.lang.*;
  import java.util.*;
  
  public class ObjectPool
  {
    private final Class objectType;
    private final Vector freeStack;
  
    public ObjectPool(Class type) {
      objectType = type;
      freeStack = new Vector();
    }
  
    public ObjectPool(Class type, int size) {
      objectType = type;
      freeStack = new Vector(size);
    }
  
    public synchronized Object getInstance() {
  
      // Check if the pool is empty.
      if (freeStack.isEmpty()) {
  
        // Create a new object if so.
        try {
          return objectType.newInstance();
        } catch (InstantiationException ex) {}
          catch (IllegalAccessException ex) {}
  
        // Throw unchecked exception for error in pool configuration.
        throw new RuntimeException("exception creating new instance for pool");
  
      } else {
  
        // Remove object from end of free pool.
        Object result = freeStack.lastElement();
        freeStack.setSize(freeStack.size() - 1);
        return result;
      }
    }
  
    public synchronized void freeInstance(Object obj) {
  
      // Make sure the object is of the correct type.
      if (objectType.isInstance(obj)) {
        freeStack.addElement(obj);
      } else {
        throw new IllegalArgumentException("argument type invalid for pool");
      }
    }
  }
  
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/PrefixResolver.java
  
  Index: PrefixResolver.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This class that implements this interface can resolve prefixes 
   * to namespaces.
   */
  public interface PrefixResolver
  {
    /**
     * Given a namespace, get the corrisponding prefix.  This assumes that 
     * the PrevixResolver hold's it's own namespace context, or is a namespace
     * context itself.
     */
    String getNamespaceForPrefix(String prefix);
  
    /**
     * Given a namespace, get the corrisponding prefix.
     */
    String getNamespaceForPrefix(String prefix, org.w3c.dom.Node context);
    
    /** 
     * Return the base identifier.
     */
    public String getBaseIdentifier();
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/PrefixResolverDefault.java
  
  Index: PrefixResolverDefault.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.NamedNodeMap;
  
  /**
   * <meta name="usage" content="general"/>
   * This class implements a generic PrefixResolver that 
   * can be used to perform prefix-to-namespace lookup 
   * for the XPath object.
   */
  public class PrefixResolverDefault implements PrefixResolver
  {
    /**
     * The context to resolve the prefix from, if the context 
     * is not given.
     */
    Node m_context;
    
    /**
     * The URI for the XML namespace.
     * (Duplicate of that found in org.apache.xalan.xpath.XPathContext).
     */
    public static final String S_XMLNAMESPACEURI = 
"http://www.w3.org/XML/1998/namespace";;
  
    
    /**
     * Construct a PrefixResolverDefault object.
     * @param xpathExpressionContext The context from 
     * which XPath expression prefixes will be resolved.
     * Warning: This will not work correctly if xpathExpressionContext 
     * is an attribute node.
     * @param xpathExpressionContext Node from which to start searching for a 
     * xmlns attribute that binds a prefix to a namespace (when the namespace 
     * context is not specified in the getNamespaceForPrefix call).
     */
    public PrefixResolverDefault(Node xpathExpressionContext)
    {
      m_context = xpathExpressionContext;
    }
    
    /**
     * Given a namespace, get the corrisponding prefix.  This assumes that 
     * the PrevixResolver hold's it's own namespace context, or is a namespace
     * context itself.
     * @param prefix Prefix to resolve.
     * @return Namespace that prefix resolves to, or null if prefix 
     * is not bound.
     */
    public String getNamespaceForPrefix(String prefix)
    {
      return getNamespaceForPrefix(prefix, m_context);
    }
  
    /**
     * Given a namespace, get the corrisponding prefix.
     * Warning: This will not work correctly if namespaceContext 
     * is an attribute node.
     * @param prefix Prefix to resolve.
     * @param namespaceContext Node from which to start searching for a 
     * xmlns attribute that binds a prefix to a namespace.
     * @return Namespace that prefix resolves to, or null if prefix 
     * is not bound.
     */
    public String getNamespaceForPrefix(String prefix, org.w3c.dom.Node 
namespaceContext)
    {
      Node parent = namespaceContext;
      String namespace = null;
      if(prefix.equals("xml"))
      {
        namespace = S_XMLNAMESPACEURI;
      }
      else
      {
       int type;
       while ((null != parent) && (null == namespace)
               && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
                   || (type == Node.ENTITY_REFERENCE_NODE))) 
        {
          if (type == Node.ELEMENT_NODE) 
          {
            NamedNodeMap nnm = parent.getAttributes();
            for (int i = 0;  i < nnm.getLength();  i ++) 
            {
              Node attr = nnm.item(i);
              String aname = attr.getNodeName();
              boolean isPrefix = aname.startsWith("xmlns:");
              if (isPrefix || aname.equals("xmlns")) 
              {
                int index = aname.indexOf(':');
                String p = isPrefix ? aname.substring(index+1) : "";
                if (p.equals(prefix)) 
                {
                  namespace = attr.getNodeValue();
                  break;
                }
              }
            }
          }
          parent = parent.getParentNode();
        }
      }
      return namespace;
    }
    
    /** 
     * Return the base identifier.
     */
    public String getBaseIdentifier()
    {
      return null;
    }  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/QName.java
  
  Index: QName.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.util.Stack;
  
  import org.w3c.dom.Element;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.res.XSLMessages;
  
  /**
   * <meta name="usage" content="general"/>
   * Class to represent a qualified name: "The name of an internal XSLT object, 
   * specifically a named template (see [7 Named Templates]), a mode (see [6.7 
Modes]), 
   * an attribute set (see [8.1.4 Named Attribute Sets]), a key (see [14.2 
Keys]), 
   * a locale (see [14.3 Number Formatting]), a variable or a parameter (see 
   * [12 Variables and Parameters]) is specified as a QName. If it has a 
prefix, 
   * then the prefix is expanded into a URI reference using the namespace 
declarations 
   * in effect on the attribute in which the name occurs. The expanded name 
   * consisting of the local part of the name and the possibly null URI 
reference 
   * is used as the name of the object. The default namespace is not used for 
   * unprefixed names."
   */
  public class QName implements java.io.Serializable
  {
    /**
     * The XML namespace.
     */
    public static final String S_XMLNAMESPACEURI = 
"http://www.w3.org/XML/1998/namespace";;
    
    /**
     * The namespace, which may be null.
     */
    private String m_namespace;
    
    /**
     * Get the namespace of the qualified name.
     */
    public String getNamespace()
    {
      return m_namespace;
    }
    
    /**
     * The local name.
     */
    private String m_localpart;
    
    /**
     * Get the local part of the qualified name.
     */
    public String getLocalPart()
    {
      return m_localpart;
    }
  
    /**
     * The cached hashcode, which is calculated at construction time.
     */
    private int m_hashCode;
    
    /**
     * Return the cached hashcode of the qualified name.
     */
    public int hashCode()
    {
      return m_hashCode;
    }
    
    /**
     * Override equals and agree that we're equal if 
     * the passed object is a string and it matches 
     * the name of the arg.
     */
    public boolean equals(Object obj)
    {
      if(obj instanceof QName)
      {
        QName qname = (QName)obj;
        return m_localpart.equals(qname.m_localpart) 
               && (((null != m_namespace) && (null != qname.m_namespace)) 
               ? m_namespace.equals(qname.m_namespace)
                 : ((null == m_namespace) && (null == qname.m_namespace)));
      }
            
      return false;
    }
    
    /**
     * Override equals and agree that we're equal if 
     * the passed object is a string and it matches 
     * the name of the arg.
     */
    public boolean equals(String ns, String localPart)
    {
        return m_localpart.equals(localPart) 
               && (((null != m_namespace) && (null != ns)) 
               ? m_namespace.equals(ns)
                 : ((null == m_namespace) && (null == ns)));
    }
  
  
    /**
     * Override equals and agree that we're equal if 
     * the passed object is a QName and it matches 
     * the name of the arg.
     */
    public boolean equals(QName qname)
    {
      return m_localpart.equals(qname.m_localpart) 
             && (((null != m_namespace) && (null != qname.m_namespace)) 
             ? m_namespace.equals(qname.m_namespace)
               : ((null == m_namespace) && (null == qname.m_namespace)));
    }
    
    /**
     * Construct a QName from a string, without namespace resolution.  Good 
     * for a few odd cases.
     */
    public QName(String localName)
    {
      m_namespace = null;
      
      m_localpart = localName;
      m_hashCode = toString().hashCode();
    }
    
    /**
     * Construct a QName from a namespace and a local name.
     */
    public QName(String ns, String localName)
    {
      m_namespace = ns;
      
      m_localpart = localName;
      m_hashCode = toString().hashCode();
    }
    
    /**
     * This function tells if a raw attribute name is a 
     * xmlns attribute.
     */
    public static boolean isXMLNSDecl(String attRawName)
    {
      return (attRawName.startsWith("xmlns") && 
              (attRawName.equals("xmlns") ||
               attRawName.startsWith("xmlns:")));
    }
  
    /**
     * This function tells if a raw attribute name is a 
     * xmlns attribute.
     */
    public static String getPrefixFromXMLNSDecl(String attRawName)
    {
      int index = attRawName.indexOf(':');
      return (index >= 0) ? attRawName.substring(0, index) : "";
    }
  
    /**
     * Returns the local name of the given node.
     */
    public static String getLocalPart(String qname)
    {
      int index = qname.indexOf(':');
      return (index < 0) ? qname : qname.substring(index+1);
    }
  
    /**
     * Returns the local name of the given node.
     */
    public static String getPrefixPart(String qname)
    {
      int index = qname.indexOf(':');
      return (index >= 0) ? qname.substring(0, index) : "";
    }
    
    /**
     * Construct a QName from a string, resolving the prefix 
     * using the given namespace stack. The default namespace is 
     * not resolved.
     */
    public QName(String qname, Stack namespaces)
    {
      m_namespace = null;
  
      int indexOfNSSep = qname.indexOf(':');
      if(indexOfNSSep > 0)
      {
        String prefix = qname.substring(0, indexOfNSSep);
        if(prefix.equals("xml"))
        {
          m_namespace = S_XMLNAMESPACEURI;
        }
        else if(prefix.equals("xmlns"))
        {
          return;
        }
        else
        {
          int depth = namespaces.size();
          for(int i = depth-1; i >= 0; i--)
          {
            NameSpace ns = (NameSpace)namespaces.elementAt(i);
            while(null != ns)
            {
              if((null != ns.m_prefix) && prefix.equals(ns.m_prefix))
              {
                m_namespace = ns.m_uri;
                i = -1;
                break;
              }
              ns = ns.m_next;
            }
          }
        }  
        if(null == m_namespace)
        {
          throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_PREFIX_MUST_RESOLVE,
 new Object[]{prefix})); //"Prefix must resolve to a namespace: "+prefix);
        }
      }
      m_localpart = (indexOfNSSep < 0) ? qname : 
qname.substring(indexOfNSSep+1);
      m_hashCode = toString().hashCode();
    }
    
    /**
     * Construct a QName from a string, resolving the prefix 
     * using the given namespace stack. The default namespace is 
     * not resolved.
     */
    public QName(String qname, Element namespaceContext, PrefixResolver 
resolver)
    {
      m_namespace = null;
  
      int indexOfNSSep = qname.indexOf(':');
      if(indexOfNSSep > 0)
      {
        if(null != namespaceContext)
        {
          String prefix = qname.substring(0, indexOfNSSep);
          if(prefix.equals("xml"))
          {
            m_namespace = S_XMLNAMESPACEURI;
          }
          else
          {
            m_namespace = resolver.getNamespaceForPrefix(prefix, 
namespaceContext);
          }  
          if(null == m_namespace)
          {
            throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_PREFIX_MUST_RESOLVE,
 new Object[]{prefix})); //"Prefix must resolve to a namespace: "+prefix);
          }
        }
        else
        {
          // TODO: error or warning...
        }
      }
      
      m_localpart = (indexOfNSSep < 0) ? qname : 
qname.substring(indexOfNSSep+1);
      m_hashCode = toString().hashCode();
    }
    
    /**
     * Construct a QName from a string, resolving the prefix 
     * using the given namespace stack. The default namespace is 
     * not resolved.
     */
    public QName(String qname, PrefixResolver resolver)
    {
      m_namespace = null;
  
      int indexOfNSSep = qname.indexOf(':');
      if(indexOfNSSep > 0)
      {
        String prefix = qname.substring(0, indexOfNSSep);
        if(prefix.equals("xml"))
        {
          m_namespace = S_XMLNAMESPACEURI;
        }
        else
        {
          m_namespace = resolver.getNamespaceForPrefix(prefix);
        }  
        if(null == m_namespace)
        {
          throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_PREFIX_MUST_RESOLVE,
 new Object[]{prefix})); //"Prefix must resolve to a namespace: "+prefix);
        }
      }
      
      m_localpart = (indexOfNSSep < 0) ? qname : 
qname.substring(indexOfNSSep+1);
      m_hashCode = toString().hashCode();
    }
    
    /**
     * Return the string representation of the namespace. Performs 
     * string concatenation, so beware of performance issues.
     */
    public String toString()
    {
      return (null != this.m_namespace) 
             ? (this.m_namespace + ":" + this.m_localpart) 
               : this.m_localpart;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/RawCharacterHandler.java
  
  Index: RawCharacterHandler.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="advanced"/>
   * An interface that a Serializer/ContentHandler/ContentHandler must 
   * implement in order for disable-output-escaping to work.
   */
  public interface RawCharacterHandler
  {
    /**
     * Serialize the characters without escaping.
     */
    public void charactersRaw (char ch[], int start, int length)
      throws org.xml.sax.SAXException;
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/StringKey.java
  
  Index: StringKey.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="internal"/>
   * Simple class for fast lookup of string values, when used with 
   * hashtables.  This class caches the hash value of the string.
   */
  public class StringKey extends Object
  {
    private String m_str;
    int m_hash;
      
    public StringKey(String key)
    {
      m_str = key;
      m_hash = key.hashCode();
    }
    
    public int hashCode()
    {
      return m_hash;
    }
    
    public final boolean equals(Object obj)
    {
      return obj.equals(m_str);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/StringToIntTable.java
  
  Index: StringToIntTable.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="internal"/>
   * A very simple lookup table that stores a list of strings, the even 
   * number strings being keys, and the odd number strings being values.
   */
  public class StringToIntTable
  {
    private int m_blocksize;
    private String m_map[];
    private int m_values[];
    private int m_firstFree = 0;
    private int m_mapSize;
  
    /**
     * Default constructor.  Note that the default 
     * block size is very small, for small lists.
     */
    public StringToIntTable()
    {
      m_blocksize = 8;
      m_mapSize = m_blocksize;
      m_map = new String[m_blocksize]; 
      m_values = new int[m_blocksize]; 
    }
  
    /**
     * Construct a StringToIntTable, using the given block size.
     */
    public StringToIntTable(int blocksize)
    {
      m_blocksize = blocksize;
      m_mapSize = blocksize;
      m_map = new String[blocksize]; 
      m_values = new int[m_blocksize]; 
    }
    
    /**
     * Get the length of the list.
     */
    public final int getLength()
    {
      return m_firstFree;
    }
  
    /**
     * Append a string onto the vector.
     */
    public final void put(String key, int value)
    {
      if((m_firstFree+1) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        String newMap[] = new String[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
  
        int newValues[] = new int[m_mapSize];
        System.arraycopy(m_values, 0, newValues, 0, m_firstFree+1);
        m_values = newValues;
      }
      m_map[m_firstFree] = key;
      m_values[m_firstFree] = value;
      m_firstFree++;
    }
    
    /**
     * Tell if the table contains the given string.
     */
    public final int get(String key)
    {
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i].equals(key))
          return m_values[i];
      }
      return -10000;  // Bogus value, needs to throw exception.
    }
    
  
    /**
     * Tell if the table contains the given string.
     */
    public final int getIgnoreCase(String key)
    {
      if(null == key)
        return -10000;  // Bogus value, needs to throw exception.
      
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i].equalsIgnoreCase(key))
          return m_values[i];
      }
      return -10000;  // Bogus value, needs to throw exception.
    }
    
    /**
     * Tell if the table contains the given string.
     */
    public final boolean contains(String key)
    {
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i].equals(key))
          return true;
      }
      return false;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/StringToStringTable.java
  
  Index: StringToStringTable.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="internal"/>
   * A very simple lookup table that stores a list of strings, the even 
   * number strings being keys, and the odd number strings being values.
   */
  public class StringToStringTable
  {
    private int m_blocksize;
    private String m_map[];
    private int m_firstFree = 0;
    private int m_mapSize;
  
    /**
     * Default constructor.  Note that the default 
     * block size is very small, for small lists.
     */
    public StringToStringTable()
    {
      m_blocksize = 16;
      m_mapSize = m_blocksize;
      m_map = new String[m_blocksize]; 
    }
  
    /**
     * Construct a StringToStringTable, using the given block size.
     */
    public StringToStringTable(int blocksize)
    {
      m_blocksize = blocksize;
      m_mapSize = blocksize;
      m_map = new String[blocksize]; 
    }
    
    /**
     * Get the length of the list.
     */
    public final int getLength()
    {
      return m_firstFree;
    }
  
    /**
     * Append a string onto the vector.
     */
    public final void put(String key, String value)
    {
      if((m_firstFree+2) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        String newMap[] = new String[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      m_map[m_firstFree] = key;
      m_firstFree++;
      m_map[m_firstFree] = value;
      m_firstFree++;
    }
    
    /**
     * Tell if the table contains the given string.
     */
    public final String get(String key)
    {
      for(int i = 0; i < m_firstFree; i+=2)
      {
        if(m_map[i].equals(key))
          return m_map[i+1];
      }
      return null;
    }
    
    /**
     * Tell if the table contains the given string.
     */
    public final void remove(String key)
    {
      for(int i = 0; i < m_firstFree; i+=2)
      {
        if(m_map[i].equals(key))
        {
          if((i+2) < m_firstFree)
            System.arraycopy(m_map, i+2, m_map, i, m_firstFree-(i+2));
          m_firstFree -= 2;
          m_map[m_firstFree] = null;
          m_map[m_firstFree+1] = null;
          break;
        }
      }
    }
  
  
    /**
     * Tell if the table contains the given string.
     */
    public final String getIgnoreCase(String key)
    {
      if(null == key)
        return null;
      
      for(int i = 0; i < m_firstFree; i+=2)
      {
        if(m_map[i].equalsIgnoreCase(key))
          return m_map[i+1];
      }
      return null;
    }
  
    /**
     * Tell if the table contains the given string in the value.
     */
    public final String getByValue(String val)
    {
      for(int i = 1; i < m_firstFree; i+=2)
      {
        if(m_map[i].equals(val))
          return m_map[i-1];
      }
      return null;
    }
  
    
    /**
     * Get the nth element.
     */
    public final String elementAt(int i)
    {
      return m_map[i];
    }
    
    /**
     * Tell if the table contains the given string.
     */
    public final boolean contains(String key)
    {
      for(int i = 0; i < m_firstFree; i+=2)
      {
        if(m_map[i].equals(key))
          return true;
      }
      return false;
    }
  
    /**
     * Tell if the table contains the given string.
     */
    public final boolean containsValue(String val)
    {
      for(int i = 1; i < m_firstFree; i+=2)
      {
        if(m_map[i].equals(val))
          return true;
      }
      return false;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/StringToStringTableVector.java
  
  Index: StringToStringTableVector.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="internal"/>
   * A very simple table that stores a list of StringToStringTables, optimized 
   * for small lists.
   */
  public class StringToStringTableVector
  {
    private int m_blocksize;
    private StringToStringTable m_map[];
    private int m_firstFree = 0;
    private int m_mapSize;
  
    /**
     * Default constructor.  Note that the default 
     * block size is very small, for small lists.
     */
    public StringToStringTableVector()
    {
      m_blocksize = 8;
      m_mapSize = m_blocksize;
      m_map = new StringToStringTable[m_blocksize]; 
    }
  
    /**
     * Construct a StringToStringTableVector, using the given block size.
     */
    public StringToStringTableVector(int blocksize)
    {
      m_blocksize = blocksize;
      m_mapSize = blocksize;
      m_map = new StringToStringTable[blocksize]; 
    }
    
    /**
     * Get the length of the list.
     */
    public final int getLength()
    {
      return m_firstFree;
    }
  
    /**
     * Get the length of the list.
     */
    public final int size()
    {
      return m_firstFree;
    }
  
    /**
     * Append a string onto the vector.
     */
    public final void addElement(StringToStringTable value)
    {
      if((m_firstFree+1) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        StringToStringTable newMap[] = new StringToStringTable[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      m_map[m_firstFree] = value;
      m_firstFree++;
    }
    
    /**
     * Given a string, find the last added occurance value
     * that matches the key.
     */
    public final String get(String key)
    {
      for(int i=m_firstFree-1; i >= 0; --i)
      {
        String nsuri = m_map[i].get(key);
        if (nsuri != null)
          return nsuri;
      }
      return null;
    }
  
    /**
     * Given a string, find the last added occurance value
     * that matches the key.
     */
    public final boolean containsKey(String key)
    {
      for(int i=m_firstFree-1; i >= 0; --i)
      {
        if (m_map[i].get(key) != null)
          return true;
      }
      return false;
    }
  
    /**
     * Remove the last element.
     */
    public final void removeLastElem()
    {
      if(m_firstFree > 0)
      {
        m_map[m_firstFree] = null;
        m_firstFree--;
      }
    }
    
    /**
     * Get the nth element.
     */
    public final StringToStringTable elementAt(int i)
    {
      return m_map[i];
    }
    
    /**
     * Tell if the table contains the given string.
     */
    public final boolean contains(StringToStringTable s)
    {
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i].equals(s))
          return true;
      }
      return false;
    }
  
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/StringVector.java
  
  Index: StringVector.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="internal"/>
   * A very simple table that stores a list of strings, optimized 
   * for small lists.
   */
  public class StringVector
  {
    protected int m_blocksize;
    protected String m_map[];
    protected int m_firstFree = 0;
    protected int m_mapSize;
  
    /**
     * Default constructor.  Note that the default 
     * block size is very small, for small lists.
     */
    public StringVector()
    {
      m_blocksize = 8;
      m_mapSize = m_blocksize;
      m_map = new String[m_blocksize]; 
    }
  
    /**
     * Construct a StringVector, using the given block size.
     */
    public StringVector(int blocksize)
    {
      m_blocksize = blocksize;
      m_mapSize = blocksize;
      m_map = new String[blocksize]; 
    }
    
    /**
     * Get the length of the list.
     */
    public int getLength()
    {
      return m_firstFree;
    }
  
    /**
     * Get the length of the list.
     */
    public final int size()
    {
      return m_firstFree;
    }
  
    /**
     * Append a string onto the vector.
     */
    public final void addElement(String value)
    {
      if((m_firstFree+1) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        String newMap[] = new String[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      m_map[m_firstFree] = value;
      m_firstFree++;
    }
    
    /**
     * Get the nth element.
     */
    public final String elementAt(int i)
    {
      return m_map[i];
    }
    
    /**
     * Tell if the table contains the given string.
     */
    public final boolean contains(String s)
    {
      if(null == s)
        return false;
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i].equals(s))
          return true;
      }
      return false;
    }
  
    /**
     * Tell if the table contains the given string.
     */
    public final boolean containsIgnoreCase(String s)
    {
      if(null == s)
        return false;
      for(int i = 0; i < m_firstFree; i++)
      {
        if(m_map[i].equalsIgnoreCase(s))
          return true;
      }
      return false;
    }
  
    /**
     * Tell if the table contains the given string.
     */
    public final void push(String s)
    {
      if((m_firstFree+1) >= m_mapSize)
      {
        m_mapSize+=m_blocksize;
        String newMap[] = new String[m_mapSize];
        System.arraycopy(m_map, 0, newMap, 0, m_firstFree+1);
        m_map = newMap;
      }
      m_map[m_firstFree] = s;
      m_firstFree++;
    }
  
    /**
     * Tell if the table contains the given string.
     */
    public final String pop()
    {
      if(m_firstFree <= 0)
        return null;
      
      m_firstFree--;
      String s = m_map[m_firstFree];
      m_map[m_firstFree] = null;
      return s;
    }
  
    /**
     * Tell if the table contains the given string.
     */
    public final String peek()
    {
      return (m_firstFree <= 0) ? null : m_map[m_firstFree-1];
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/SystemIDResolver.java
  
  Index: SystemIDResolver.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import java.net.URL;
  import java.net.MalformedURLException;
  import java.io.File;
  import java.util.StringTokenizer;
  import org.xml.sax.SAXException;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  public class SystemIDResolver
  {
    /**
     * Take a user string and try and parse XML, and also return 
     * the url.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide 
     * the error condition is severe enough to halt processing.
     */
    public static URL getURLFromString(String urlString, String base)
      throws SAXException 
    {
      String origURLString = urlString;
      String origBase = base;
      
      // System.out.println("getURLFromString - urlString: "+urlString+", base: 
"+base);
      Object doc;
      URL url = null;
      int fileStartType = 0;
      try
      {
        
        if(null != base)
        {
          if(base.toLowerCase().startsWith("file:/"))
          {
            fileStartType = 1;
          }
          else if(base.toLowerCase().startsWith("file:"))
          {
            fileStartType = 2;
          }
        }
        
        boolean isAbsoluteURL;
        
        // From http://www.ics.uci.edu/pub/ietf/uri/rfc1630.txt
        // A partial form can be distinguished from an absolute form in that the
        // latter must have a colon and that colon must occur before any slash
        // characters. Systems not requiring partial forms should not use any
        // unencoded slashes in their naming schemes.  If they do, absolute URIs
        // will still work, but confusion may result.
        int indexOfColon = urlString.indexOf(':');
        int indexOfSlash = urlString.indexOf('/');
        if((indexOfColon != -1) && (indexOfSlash != -1) && (indexOfColon < 
indexOfSlash))
        {
          // The url (or filename, for that matter) is absolute.
          isAbsoluteURL = true;
        }
        else
        {
          isAbsoluteURL = false;
        }
        
        if(isAbsoluteURL || (null == base) || (base.length() == 0))
        {
          try 
          {
            url = new URL(urlString);
          }
          catch (MalformedURLException e) {}
        }
        // The Java URL handling doesn't seem to handle relative file names.
        else if(!((urlString.charAt(0) == '.') || (fileStartType > 0)))
        {
          try 
          {
            URL baseUrl = new URL(base);
            url = new URL(baseUrl, urlString);
          }
          catch (MalformedURLException e) 
          {
          }
        }
        
        if(null == url)
        {
          // Then we're going to try and make a file URL below, so strip 
          // off the protocol header.
          if(urlString.toLowerCase().startsWith("file:/"))
          {
            urlString = urlString.substring(6);
          }
          else if(urlString.toLowerCase().startsWith("file:"))
          {
            urlString = urlString.substring(5);
          }
        }
        
        if((null == url) && ((null == base) || (fileStartType > 0)))
        {
          if(1 == fileStartType)
          {
            if(null != base)
              base = base.substring(6);
            fileStartType = 1;
          }
          else if(2 == fileStartType)
          {
            if(null != base)
              base = base.substring(5);
            fileStartType = 2;
          }
          
          File f = new File(urlString);
          
          if(!f.isAbsolute() && (null != base))
          {
            // String dir = f.isDirectory() ? f.getAbsolutePath() : 
f.getParent();
            // System.out.println("prebuiltUrlString (1): "+base);
            StringTokenizer tokenizer = new StringTokenizer(base, "\\/");
            String fixedBase = null;
            while(tokenizer.hasMoreTokens())
            {
              String token = tokenizer.nextToken();
              if (null == fixedBase) 
              {
                // Thanks to Rick Maddy for the bug fix for UNIX here.
                if (base.charAt(0) == '\\' || base.charAt(0) == '/') 
                {
                  fixedBase = File.separator + token;
                }
                else 
                {
                  fixedBase = token;
                }
              }
              else 
              {
                fixedBase+= File.separator + token;
              }
            }
            // System.out.println("rebuiltUrlString (1): "+fixedBase);
            f = new File(fixedBase);
            String dir = f.isDirectory() ? f.getAbsolutePath() : f.getParent();
            // System.out.println("dir: "+dir);
            // System.out.println("urlString: "+urlString);
            // f = new File(dir, urlString);
            // System.out.println("f (1): "+f.toString());
            // urlString = f.getAbsolutePath();
            f = new File(urlString); 
            boolean isAbsolute =  f.isAbsolute() 
                                  || (urlString.charAt( 0 ) == '\\')
                                  || (urlString.charAt( 0 ) == '/');
            if(!isAbsolute)
            {
              // Getting more and more ugly...
              if(dir.charAt( dir.length()-1 ) != File.separator.charAt(0) && 
                 urlString.charAt( 0 ) != File.separator.charAt(0))
              {
                urlString = dir + File.separator + urlString;
              }
              else
              {
                urlString = dir + urlString;
              }
  
              // System.out.println("prebuiltUrlString (2): "+urlString);
              tokenizer = new StringTokenizer(urlString, "\\/");
              String rebuiltUrlString = null;
              while(tokenizer.hasMoreTokens())
              {
                String token = tokenizer.nextToken();
                if (null == rebuiltUrlString) 
                {
                  // Thanks to Rick Maddy for the bug fix for UNIX here.
                  if (urlString.charAt(0) == '\\' || urlString.charAt(0) == 
'/') 
                  {
                    rebuiltUrlString = File.separator + token;
                  }
                  else 
                  {
                    rebuiltUrlString = token;
                  }
                }
                else 
                {
                  rebuiltUrlString+= File.separator + token;
                }
              }
              // System.out.println("rebuiltUrlString (2): "+rebuiltUrlString);
              if(null != rebuiltUrlString)
                urlString = rebuiltUrlString;
            }
            // System.out.println("fileStartType: "+fileStartType);
            if(1 == fileStartType)
            {
              if (urlString.charAt(0) == '/') 
              {
                urlString = "file://"+urlString;
              }
              else
              {
                urlString = "file:/"+urlString;
              }
            }
            else if(2 == fileStartType)
            {
              urlString = "file:"+urlString;
            }
            try 
            {
              // System.out.println("Final before try: "+urlString);
              url = new URL(urlString);
            }
            catch (MalformedURLException e) 
            {
              // System.out.println("Error trying to make URL from "+urlString);
            }
          }
        }
        if(null == url)
        {
          // The sun java VM doesn't do this correctly, but I'll 
          // try it here as a second-to-last resort.
          if((null != origBase) && (origBase.length() > 0))
          {
            try 
            {
              URL baseURL = new URL(origBase);
              // System.out.println("Trying to make URL from "+origBase+" and 
"+origURLString);
              url = new URL(baseURL, origURLString);
              // System.out.println("Success! New URL is: "+url.toString());
            }
            catch (MalformedURLException e) 
            {
              // System.out.println("Error trying to make URL from "+origBase+" 
and "+origURLString);
            }
          }
          
          if(null == url)
          {
            try 
            {
              String lastPart;
              if(null != origBase)
              {
                File baseFile = new File(origBase);
                if(baseFile.isDirectory())
                {
                  lastPart = new File(baseFile, urlString).getAbsolutePath ();
                }
                else
                {
                  String parentDir = baseFile.getParent();
                  lastPart = new File(parentDir, urlString).getAbsolutePath ();
                }
              }
              else
              {
                lastPart = new File (urlString).getAbsolutePath ();
              }
              // Hack
              // if((lastPart.charAt(0) == '/') && (lastPart.charAt(2) == ':'))
              //   lastPart = lastPart.substring(1, lastPart.length() - 1);
              
              String fullpath;
              if (lastPart.charAt(0) == '\\' || lastPart.charAt(0) == '/') 
              {
                fullpath = "file://" + lastPart;
              }
              else
              {
                fullpath = "file:" + lastPart;
              }
              url = new URL(fullpath);
            }
            catch (MalformedURLException e2)
            {
              throw new SAXException( 
XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CANNOT_CREATE_URL, new 
Object[]{urlString}),e2); //"Cannot create url for: " + urlString, e2 );
            }
          }
        }
      }
      catch(SecurityException se)
      {
        try
        {
          url = new URL("http://xml.apache.org/xslt/"+java.lang.Math.random()); 
// dummy
        }
        catch (MalformedURLException e2)
        {
          // I give up
        }
      }
      // System.out.println("url: "+url.toString());
      return url;
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/TreeWalker.java
  
  Index: TreeWalker.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import org.w3c.dom.*;
  import org.xml.sax.*;
  import org.xml.sax.ext.LexicalHandler;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This class does a pre-order walk of the DOM tree, calling the 
FormatterListener
   * interface as it goes.
   */
  public class TreeWalker
  {
    private ContentHandler m_formatterListener =   null;
    
    /**
     * Get the ContentHandler used for the tree walk.
     */
    public ContentHandler getFormatterListener()
    {
      return m_formatterListener;
    }
    
    /**
     * Constructor.
     * @param   formatterListener The implemention of the 
     * FormatterListener operation (toXMLString, digest, ...)
     */
    public TreeWalker(ContentHandler formatterListener) 
    {
      this.m_formatterListener = formatterListener;
    }
  
    /**
     * Perform a pre-order traversal non-recursive style.
     */
    public void traverse(Node pos) throws SAXException 
    {
      Node top = pos;
    while(null != pos)
      {     
        startNode(pos);
        
        Node nextNode = pos.getFirstChild();
        while(null == nextNode)
        {
          endNode(pos);
          if(top.equals( pos ))
            break;
          nextNode = pos.getNextSibling();
          if(null == nextNode)
          {
            pos = pos.getParentNode();
            if((null == pos) || (top.equals( pos )))
            {
              if(null != pos)
                endNode(pos);
              nextNode = null;
              break;
            }
          }
        }
        pos = nextNode;
      }
    }
  
    /**
     * Perform a pre-order traversal non-recursive style.
     */
    public void traverse(Node pos, Node top) throws SAXException 
    {
      while(null != pos)
      {     
        startNode(pos);
        
        Node nextNode = pos.getFirstChild();
        while(null == nextNode)
        {
          endNode(pos);
          if((null != top) && top.equals( pos ))
            break;
          nextNode = pos.getNextSibling();
          if(null == nextNode)
          {
            pos = pos.getParentNode();
            if((null == pos) || ((null != top) && top.equals( pos )))
            {
              nextNode = null;
              break;
            }
          }
        }
        pos = nextNode;
      }
    }
    
    /*
    public void traverse(Node pos) throws SAXException 
    {
      startNode(pos);
      NodeList children = pos.getChildNodes();
      if(null != children)
      {
        int nChildren = children.getLength();
        for(int i = 0; i < nChildren; i++)
        {
          traverse(children.item(i));
        }
      }
      endNode(pos);
    }
    */
    
    boolean nextIsRaw = false;
    
    protected void startNode(Node node)
      throws SAXException 
    {
      switch(node.getNodeType())
      {
      case Node.COMMENT_NODE:
        {
          String data = ((Comment)node).getData();
          if(m_formatterListener instanceof LexicalHandler)
          {
            LexicalHandler lh = ((LexicalHandler)this.m_formatterListener);
            lh.comment(data.toCharArray(), 0, data.length());
          }
        }
        break;
      case Node.DOCUMENT_FRAGMENT_NODE:
        // ??;
        break;
      case Node.DOCUMENT_NODE:
        this.m_formatterListener.startDocument();
        break;
      case Node.ELEMENT_NODE:
        NamedNodeMap atts = ((Element)node).getAttributes();
        this.m_formatterListener.startElement ("", "", node.getNodeName(), new 
AttList(atts));
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:
        {
          ProcessingInstruction pi = (ProcessingInstruction)node;
          String name = pi.getNodeName();
          // String data = pi.getData();
          if(name.equals("xslt-next-is-raw") && name.equals("formatter-to-dom"))
          {
            nextIsRaw = true;
          }
          else
          {
            this.m_formatterListener.processingInstruction(pi.getNodeName(), 
pi.getData());
          }
        }
        break;
      case Node.CDATA_SECTION_NODE:
        {
          String data = ((Text)node).getData();
          boolean isLexH = (m_formatterListener instanceof LexicalHandler);
          LexicalHandler lh = isLexH ? 
((LexicalHandler)this.m_formatterListener) : null;
          if(isLexH)
          {
            lh.startCDATA();
          }
          this.m_formatterListener.characters(data.toCharArray(), 0, 
data.length());
          {
            if(isLexH)
            {
              lh.endCDATA();
            }
          }
        }
        break;
      case Node.TEXT_NODE:
        {
          String data = ((Text)node).getData();
          if(nextIsRaw)
          {
            nextIsRaw = false;
            if(this.m_formatterListener instanceof RawCharacterHandler)
            {
              
((RawCharacterHandler)this.m_formatterListener).charactersRaw(data.toCharArray(),
 0, data.length());
            }
            else
            {
              System.out.println("Warning: can't output raw characters!");
              this.m_formatterListener.characters(data.toCharArray(), 0, 
data.length());
            }
          }
          else
          {
            this.m_formatterListener.characters(data.toCharArray(), 0, 
data.length());
          }
        }
        break;
      case Node.ENTITY_REFERENCE_NODE:
        {
          EntityReference eref = (EntityReference)node;
          if(m_formatterListener instanceof LexicalHandler)
          {
            
((LexicalHandler)this.m_formatterListener).startEntity(eref.getNodeName());
          }
          else
          {
            // warning("Can not output entity to a pure SAX ContentHandler");
          }
        }
        break;
      default:
      }
    }
  
    protected void endNode(Node node)
      throws SAXException 
    {
      switch(node.getNodeType())
      {
      case Node.DOCUMENT_NODE:
        this.m_formatterListener.endDocument();
        break;
      case Node.ELEMENT_NODE:
        this.m_formatterListener.endElement("", "", node.getNodeName());
        break;
      case Node.CDATA_SECTION_NODE:
        break;
      case Node.ENTITY_REFERENCE_NODE:
        {
          EntityReference eref = (EntityReference)node;
          if(m_formatterListener instanceof LexicalHandler)
          {
            LexicalHandler lh = ((LexicalHandler)this.m_formatterListener);
            lh.endEntity(eref.getNodeName());
          }
        }
        break;
      default:
      }
    }
    
  }  //TreeWalker
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/Trie.java
  
  Index: Trie.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2000 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  package org.apache.xalan.utils;
  
  /** 
   * <meta name="usage" content="internal"/>
   * A digital search trie for 7-bit ASCII text
   * The API is a subset of java.util.Hashtable
   * The key must be a 7-bit ASCII string
   * The value may be any Java Object
   */
  public class Trie
  {
        public static final int ALPHA_SIZE = 128;
  
        Node m_Root;
  
        public Trie()
        {
                m_Root = new Node();
        }
  
        public Object put(String key, Object value)
        {
                final int len = key.length();
  
                Node node = m_Root;
  
                for (int i = 0; i< len; i++)
                {
                        Node nextNode = 
node.m_nextChar[Character.toUpperCase(key.charAt(i))];
  
                        if (nextNode != null)
                        {
                                node = nextNode;
                        }
                        else
                        {
                                for (;i<len; i++)
                                {
                                        Node newNode = new Node();
                                        
node.m_nextChar[Character.toUpperCase(key.charAt(i))] = newNode;
                                        node = newNode;
                                }
  
                                break;
                        }
                }
  
                Object ret = node.m_Value;
                node.m_Value = value;
  
                return ret;
        }
  
        public Object get(String key)
        {
                final int len = key.length();
  
                Node node = m_Root;
  
                for (int i = 0; i< len; i++)
                {
                        try
                        {
                                node = 
node.m_nextChar[Character.toUpperCase(key.charAt(i))];
                        }
  
                        catch (ArrayIndexOutOfBoundsException e)
                        {
                                // the key is not 7-bit ASCII so we won't find 
it here
                                node = null;                                    
                        }
  
                        if (node == null)
                                return null;
                }
  
                return node.m_Value;
        }
  
        class Node
        {
                Node()
                {
                        m_nextChar = new Node[ALPHA_SIZE];
                        m_Value = null;
                }
  
                Node m_nextChar[];
                Object m_Value;
        }
  }
  
  
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/utils/UnImplNode.java
  
  Index: UnImplNode.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  import org.w3c.dom.*;
  import org.apache.xalan.res.XSLTErrorResources;
  import org.apache.xalan.res.XSLMessages;
  
  /**
   * <meta name="usage" content="internal"/>
   * To be subclassed by classes that wish to fake being nodes.
   */
  public class UnImplNode implements Node, Element, NodeList, Document
  {
    public UnImplNode()
    {
    }
  
    /**
     * Throw an error.
     */
    public void error(int msg)
    {
      throw new RuntimeException(XSLMessages.createMessage(msg, null));
    }
  
    /**
     * Throw an error.
     */
    public void error(int msg, Object[]args)
    {
      throw new RuntimeException(XSLMessages.createMessage(msg, args)); 
//"UnImplNode error: "+msg);
    }
  
    /** Unimplemented. */
    public Node               appendChild(Node newChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"appendChild not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public boolean            hasChildNodes()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"hasChildNodes not 
supported!");
      return false;
    }
  
    /** Unimplemented. */
    public short              getNodeType()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getNodeType not 
supported!");
      return 0;
    }
  
    /** Unimplemented. */
    public Node               getParentNode()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getParentNode not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public NodeList           getChildNodes()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getChildNodes not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Node               getFirstChild()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getFirstChild not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Node               getLastChild()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getLastChild not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Node               getNextSibling()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getNextSibling 
not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public int getLength()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getLength not 
supported!");
      return 0;
    } // getLength():int
  
    /** Unimplemented. */
    public Node item(int index)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"item not 
supported!");
      return null;
    } // item(int):Node
  
    /** Unimplemented. */
    public Document           getOwnerDocument()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getOwnerDocument 
not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public String getTagName()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getTagName not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public String getNodeName()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getNodeName not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public void               normalize()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"normalize not 
supported!");
    }
  
    /** Unimplemented. */
    public NodeList           getElementsByTagName(String name)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); 
//"getElementsByTagName not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Attr               removeAttributeNode(Attr oldAttr)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); 
//"removeAttributeNode not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Attr               setAttributeNode(Attr newAttr)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"setAttributeNode 
not supported!");
      return null;
    }
    
    public boolean hasAttribute(String name)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"hasAttribute not 
supported!");
      return false;
    }
  
    public boolean hasAttributeNS(String name, String x)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"hasAttributeNS 
not supported!");
      return false;
    }
  
    public Attr               getAttributeNode(String name)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getAttributeNode 
not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public void               removeAttribute(String name)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"removeAttribute 
not supported!");
    }
  
    /** Unimplemented. */
    public void               setAttribute(String name,
                                           String value)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"setAttribute not 
supported!");
    }
  
    /** Unimplemented. */
    public String             getAttribute(String name)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getAttribute not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public NodeList           getElementsByTagNameNS(String namespaceURI,
                                                     String localName)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); 
//"getElementsByTagNameNS not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Attr               setAttributeNodeNS(Attr newAttr)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); 
//"setAttributeNodeNS not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Attr               getAttributeNodeNS(String namespaceURI,
                                                 String localName)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); 
//"getAttributeNodeNS not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public void               removeAttributeNS(String namespaceURI,
                                                String localName)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"removeAttributeNS 
not supported!");
    }
  
    /** Unimplemented. */
    public void               setAttributeNS(String namespaceURI,
                                             String qualifiedName,
                                             String value)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"setAttributeNS 
not supported!");
    }
  
    /** Unimplemented. */
    public String             getAttributeNS(String namespaceURI,
                                             String localName)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getAttributeNS 
not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Node               getPreviousSibling()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); 
//"getPreviousSibling not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Node               cloneNode(boolean deep)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"cloneNode not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public String             getNodeValue()
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getNodeValue not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public void               setNodeValue(String nodeValue)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"setNodeValue not 
supported!");
    }
  
    /** Unimplemented. */
    public NamedNodeMap       getAttributes()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getAttributes not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Node               insertBefore(Node newChild,
                                           Node refChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"insertBefore not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Node               replaceChild(Node newChild,
                                           Node oldChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"replaceChild not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public Node               removeChild(Node oldChild)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"replaceChild not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public boolean            supports(String feature,
                                       String version)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"supports not 
supported!");
      return false;
    }
  
    /** Unimplemented. */
    public String             getNamespaceURI()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getNamespaceURI 
not supported!");
      return null;
    }
  
    /** Unimplemented. */
    public String             getPrefix()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getPrefix not 
supported!");
      return null;
    }
  
    /** Unimplemented. */
    public void               setPrefix(String prefix)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"setPrefix not 
supported!");
    }
  
    /** Unimplemented. */
    public String       getLocalName()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getLocalName not 
supported!");
      return null;
    }
    
    /** Unimplemented. */
    public DocumentType       getDoctype()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public DOMImplementation  getImplementation()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Element            getDocumentElement()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Element            createElement(String tagName)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public DocumentFragment   createDocumentFragment()
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Text               createTextNode(String data)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Comment            createComment(String data)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public CDATASection       createCDATASection(String data)
      throws DOMException
  
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public ProcessingInstruction createProcessingInstruction(String target,
                                                             String data)
      throws DOMException
  
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Attr               createAttribute(String name)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public EntityReference    createEntityReference(String name)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Node               importNode(Node importedNode,
                                         boolean deep)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Element            createElementNS(String namespaceURI,
                                              String qualifiedName)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Attr               createAttributeNS(String namespaceURI,
                                                String qualifiedName)
      throws DOMException
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public Element            getElementById(String elementId)
    {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
    
    public void         setData(String data)
      throws DOMException
  {
    error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
    }
  
    /** Unimplemented. */
    public String       substringData(int offset, 
                                      int count)
      throws DOMException
  {
    error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
    }
  
    /** Unimplemented. */
    public void         appendData(String arg)
      throws DOMException
  {
    error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
    }
  
    /** Unimplemented. */
    public void         insertData(int offset, 
                                   String arg)
      throws DOMException
  {
    error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
    }
  
    /** Unimplemented. */
    public void         deleteData(int offset, 
                                   int count)
      throws DOMException
  {
    error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
    }
  
    /** Unimplemented. */
    public void         replaceData(int offset, 
                                    int count, 
                                    String arg)
      throws DOMException
  {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
    }
  
    /** Unimplemented. */
    public Text         splitText(int offset)
      throws DOMException
  {
      error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED);
      return null;
  }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/utils/WrongParserException.java
  
  Index: WrongParserException.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.utils;
  
  /**
   * <meta name="usage" content="general"/>
   * Certain functions may throw this error if they are paired with 
   * the incorrect parser.
   */
  public class WrongParserException extends RuntimeException
  {
    /**
     * Create a WrongParserException object.
     * @param message The error message that should be reported to the user.
     */
    public WrongParserException(String message) 
    {
       super(message);
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/Arg.java
  
  Index: Arg.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.xpath.XObject;
  
  /**
   * <meta name="usage" content="internal"/>
   * This class holds an instance of an argument on 
   * the stack.
   */
  public class Arg
  {
    private QName m_qname;
    
    /**
     * Get the qualified name for this argument.
     */
    public QName getQName()
    {
          return m_qname;
    }
  
    /**
     * Set the qualified name for this argument.
     */
    public void setQName(QName name)
    {
          m_qname = name;
    }
    
    private XObject m_val;
    
    /**
     * Get the value for this argument.
     */
    public XObject getVal()
    {
          return m_val;
    }
  
    /**
     * Set the value for this argument.
     */
    public void setVal(XObject val)
    {
          m_val = val;
    }
    
    private String m_expression;
    
    /**
     * Get the value expression for this argument.
     */
    public String getExpression()
    {
          return m_expression;
    }
  
    /**
     * Set the value expression for this argument.
     */
    public void setExpression(String expr)
    {
          m_expression = expr;
    }
  
    private boolean m_isParamVar;
    
    /**
     * Construct a dummy parameter argument.
     */
    public Arg()
    {
      m_qname = new QName("");; // so that string compares can be done.
      m_val = null;
      m_expression = null;
      m_isParamVar = false;
    }
  
    /**
     * Construct a parameter argument.
     */
    public Arg(QName qname, String expression, boolean isParamVar)
    {
      m_qname = qname;
      m_val = null;
      m_expression = expression;
      m_isParamVar = isParamVar;
    }
  
    /**
     * Construct a parameter argument.
     */
    public Arg(QName qname, XObject val)
    {
      m_qname = qname;
      m_val = val;
      m_isParamVar = false;
      m_expression = null;
    }
  
  
    /**
     * Construct a parameter argument.
     */
    public Arg(QName qname, XObject val, boolean isParamVar)
    {
      m_qname = qname;
      m_val = val;
      m_isParamVar = isParamVar;
      m_expression = null;
    }
  
    /**
     * Override equals and agree that we're equal if 
     * the passed object is a string and it matches 
     * the name of the arg.
     */
    public boolean equals(Object obj)
    {
      try
      {
        if(m_qname != null)
        {
          QName qname = (QName)obj;
          return m_qname.equals(qname.getLocalPart()) 
                 && ((null != m_qname.getNamespace()) && (null != 
qname.getNamespace())) 
                 ? m_qname.getNamespace().equals(qname.getNamespace())
                   : ((null == m_qname.getNamespace()) && (null == 
qname.getNamespace()));
        }
      }
      catch(ClassCastException cce)
      {
      }
      
      return false;
    }
  
    /**
     * Override equals and agree that we're equal if 
     * the passed object is a QName and it matches 
     * the name of the arg.
     */
    public boolean equals(QName qname)
    {
      if(m_qname != null)
      {
        return m_qname.getLocalPart().equals(qname.getLocalPart()) 
               && (((null != m_qname.getNamespace()) && (null != 
qname.getNamespace())) 
                   ? m_qname.getNamespace().equals(qname.getNamespace())
                     : ((null == m_qname.getNamespace()) && (null == 
qname.getNamespace())));
      }
      return false;
    }
  
  }
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/DOM2Helper.java
  
  Index: DOM2Helper.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import java.io.IOException;
  import java.util.StringTokenizer;
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.xpath.DOMHelper;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Text;
  import org.w3c.dom.Attr;
  
  import org.xml.sax.SAXException;
  import org.xml.sax.InputSource;
  import org.xml.sax.Parser;
  
  /**
   * <meta name="usage" content="general"/>
   * Provides XSLTProcessor an interface to the Xerces XML parser.  This 
   * liaison should be used if Xerces DOM nodes are being process as 
   * the source tree or as the result tree.
   * @see org.apache.xalan.xslt.XSLTProcessor
   * @see org.apache.xml.parsers
   */
  public class DOM2Helper extends DOMHelper
  {
    /**
     * Construct an instance.
     */
    public DOM2Helper()
    {
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Check node to see if it matches this liaison.
     */
    public void checkNode(Node node)
      throws SAXException
    {
      if(!(node instanceof org.apache.xerces.dom.NodeImpl))
        throw new 
SAXException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_XERCES_CANNOT_HANDLE_NODES,
 new Object[]{((Object)node).getClass()})); //"DOM2Helper can not handle nodes 
of type"
          //+((Object)node).getClass());
    }
  
    /**
     * Returns true that this implementation does support
     * the SAX ContentHandler interface.
     */
    public boolean supportsSAX()
    {
      return true;
    }
    
    private Document m_doc;
    
    public void setDocument(Document doc) {m_doc = doc;}
    public Document getDocument() {return m_doc;}
  
    /**
     * <meta name="usage" content="internal"/>
     * Parse an XML document.
     * 
     * <p>Right now the Xerces DOMParser class is used.  This needs 
     * fixing, either via jaxp, or via some other, standard method.</p>
     *
     * <p>The application can use this method to instruct the SAX parser
     * to begin parsing an XML document from any valid input
     * source (a character stream, a byte stream, or a URI).</p>
     *
     * <p>Applications may not invoke this method while a parse is in
     * progress (they should create a new Parser instead for each
     * additional XML document).  Once a parse is complete, an
     * application may reuse the same Parser object, possibly with a
     * different input source.</p>
     *
     * @param source The input source for the top-level of the
     *        XML document.
     * @exception org.xml.sax.SAXException Any SAX exception, possibly
     *            wrapping another exception.
     * @exception java.io.IOException An IO exception from the parser,
     *            possibly from a byte stream or character stream
     *            supplied by the application.
     * @see org.xml.sax.InputSource
     * @see #parse(java.lang.String)
     * @see #setEntityResolver
     * @see #setDTDHandler
     * @see #setContentHandler
     * @see #setErrorHandler
     */
    public void parse (InputSource source)
      throws SAXException
    {
      // I guess I should use JAXP factory here... when it's legal.
      org.apache.xerces.parsers.DOMParser parser 
        = new org.apache.xerces.parsers.DOMParser();
      
      // 
domParser.setFeature("http://apache.org/xml/features/dom/create-entity-ref-nodes";,
 getShouldExpandEntityRefs()? false : true);
      if(m_useDOM2getNamespaceURI)
      {
        
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion";, 
true);
        parser.setFeature("http://xml.org/sax/features/namespaces";, true);
      }
      else
      {
        
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion";, 
false);
      }
      
      parser.setFeature("http://apache.org/xml/features/allow-java-encodings";, 
true);
  
      String ident = (null == source.getSystemId())
                     ? "Input XSL" : source.getSystemId();
      parser.setErrorHandler(new 
org.apache.xalan.utils.DefaultErrorHandler(ident));
  
      // if(null != m_entityResolver)
      // {
      // System.out.println("Setting the entity resolver.");
      //  parser.setEntityResolver(m_entityResolver);
      // }
  
      try
      {
        parser.parse(source);
      }
      catch(IOException ioe)
      {
        throw new SAXException(ioe);
      }
      setDocument(((org.apache.xerces.parsers.DOMParser)parser).getDocument());
    }
  
    /**
     * Given an ID, return the element.
     */
    public Element getElementByID(String id, Document doc)
    {
      return doc.getElementById(id);
    }
  
    /**
     * Get the parent of a node.
     */
    public Node getParentOfNode(Node node)
      throws RuntimeException
    {
      return (Node.ATTRIBUTE_NODE == node.getNodeType())
             ? ((Attr)node).getOwnerElement() : node.getParentNode();
    }
  
    private boolean m_useDOM2getNamespaceURI = false;
  
  }
  
  
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/DOMHelper.java
  
  Index: DOMHelper.java
  ===================================================================
  package org.apache.xalan.xpath;
  
  import java.net.URL;
  import java.util.Hashtable;
  import java.util.Vector;
  import org.w3c.dom.*;
  import org.xml.sax.SAXException;
  import org.apache.xalan.utils.NSInfo;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  public class DOMHelper
  {
    /**
     * Create an empty DOM Document.  Mainly used for creating an 
     * output document.  Implementation of XPathContext
     * interface method.
     * Default handling: Not supported - need parser-specific implementation.
     */
    public Document createDocument()
    {
      throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CREATEDOCUMENT_NOT_SUPPORTED,
 null));//"createDocument() not supported in XPathContext!");
      // return null;
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Tells, through the combination of the default-space attribute 
     * on xsl:stylesheet, xsl:strip-space, xsl:preserve-space, and the
     * xml:space attribute, whether or not extra whitespace should be stripped 
     * from the node.  Literal elements from template elements should 
     * <em>not</em> be tested with this function.
     * @param textNode A text node from the source tree.
     * @return true if the text node should be stripped of extra whitespace.
     */
    public boolean shouldStripSourceNode(Node textNode)
      throws org.xml.sax.SAXException
    {
      // return (null == m_envSupport) ? false : 
m_envSupport.shouldStripSourceNode(textNode);
      return false;
    }
    
    /**
     * Figure out if node2 should be placed after node1 in 
     * document order (returns node1 &lt;= node2).
     * NOTE: Make sure this does the right thing with attribute nodes!!!
     * @return true if node2 should be placed 
     * after node1, and false if node2 should be placed 
     * before node1.
     */
    public boolean isNodeAfter(Node node1, Node node2)
    {
      if(node1 == node2)
        return true;
  
      boolean isNodeAfter = false; // return value.
      
      Node parent1 = getParentOfNode(node1);
      Node parent2 = getParentOfNode(node2);
      
      // Optimize for most common case
      if(parent1 == parent2) // then we know they are siblings
      {
        if (null != parent1)
          isNodeAfter = isNodeAfterSibling(
                                         parent1, node1, node2);
        else
        {
          if(node1 == node2) // Same document?
            return false;
          else
            return true;
        }
      }
      else
      {
        // General strategy: Figure out the lengths of the two 
        // ancestor chains, and walk up them looking for the 
        // first common ancestor, at which point we can do a 
        // sibling compare.  Edge condition where one is the 
        // ancestor of the other.
        
        // Count parents, so we can see if one of the chains 
        // needs to be equalized.
        int nParents1 = 2, nParents2 = 2; // count node & parent obtained above
        while(parent1 != null)
        {
          nParents1++;
          parent1 = getParentOfNode(parent1);
        }
        
        while(parent2 != null)
        {
          nParents2++;
          parent2 = getParentOfNode(parent2);
        }
        
        Node startNode1 = node1, startNode2 = node2; // adjustable starting 
points
        
        // Do I have to adjust the start point in one of 
        // the ancesor chains?
        if(nParents1 < nParents2)
        {
          // adjust startNode2
          int adjust = nParents2 - nParents1;
          for(int i = 0; i < adjust; i++)
          {
            startNode2 = getParentOfNode(startNode2);
          }
        }
        else if(nParents1 > nParents2)
        {
          // adjust startNode1
          int adjust = nParents1 - nParents2;
          for(int i = 0; i < adjust; i++)
          {
            startNode1 = getParentOfNode(startNode1);
          }
        }
        
        Node prevChild1 = null, prevChild2 = null; // so we can "back up"
        
        // Loop up the ancestor chain looking for common parent.
        while(null != startNode1)
        {
          if(startNode1 == startNode2) // common parent?
          {
            if(null == prevChild1) // first time in loop?
            {
              // Edge condition: one is the ancestor of the other.
              isNodeAfter = (nParents1 < nParents2) ? true : false;
              break; // from while loop
            }
            else
            {
              isNodeAfter = isNodeAfterSibling(
                                               startNode1, prevChild1, 
prevChild2);
              break; // from while loop
            }
          } // end if(startNode1 == startNode2)
          prevChild1 = startNode1;
          startNode1 = getParentOfNode(startNode1);
          prevChild2 = startNode2;
          startNode2 = getParentOfNode(startNode2);
        } // end while
      } // end big else
      
      /* -- please do not remove... very useful for diagnostics --
      System.out.println("node1 = 
"+node1.getNodeName()+"("+node1.getNodeType()+")"+
      ", node2 = "+node2.getNodeName()
      +"("+node2.getNodeType()+")"+
      ", isNodeAfter = "+isNodeAfter); */
      
      return isNodeAfter;
    } // end isNodeAfter(Node node1, Node node2)
    
    /**
     * Figure out if child2 is after child1 in document order.
     * @param parent Must be the parent of child1 and child2.
     * @param child1 Must be the child of parent and not equal to child2.
     * @param child2 Must be the child of parent and not equal to child1.
     * @returns true if child 2 is after child1 in document order.
     */
    private static boolean isNodeAfterSibling(
                                       Node parent, Node child1, Node child2)
    {
      boolean isNodeAfterSibling = false;
      int child1type = child1.getNodeType();
      int child2type = child2.getNodeType();
      if((Node.ATTRIBUTE_NODE != child1type) && (Node.ATTRIBUTE_NODE == 
child2type))
      {
        // always sort attributes before non-attributes.
        isNodeAfterSibling = false;
      }
      else if((Node.ATTRIBUTE_NODE == child1type) && (Node.ATTRIBUTE_NODE != 
child2type))
      {
        // always sort attributes before non-attributes.
        isNodeAfterSibling = true;
      }
      else if(Node.ATTRIBUTE_NODE == child1type)
      {
        NamedNodeMap children = parent.getAttributes();
        int nNodes = children.getLength();
        boolean found1 = false, found2 = false;
        for(int i = 0; i < nNodes; i++)
        {
          Node child = children.item(i);
          if(child1 == child)
          {
            if(found2)
            {
              isNodeAfterSibling = false;
              break;
            }
            found1 = true;
          }
          else if(child2 == child)
          {
            if(found1)
            {
              isNodeAfterSibling = true;
              break;
            }
            found2 = true;
          }
        }
      }
      else
      {
        // NodeList children = parent.getChildNodes();
        // int nNodes = children.getLength();
        Node child = parent.getFirstChild();
        boolean found1 = false, found2 = false;
        while(null != child)
        {
          // Node child = children.item(i);
          if(child1 == child)
          {
            if(found2)
            {
              isNodeAfterSibling = false;
              break;
            }
            found1 = true;
          }
          else if(child2 == child)
          {
            if(found1)
            {
              isNodeAfterSibling = true;
              break;
            }
            found2 = true;
          }
          child = child.getNextSibling();
        }
      }
      return isNodeAfterSibling;
    } // end isNodeAfterSibling(Node parent, Node child1, Node child2)
    
    
    //==========================================================
    // SECTION: Namespace resolution
    //==========================================================
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the depth level of this node in the tree (count from 1).
     */
    public short getLevel(Node n)
    {
      short level = 1;
      while(null != (n = getParentOfNode(n)))
      {
        level++;
      }
      return level;
    }
    
    /**
     * Given a prefix and a namespace context, return the expanded namespace.
     * Default handling: 
     */
    public String getNamespaceForPrefix(String prefix, Element namespaceContext)
    {
      int type;
      Node parent = namespaceContext;
      String namespace = null;
      if(prefix.equals("xml"))
      {
        namespace = QName.S_XMLNAMESPACEURI;
      }
      else
      {
        while ((null != parent) && (null == namespace)
               && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
                   || (type == Node.ENTITY_REFERENCE_NODE))) 
        {
          if (type == Node.ELEMENT_NODE) 
          {
            NamedNodeMap nnm = parent.getAttributes();
            for (int i = 0;  i < nnm.getLength();  i ++) 
            {
              Node attr = nnm.item(i);
              String aname = attr.getNodeName();
              boolean isPrefix = aname.startsWith("xmlns:");
              if (isPrefix || aname.equals("xmlns")) 
              {
                int index = aname.indexOf(':');
                String p = isPrefix ? aname.substring(index+1) : "";
                if (p.equals(prefix)) 
                {
                  namespace = attr.getNodeValue();
                  break;
                }
              }
            }
          }
          parent = getParentOfNode(parent);
        }
      }
      return namespace;
    }
    
    /**
     * An experiment for the moment.
     */
    Hashtable m_NSInfos = new Hashtable();
    
    protected static final NSInfo m_NSInfoUnProcWithXMLNS = new NSInfo(false, 
true);
    protected static final NSInfo m_NSInfoUnProcWithoutXMLNS = new 
NSInfo(false, false);
    protected static final NSInfo m_NSInfoUnProcNoAncestorXMLNS = new 
NSInfo(false, false, NSInfo.ANCESTORNOXMLNS);
    protected static final NSInfo m_NSInfoNullWithXMLNS = new NSInfo(true, 
true);
    protected static final NSInfo m_NSInfoNullWithoutXMLNS = new NSInfo(true, 
false);
    protected static final NSInfo m_NSInfoNullNoAncestorXMLNS = new 
NSInfo(true, false, NSInfo.ANCESTORNOXMLNS);
    
    protected Vector m_candidateNoAncestorXMLNS =  new Vector();
    
    /**
     * Returns the namespace of the given node.
     */
    public String getNamespaceOfNode(Node n)
    {
      String namespaceOfPrefix;
      boolean hasProcessedNS;
      NSInfo nsInfo;
      int ntype = n.getNodeType();
      if(Node.ATTRIBUTE_NODE != ntype)
      {
        Object nsObj = m_NSInfos.get(n); // return value
        nsInfo = (nsObj == null) ? null : (NSInfo)nsObj;
        hasProcessedNS = (nsInfo == null) ? false : nsInfo.m_hasProcessedNS;
      }
      else
      {
        hasProcessedNS = false;
        nsInfo = null;
      }
      if(hasProcessedNS)
      {
        namespaceOfPrefix = nsInfo.m_namespace;
      }
      else
      {
        namespaceOfPrefix = null;
        String nodeName = n.getNodeName();
        int indexOfNSSep = nodeName.indexOf(':');
        String prefix;
  
        if(Node.ATTRIBUTE_NODE == ntype)
        {
          if(indexOfNSSep > 0)
          {
            prefix = nodeName.substring(0, indexOfNSSep);
          }
          else
          {
            // Attributes don't use the default namespace, so if 
            // there isn't a prefix, we're done.
            return namespaceOfPrefix;
          }
        }
        else
        {
          prefix = (indexOfNSSep >= 0) ? nodeName.substring(0, indexOfNSSep) : 
"";
        }
        boolean ancestorsHaveXMLNS = false;
        boolean nHasXMLNS = false;
        if(prefix.equals("xml"))
        {
          namespaceOfPrefix = QName.S_XMLNAMESPACEURI;
        }
        else
        {
          int parentType;
          Node parent = n;
          while ((null != parent) && (null == namespaceOfPrefix)) 
          {
            if((null != nsInfo) 
               && (nsInfo.m_ancestorHasXMLNSAttrs == nsInfo.ANCESTORNOXMLNS))
            {
              break;
            }
            parentType = parent.getNodeType();
            if((null == nsInfo) || nsInfo.m_hasXMLNSAttrs)
            {
              boolean elementHasXMLNS = false;
              if (parentType == Node.ELEMENT_NODE) 
              {
                NamedNodeMap nnm = parent.getAttributes();
                for (int i = 0;  i < nnm.getLength();  i ++) 
                {
                  Node attr = nnm.item(i);
                  String aname = attr.getNodeName();
                  if(aname.charAt(0) == 'x')
                  {
                    boolean isPrefix = aname.startsWith("xmlns:");
                    if (aname.equals("xmlns") || isPrefix) 
                    {
                      if(n == parent)
                        nHasXMLNS = true;
                      elementHasXMLNS = true;
                      ancestorsHaveXMLNS = true;
                      String p = isPrefix ? aname.substring(6) : "";
                      if (p.equals(prefix)) 
                      {
                        namespaceOfPrefix = attr.getNodeValue();
                        break;
                      }
                    }
                  }
                }
              }
              if((Node.ATTRIBUTE_NODE != parentType) && (null == nsInfo) && (n 
!= parent))
              {
                nsInfo = elementHasXMLNS ? m_NSInfoUnProcWithXMLNS : 
m_NSInfoUnProcWithoutXMLNS;
                m_NSInfos.put(parent, nsInfo);
              }
            }
            if(Node.ATTRIBUTE_NODE == parentType)
            {
              parent = getParentOfNode(parent);
            }
            else
            {
              m_candidateNoAncestorXMLNS.addElement(parent);
              m_candidateNoAncestorXMLNS.addElement(nsInfo);
              parent = parent.getParentNode();
            }
            if(null != parent)
            {
              Object nsObj = m_NSInfos.get(parent); // return value
              nsInfo = (nsObj == null) ? null : (NSInfo)nsObj;
            }
          }
          int nCandidates = m_candidateNoAncestorXMLNS.size();
          if(nCandidates > 0)
          {
            if((false == ancestorsHaveXMLNS) && (null == parent))
            {
              for(int i = 0; i < nCandidates; i+=2)
              {
                Object candidateInfo = 
m_candidateNoAncestorXMLNS.elementAt(i+1);
                if(candidateInfo == m_NSInfoUnProcWithoutXMLNS)
                {
                  m_NSInfos.put(m_candidateNoAncestorXMLNS.elementAt(i), 
                                m_NSInfoUnProcNoAncestorXMLNS );
                }
                else if(candidateInfo == m_NSInfoNullWithoutXMLNS)
                {
                  m_NSInfos.put(m_candidateNoAncestorXMLNS.elementAt(i), 
                                m_NSInfoNullNoAncestorXMLNS );
                }
              }
            }
            m_candidateNoAncestorXMLNS.removeAllElements();
          }
        }
        
        if(Node.ATTRIBUTE_NODE != ntype)
        {
          if(null == namespaceOfPrefix)
          {
            if(ancestorsHaveXMLNS)
            {
              if(nHasXMLNS)
                m_NSInfos.put(n, m_NSInfoNullWithXMLNS );
              else
                m_NSInfos.put(n, m_NSInfoNullWithoutXMLNS );
            }
            else
            {
              m_NSInfos.put(n, m_NSInfoNullNoAncestorXMLNS );
            }
          }
          else
          {
            m_NSInfos.put(n,  new NSInfo(namespaceOfPrefix, nHasXMLNS));
          }
        }
      }
      return namespaceOfPrefix;
    }
  
    /**
     * Returns the local name of the given node.
     */
    public String getLocalNameOfNode(Node n)
    {
      String qname = n.getNodeName();
      int index = qname.indexOf(':');
      return (index < 0) ? qname : qname.substring(index+1);
    }
  
    /**
     * Returns the element name with the namespace expanded.
     */
    public String getExpandedElementName(Element elem)
    {
      String namespace = getNamespaceOfNode(elem);
      return (null != namespace) ? namespace+":"+ getLocalNameOfNode(elem) 
                                   : getLocalNameOfNode(elem);
    }
  
    /**
     * Returns the attribute name with the namespace expanded.
     */
    public String getExpandedAttributeName(Attr attr)
    {
      String namespace = getNamespaceOfNode(attr);
      return (null != namespace) ? namespace+":"+ getLocalNameOfNode(attr) 
                                   : getLocalNameOfNode(attr);
    }
  
    //==========================================================
    // SECTION: DOM Helper Functions
    //==========================================================
  
    /** 
     * Tell if the node is ignorable whitespace.
     * @deprecated
     */
    public boolean isIgnorableWhitespace(Text node)
    {
      boolean isIgnorable = false; // return value
      // TODO: I can probably do something to figure out if this 
      // space is ignorable from just the information in
      // the DOM tree.
      return isIgnorable;
    }
    
    /**
     * Get the first unparented node in the ancestor chain.
     * @deprecated
     */
    public Node getRoot(Node node)
    {
      Node root = null;
      while(node != null)
      {
        root = node;
        node = getParentOfNode(node);
      }
      return root;
    }
    
    /**
     * Get the root node of the document tree, regardless of 
     * whether or not the node passed in is a document node.
     */
    public Node getRootNode(Node n)
    {
      return (Node.DOCUMENT_NODE == n.getNodeType()) ? 
             n : n.getOwnerDocument();
    }
    
    /**
     * Tell if the given node is a namespace decl node.
     */
    public boolean isNamespaceNode(Node n)
    {
      if(Node.ATTRIBUTE_NODE == n.getNodeType())
      {
        String attrName = n.getNodeName();
        return (attrName.startsWith("xmlns:") || attrName.equals("xmlns"));
      }
      return false;
    }
    
    /**
     * I have to write this silly, and expensive function, 
     * because the DOM WG decided that attributes don't 
     * have parents.  If Xalan is used with a DOM implementation
     * that reuses attribute nodes, this will not work correctly.
     */
    public Node getParentOfNode(Node node)
      throws RuntimeException
    {
      Node parent;
      int nodeType = node.getNodeType();
      if(Node.ATTRIBUTE_NODE == nodeType)
      {
        Document doc = node.getOwnerDocument();
        
        /*
        TBD:
        if(null == doc)
        {
          throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT,
 null));//"Attribute child does not have an owner document!");
        }
        */
        
        Element rootElem = doc.getDocumentElement();
        
        if(null == rootElem)
        {
          throw new 
RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT,
 null));//"Attribute child does not have an owner document element!");
        }
        
        parent = locateAttrParent(rootElem, node);
      }
      else
      {
        parent = node.getParentNode();
        // if((Node.DOCUMENT_NODE != nodeType) && (null == parent))
        // {
        //   throw new RuntimeException("Child does not have parent!");
        // }
      }
      return parent;
    }
    
    /**
     * Given an ID, return the element.
     */
    public Element getElementByID(String id, Document doc)
    {
      return null;
    }
    
    /**
     * The getUnparsedEntityURI function returns the URI of the unparsed 
     * entity with the specified name in the same document as the context 
     * node (see [3.3 Unparsed Entities]). It returns the empty string if 
     * there is no such entity.
     * (Should this go here or in the XLocator??)
     * Since it states in the DOM draft: "An XML processor may choose to 
     * completely expand entities before the structure model is passed 
     * to the DOM; in this case, there will be no EntityReferences in the DOM 
tree."
     * So I'm not sure how well this is going to work.
     */
    public String getUnparsedEntityURI(String name, Document doc)
    {
      String url = ""; 
      DocumentType doctype = doc.getDoctype(); 
      if(null != doctype)
      {
        NamedNodeMap entities = doctype.getEntities();
        Entity entity = (Entity)entities.getNamedItem(name);
        String notationName = entity.getNotationName();
        if(null != notationName) // then it's unparsed
        {
          // The draft says: "The XSLT processor may use the public 
          // identifier to generate a URI for the entity instead of the URI 
          // specified in the system identifier. If the XSLT processor does 
          // not use the public identifier to generate the URI, it must use 
          // the system identifier; if the system identifier is a relative 
          // URI, it must be resolved into an absolute URI using the URI of 
          // the resource containing the entity declaration as the base 
          // URI [RFC2396]."
          // So I'm falling a bit short here.
          url = entity.getSystemId();
          if(null == url)
          {
            url = entity.getPublicId();
          }
          else
          {
            // This should be resolved to an absolute URL, but that's hard 
            // to do from here.
          }
        }
      }
      return url;
    }  
    /**
     * Support for getParentOfNode.
     */
    private Node locateAttrParent(Element elem, Node attr)
    {
      Node parent = null;
      NamedNodeMap attrs = elem.getAttributes();
      if(null != attrs)
      {
        int nAttrs = attrs.getLength();
        for(int i = 0; i < nAttrs; i++)
        {
          if(attr == attrs.item(i))
          {
            parent = elem;
            break;
          }
        }
      }
      if(null == parent)
      {
        for(Node node = elem.getFirstChild(); null != node; node = 
node.getNextSibling())
        {
          if(Node.ELEMENT_NODE == node.getNodeType())
          {
            parent = locateAttrParent((Element)node, attr);
            if(null != parent) break;
          }
        }
      }
      return parent;
    }
      
    /**
     * The factory object used for creating nodes 
     * in the result tree.
     */
    protected Document m_DOMFactory = null;
    
    /**
     * Get the factory object required to create DOM nodes 
     * in the result tree.
     */
    public void setDOMFactory(Document domFactory)
    {
      this.m_DOMFactory = domFactory;
    }
  
    
    /**
     * Get the factory object required to create DOM nodes 
     * in the result tree.
     */
    public Document getDOMFactory()
    {
      if(null == this.m_DOMFactory)
      {
        this.m_DOMFactory = createDocument();
      }
      
      return this.m_DOMFactory;
    }
    
    /**
     * Get the textual contents of the node. If the node 
     * is an element, apply whitespace stripping rules, 
     * though I'm not sure if this is right (I'll fix 
     * or declare victory when I review the entire 
     * whitespace handling).
     */
    public static String getNodeData(Node node)
    {
      StringBuffer buf = new StringBuffer();
      getNodeData(node, buf);
      return (buf.length() > 0) ? buf.toString() : "";
    }
    
    /**
     * Get the textual contents of the node. If the node 
     * is an element, apply whitespace stripping rules, 
     * though I'm not sure if this is right (I'll fix 
     * or declare victory when I review the entire 
     * whitespace handling).
     */
    public static void getNodeData(Node node, StringBuffer buf)
    {
      // String data = null;
  
      switch(node.getNodeType())
      {
      case Node.DOCUMENT_FRAGMENT_NODE:
        {
          NodeList mnl = node.getChildNodes();
          int n = mnl.getLength();
          for(int i = 0; i < n; i++)
            getNodeData(mnl.item(i), buf);
        }         
        break;
      case Node.DOCUMENT_NODE:
      case Node.ELEMENT_NODE:
        {
          for(Node child = node.getFirstChild(); null != child; child = 
child.getNextSibling())
            getNodeData(child, buf);
        }
        break;
      case Node.TEXT_NODE:
      case Node.CDATA_SECTION_NODE:
        buf.append( ((Text)node).getData() );
        break;
      case Node.ATTRIBUTE_NODE:
        buf.append( node.getNodeValue() );
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:      
        // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);        
        break;
      default:
        // ignore
        break;
      }
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/FoundIndex.java
  
  Index: FoundIndex.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  /**
   * <meta name="usage" content="internal"/>
   * Class to let us know when it's time to do 
   * a search from the parent because of indexing.
   */
  public class FoundIndex extends RuntimeException
  {
    public FoundIndex()
    {
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/FunctionTable.java
  
  Index: FunctionTable.java
  ===================================================================
  package org.apache.xalan.xpath;
  
  import org.apache.xalan.xpath.functions.Function;
  import org.apache.xalan.xpath.functions.FuncLoader;
  
  /**
   * The function table for XPath.
   */
  public class FunctionTable
  {
    public static final int FUNC_CURRENT = 0;
    public static final int FUNC_LAST = 1;
    public static final int FUNC_POSITION = 2;
    public static final int FUNC_COUNT = 3;
    public static final int FUNC_ID = 4;
    public static final int FUNC_KEY = 5;
    // public static final int FUNC_DOC = 6;
    public static final int FUNC_LOCAL_PART = 7;
    public static final int FUNC_NAMESPACE = 8;
    public static final int FUNC_QNAME = 9;
    public static final int FUNC_GENERATE_ID = 10;
    public static final int FUNC_NOT = 11;
    public static final int FUNC_TRUE = 12;
    public static final int FUNC_FALSE = 13;
    public static final int FUNC_BOOLEAN = 14;
    public static final int FUNC_NUMBER = 15;
    public static final int FUNC_FLOOR = 16;
    public static final int FUNC_CEILING = 17;
    public static final int FUNC_ROUND = 18;
    public static final int FUNC_SUM = 19;
    public static final int FUNC_STRING = 20;
    public static final int FUNC_STARTS_WITH = 21;
    public static final int FUNC_CONTAINS = 22;
    public static final int FUNC_SUBSTRING_BEFORE = 23;
    public static final int FUNC_SUBSTRING_AFTER = 24;
    public static final int FUNC_NORMALIZE_SPACE = 25;
    public static final int FUNC_TRANSLATE = 26;
    public static final int FUNC_CONCAT = 27;
   // public static final int FUNC_FORMAT_NUMBER = 28;
    public static final int FUNC_SUBSTRING = 29;
    public static final int FUNC_STRING_LENGTH = 30;
    public static final int FUNC_SYSTEM_PROPERTY = 31;
    public static final int FUNC_LANG = 32;
    public static final int FUNC_EXT_FUNCTION_AVAILABLE = 33;
    public static final int FUNC_EXT_ELEM_AVAILABLE = 34;
      
    // Proprietary
    public static final int FUNC_DOCLOCATION = 35;
  
    public static final int FUNC_UNPARSED_ENTITY_URI = 36;
  
    /**
     * The function table.
     */
    static Function m_functions[];
      
    /**
     * Number of built in functions.  Be sure to update this as 
     * built-in functions are added.
     */
    private static final int NUM_BUILT_IN_FUNCS = 37;
  
    /**
     * Number of built-in functions that may be added.
     */
    private static final int NUM_ALLOWABLE_ADDINS = 30;
    
    /**
     * The index to the next free function index.
     */
    static int m_funcNextFreeIndex = NUM_BUILT_IN_FUNCS;
    
    static
    {
      m_functions = new Function[NUM_BUILT_IN_FUNCS+NUM_ALLOWABLE_ADDINS];
      m_functions[FUNC_CURRENT] = new FuncLoader("FuncCurrent", FUNC_CURRENT);
      m_functions[FUNC_LAST] = new FuncLoader("FuncLast", FUNC_LAST);
      m_functions[FUNC_POSITION] = new FuncLoader("FuncPosition", 
FUNC_POSITION);
      m_functions[FUNC_COUNT] = new FuncLoader("FuncCount", FUNC_COUNT);
      m_functions[FUNC_ID] = new FuncLoader("FuncId", FUNC_ID);
      m_functions[FUNC_KEY] = new 
FuncLoader("org.apache.xalan.templates.FuncKey", FUNC_KEY);
      // m_functions[FUNC_DOC] = new FuncDoc();
      m_functions[FUNC_LOCAL_PART] = new FuncLoader("FuncLocalPart", 
FUNC_LOCAL_PART);
      m_functions[FUNC_NAMESPACE] = new FuncLoader("FuncNamespace", 
FUNC_NAMESPACE);
      m_functions[FUNC_QNAME] = new FuncLoader("FuncQname", FUNC_QNAME);
      m_functions[FUNC_GENERATE_ID] = new FuncLoader("FuncGenerateId", 
FUNC_GENERATE_ID);
      m_functions[FUNC_NOT] = new FuncLoader("FuncNot", FUNC_NOT);
      m_functions[FUNC_TRUE] = new FuncLoader("FuncTrue", FUNC_TRUE);
      m_functions[FUNC_FALSE] = new FuncLoader("FuncFalse", FUNC_FALSE);
      m_functions[FUNC_BOOLEAN] = new FuncLoader("FuncBoolean", FUNC_BOOLEAN);
      m_functions[FUNC_LANG] = new FuncLoader("FuncLang", FUNC_LANG);
      m_functions[FUNC_NUMBER] = new FuncLoader("FuncNumber", FUNC_NUMBER);
      m_functions[FUNC_FLOOR] = new FuncLoader("FuncFloor", FUNC_FLOOR);
      m_functions[FUNC_CEILING] = new FuncLoader("FuncCeiling", FUNC_CEILING);
      m_functions[FUNC_ROUND] = new FuncLoader("FuncRound", FUNC_ROUND);
      m_functions[FUNC_SUM] = new FuncLoader("FuncSum", FUNC_SUM);
      m_functions[FUNC_STRING] = new FuncLoader("FuncString", FUNC_STRING);
      m_functions[FUNC_STARTS_WITH] = new FuncLoader("FuncStartsWith", 
FUNC_STARTS_WITH);
      m_functions[FUNC_CONTAINS] = new FuncLoader("FuncContains", 
FUNC_CONTAINS);
      m_functions[FUNC_SUBSTRING_BEFORE] = new 
FuncLoader("FuncSubstringBefore", FUNC_SUBSTRING_BEFORE);
      m_functions[FUNC_SUBSTRING_AFTER] = new FuncLoader("FuncSubstringAfter", 
FUNC_SUBSTRING_AFTER);
      m_functions[FUNC_NORMALIZE_SPACE] = new FuncLoader("FuncNormalizeSpace", 
FUNC_NORMALIZE_SPACE);
      m_functions[FUNC_TRANSLATE] = new FuncLoader("FuncTranslate", 
FUNC_TRANSLATE);
      m_functions[FUNC_CONCAT] = new FuncLoader("FuncConcat", FUNC_CONCAT);
      //m_functions[FUNC_FORMAT_NUMBER] = new FuncFormatNumber();
      m_functions[FUNC_SYSTEM_PROPERTY] = new FuncLoader("FuncSystemProperty", 
FUNC_SYSTEM_PROPERTY);
      m_functions[FUNC_EXT_FUNCTION_AVAILABLE] = new 
FuncLoader("FuncExtFunctionAvailable", FUNC_EXT_FUNCTION_AVAILABLE);
      m_functions[FUNC_EXT_ELEM_AVAILABLE] = new 
FuncLoader("FuncExtElementAvailable", FUNC_EXT_ELEM_AVAILABLE);
      m_functions[FUNC_SUBSTRING] = new FuncLoader("FuncSubstring", 
FUNC_SUBSTRING);
      m_functions[FUNC_STRING_LENGTH] = new FuncLoader("FuncStringLength", 
FUNC_STRING_LENGTH);
      m_functions[FUNC_DOCLOCATION] = new FuncLoader("FuncDoclocation", 
FUNC_DOCLOCATION);
      m_functions[FUNC_UNPARSED_ENTITY_URI] = new 
FuncLoader("FuncUnparsedEntityURI", FUNC_UNPARSED_ENTITY_URI);
      
    }
  
    /**
     * Install a built-in function.
     * @param name The unqualified name of the function.
     * @param func A Implementation of an XPath Function object.
     * @return the position of the function in the internal index.
     */
    public static int installFunction(String name, Function func)
    {
      int funcIndex;
      Object funcIndexObj = Keywords.m_functions.get(name);
      if(null != funcIndexObj)
      {
        funcIndex = ((Integer)funcIndexObj).intValue();
      }
      else
      {
        funcIndex = m_funcNextFreeIndex;
        m_funcNextFreeIndex++;
        Keywords.m_functions.put(name, new Integer(funcIndex));
      }
      m_functions[funcIndex] = func;
      return funcIndex;
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/Keywords.java
  
  Index: Keywords.java
  ===================================================================
  package org.apache.xalan.xpath;
  
  import java.util.Hashtable;
  import org.apache.xalan.utils.StringKey;
  
  public class Keywords
  {
    static Hashtable m_keywords = new Hashtable();
    static Hashtable m_axisnames = new Hashtable();
    static Hashtable m_functions = new Hashtable();
    static Hashtable m_nodetypes = new Hashtable();
  
    private static final String FROM_ANCESTORS_STRING = "ancestor";
    private static final String FROM_ANCESTORS_OR_SELF_STRING = 
"ancestor-or-self";
    private static final String FROM_ATTRIBUTES_STRING = "attribute";
    private static final String FROM_CHILDREN_STRING = "child";
    private static final String FROM_DESCENDANTS_STRING = "descendant";
    private static final String FROM_DESCENDANTS_OR_SELF_STRING = 
"descendant-or-self";
    private static final String FROM_FOLLOWING_STRING = "following";
    private static final String FROM_FOLLOWING_SIBLINGS_STRING = 
"following-sibling";
    private static final String FROM_PARENT_STRING = "parent";
    private static final String FROM_PRECEDING_STRING = "preceding";
    private static final String FROM_PRECEDING_SIBLINGS_STRING = 
"preceding-sibling";
    private static final String FROM_SELF_STRING = "self";
    private static final String FROM_NAMESPACE_STRING = "namespace";
  
    private static final String FROM_SELF_ABBREVIATED_STRING = ".";
    private static final String NODETYPE_COMMENT_STRING = "comment";
    private static final String NODETYPE_TEXT_STRING = "text";
    private static final String NODETYPE_PI_STRING = "processing-instruction";
    private static final String NODETYPE_NODE_STRING = "node";
    private static final String FROM_ATTRIBUTE_STRING = "@";
    private static final String FROM_DOC_STRING = "document";
    private static final String FROM_DOCREF_STRING = "document";
    private static final String FROM_ID_STRING = "id";
    private static final String FROM_IDREF_STRING = "idref";
    private static final String NODETYPE_ANYELEMENT_STRING = "*";
    private static final String FUNC_CURRENT_STRING = "current";
    private static final String FUNC_LAST_STRING = "last";
    private static final String FUNC_POSITION_STRING = "position";
    private static final String FUNC_COUNT_STRING = "count";
    static final String FUNC_ID_STRING = "id";
    private static final String FUNC_IDREF_STRING = "idref";
    static final String FUNC_KEY_STRING = "key";
    private static final String FUNC_KEYREF_STRING = "keyref";
    private static final String FUNC_DOC_STRING = "doc";
    private static final String FUNC_DOCUMENT_STRING = "document";
    private static final String FUNC_DOCREF_STRING = "docref";
    private static final String FUNC_LOCAL_PART_STRING = "local-name";
    private static final String FUNC_NAMESPACE_STRING = "namespace-uri";
    private static final String FUNC_NAME_STRING = "name";
    private static final String FUNC_GENERATE_ID_STRING = "generate-id";
    private static final String FUNC_NOT_STRING = "not";
    private static final String FUNC_TRUE_STRING = "true";
    private static final String FUNC_FALSE_STRING = "false";
    private static final String FUNC_BOOLEAN_STRING = "boolean";
    private static final String FUNC_LANG_STRING = "lang";
    private static final String FUNC_NUMBER_STRING = "number";
    private static final String FUNC_FLOOR_STRING = "floor";
    private static final String FUNC_CEILING_STRING = "ceiling";
    private static final String FUNC_ROUND_STRING = "round";
    private static final String FUNC_SUM_STRING = "sum";
    private static final String FUNC_STRING_STRING = "string";
    private static final String FUNC_STARTS_WITH_STRING = "starts-with";
    private static final String FUNC_CONTAINS_STRING = "contains";
    private static final String FUNC_SUBSTRING_BEFORE_STRING = 
"substring-before";
    private static final String FUNC_SUBSTRING_AFTER_STRING = "substring-after";
    private static final String FUNC_NORMALIZE_SPACE_STRING = "normalize-space";
    private static final String FUNC_TRANSLATE_STRING = "translate";
    private static final String FUNC_CONCAT_STRING = "concat";
    //private static final String FUNC_FORMAT_NUMBER_STRING = "format-number";
    private static final String FUNC_SYSTEM_PROPERTY_STRING = "system-property";
    private static final String FUNC_EXT_FUNCTION_AVAILABLE_STRING = 
"function-available";
    private static final String FUNC_EXT_ELEM_AVAILABLE_STRING = 
"element-available";
    private static final String FUNC_SUBSTRING_STRING = "substring";
    private static final String FUNC_STRING_LENGTH_STRING = "string-length";
    private static final String FUNC_UNPARSED_ENTITY_URI_STRING = 
"unparsed-entity-uri";
  
    // Proprietary, built in functions
    private static final String FUNC_DOCLOCATION_STRING = "document-location";
  
    static
    {
      m_axisnames.put(new StringKey(FROM_ANCESTORS_STRING), new 
Integer(OpCodes.FROM_ANCESTORS));
      m_axisnames.put(new StringKey(FROM_ANCESTORS_OR_SELF_STRING), new 
Integer(OpCodes.FROM_ANCESTORS_OR_SELF));
      m_axisnames.put(new StringKey(FROM_ATTRIBUTES_STRING), new 
Integer(OpCodes.FROM_ATTRIBUTES));
      m_axisnames.put(new StringKey(FROM_CHILDREN_STRING), new 
Integer(OpCodes.FROM_CHILDREN));
      m_axisnames.put(new StringKey(FROM_DESCENDANTS_STRING), new 
Integer(OpCodes.FROM_DESCENDANTS));
      m_axisnames.put(new StringKey(FROM_DESCENDANTS_OR_SELF_STRING), new 
Integer(OpCodes.FROM_DESCENDANTS_OR_SELF));
      m_axisnames.put(new StringKey(FROM_FOLLOWING_STRING), new 
Integer(OpCodes.FROM_FOLLOWING));
      m_axisnames.put(new StringKey(FROM_FOLLOWING_SIBLINGS_STRING), new 
Integer(OpCodes.FROM_FOLLOWING_SIBLINGS));
      m_axisnames.put(new StringKey(FROM_PARENT_STRING), new 
Integer(OpCodes.FROM_PARENT));
      m_axisnames.put(new StringKey(FROM_PRECEDING_STRING), new 
Integer(OpCodes.FROM_PRECEDING));
      m_axisnames.put(new StringKey(FROM_PRECEDING_SIBLINGS_STRING), new 
Integer(OpCodes.FROM_PRECEDING_SIBLINGS));
      m_axisnames.put(new StringKey(FROM_SELF_STRING), new 
Integer(OpCodes.FROM_SELF));
      m_axisnames.put(new StringKey(FROM_NAMESPACE_STRING), new 
Integer(OpCodes.FROM_NAMESPACE));
  
      m_nodetypes.put(new StringKey(NODETYPE_COMMENT_STRING), new 
Integer(OpCodes.NODETYPE_COMMENT));
      m_nodetypes.put(new StringKey(NODETYPE_TEXT_STRING), new 
Integer(OpCodes.NODETYPE_TEXT));
      m_nodetypes.put(new StringKey(NODETYPE_PI_STRING), new 
Integer(OpCodes.NODETYPE_PI));
      m_nodetypes.put(new StringKey(NODETYPE_NODE_STRING), new 
Integer(OpCodes.NODETYPE_NODE));
      m_nodetypes.put(new StringKey(NODETYPE_ANYELEMENT_STRING), new 
Integer(OpCodes.NODETYPE_ANYELEMENT));
  
      m_keywords.put(new StringKey(FROM_SELF_ABBREVIATED_STRING), new 
Integer(OpCodes.FROM_SELF));
      // m_keywords.put(new StringKey(FROM_ATTRIBUTE_STRING), new 
Integer(OpCodes.FROM_ATTRIBUTE));
      // m_keywords.put(new StringKey(FROM_DOC_STRING), new 
Integer(OpCodes.FROM_DOC));
      // m_keywords.put(new StringKey(FROM_DOCREF_STRING), new 
Integer(OpCodes.FROM_DOCREF));
      // m_keywords.put(new StringKey(FROM_ID_STRING), new 
Integer(OpCodes.FROM_ID));
      // m_keywords.put(new StringKey(FROM_IDREF_STRING), new 
Integer(OpCodes.FROM_IDREF));
  
      m_keywords.put(new StringKey(FUNC_ID_STRING), new 
Integer(FunctionTable.FUNC_ID));
      m_keywords.put(new StringKey(FUNC_KEY_STRING), new 
Integer(FunctionTable.FUNC_KEY));
      // m_keywords.put(new StringKey(FUNC_DOCUMENT_STRING), new 
Integer(FunctionTable.FUNC_DOC));
  
      m_functions.put(new StringKey(FUNC_CURRENT_STRING), new 
Integer(FunctionTable.FUNC_CURRENT));
      m_functions.put(new StringKey(FUNC_LAST_STRING), new 
Integer(FunctionTable.FUNC_LAST));
      m_functions.put(new StringKey(FUNC_POSITION_STRING), new 
Integer(FunctionTable.FUNC_POSITION));
      m_functions.put(new StringKey(FUNC_COUNT_STRING), new 
Integer(FunctionTable.FUNC_COUNT));
      m_functions.put(new StringKey(FUNC_ID_STRING), new 
Integer(FunctionTable.FUNC_ID));
      m_functions.put(new StringKey(FUNC_KEY_STRING), new 
Integer(FunctionTable.FUNC_KEY));
      // m_functions.put(new StringKey(FUNC_DOCUMENT_STRING), new 
Integer(FunctionTable.FUNC_DOC));
      m_functions.put(new StringKey(FUNC_LOCAL_PART_STRING), new 
Integer(FunctionTable.FUNC_LOCAL_PART));
      m_functions.put(new StringKey(FUNC_NAMESPACE_STRING), new 
Integer(FunctionTable.FUNC_NAMESPACE));
      m_functions.put(new StringKey(FUNC_NAME_STRING), new 
Integer(FunctionTable.FUNC_QNAME));
      m_functions.put(new StringKey(FUNC_GENERATE_ID_STRING), new 
Integer(FunctionTable.FUNC_GENERATE_ID));
      m_functions.put(new StringKey(FUNC_NOT_STRING), new 
Integer(FunctionTable.FUNC_NOT));
      m_functions.put(new StringKey(FUNC_TRUE_STRING), new 
Integer(FunctionTable.FUNC_TRUE));
      m_functions.put(new StringKey(FUNC_FALSE_STRING), new 
Integer(FunctionTable.FUNC_FALSE));
      m_functions.put(new StringKey(FUNC_BOOLEAN_STRING), new 
Integer(FunctionTable.FUNC_BOOLEAN));
      m_functions.put(new StringKey(FUNC_LANG_STRING), new 
Integer(FunctionTable.FUNC_LANG));
      m_functions.put(new StringKey(FUNC_NUMBER_STRING), new 
Integer(FunctionTable.FUNC_NUMBER));
      m_functions.put(new StringKey(FUNC_FLOOR_STRING), new 
Integer(FunctionTable.FUNC_FLOOR));
      m_functions.put(new StringKey(FUNC_CEILING_STRING), new 
Integer(FunctionTable.FUNC_CEILING));
      m_functions.put(new StringKey(FUNC_ROUND_STRING), new 
Integer(FunctionTable.FUNC_ROUND));
      m_functions.put(new StringKey(FUNC_SUM_STRING), new 
Integer(FunctionTable.FUNC_SUM));
      m_functions.put(new StringKey(FUNC_STRING_STRING), new 
Integer(FunctionTable.FUNC_STRING));
      m_functions.put(new StringKey(FUNC_STARTS_WITH_STRING), new 
Integer(FunctionTable.FUNC_STARTS_WITH));
      m_functions.put(new StringKey(FUNC_CONTAINS_STRING), new 
Integer(FunctionTable.FUNC_CONTAINS));
      m_functions.put(new StringKey(FUNC_SUBSTRING_BEFORE_STRING), new 
Integer(FunctionTable.FUNC_SUBSTRING_BEFORE));
      m_functions.put(new StringKey(FUNC_SUBSTRING_AFTER_STRING), new 
Integer(FunctionTable.FUNC_SUBSTRING_AFTER));
      m_functions.put(new StringKey(FUNC_NORMALIZE_SPACE_STRING), new 
Integer(FunctionTable.FUNC_NORMALIZE_SPACE));
      m_functions.put(new StringKey(FUNC_TRANSLATE_STRING), new 
Integer(FunctionTable.FUNC_TRANSLATE));
      m_functions.put(new StringKey(FUNC_CONCAT_STRING), new 
Integer(FunctionTable.FUNC_CONCAT));
      //m_functions.put(new StringKey(FUNC_FORMAT_NUMBER_STRING), new 
Integer(FunctionTable.FUNC_FORMAT_NUMBER));
      m_functions.put(new StringKey(FUNC_SYSTEM_PROPERTY_STRING), new 
Integer(FunctionTable.FUNC_SYSTEM_PROPERTY));
      m_functions.put(new StringKey(FUNC_EXT_FUNCTION_AVAILABLE_STRING), new 
Integer(FunctionTable.FUNC_EXT_FUNCTION_AVAILABLE));
      m_functions.put(new StringKey(FUNC_EXT_ELEM_AVAILABLE_STRING), new 
Integer(FunctionTable.FUNC_EXT_ELEM_AVAILABLE));
      m_functions.put(new StringKey(FUNC_SUBSTRING_STRING), new 
Integer(FunctionTable.FUNC_SUBSTRING));
      m_functions.put(new StringKey(FUNC_STRING_LENGTH_STRING), new 
Integer(FunctionTable.FUNC_STRING_LENGTH));
      m_functions.put(new StringKey(FUNC_UNPARSED_ENTITY_URI_STRING), new 
Integer(FunctionTable.FUNC_UNPARSED_ENTITY_URI));
  
      // These aren't really functions.
      m_functions.put(new StringKey(NODETYPE_COMMENT_STRING), new 
Integer(OpCodes.NODETYPE_COMMENT));
      m_functions.put(new StringKey(NODETYPE_TEXT_STRING), new 
Integer(OpCodes.NODETYPE_TEXT));
      m_functions.put(new StringKey(NODETYPE_PI_STRING), new 
Integer(OpCodes.NODETYPE_PI));
      m_functions.put(new StringKey(NODETYPE_NODE_STRING), new 
Integer(OpCodes.NODETYPE_NODE));
  
      m_functions.put(new StringKey(FUNC_DOCLOCATION_STRING), new 
Integer(FunctionTable.FUNC_DOCLOCATION));
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/Lexer.java
  
  Index: Lexer.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.apache.xalan.utils.PrefixResolver;
  import java.util.Vector;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  /**
   * This class is in charge of lexical processing of the XPath 
   * expression into tokens.
   */
  class Lexer
  {
    /**
     * The target XPath.
     */
    private XPath m_xpath;
    
    /**
     * The prefix resolver to map prefixes to namespaces in the XPath.
     */
    PrefixResolver m_namespaceContext;
    
    /**
     * The XPath processor object.
     */
    XPathParser m_processor;
    
    /**
     * This value is added to each element name in the TARGETEXTRA
     * that is a 'target' (right-most top-level element name).
     */
    static final int TARGETEXTRA = 10000;
    
    /**
     * Ignore this, it is going away.
     * This holds a map to the m_tokenQueue that tells where the top-level 
elements are.
     * It is used for pattern matching so the m_tokenQueue can be walked 
backwards.
     * Each element that is a 'target', (right-most top level element name) has 
     * TARGETEXTRA added to it.
     * 
     */
    private int m_patternMap[] = new int[100];
    
    /**
     * Ignore this, it is going away.
     * The number of elements that m_patternMap maps;
     */
    private int m_patternMapSize;
  
  
    /**
     * Create a Lexer object.
     */
    Lexer(XPath xpath, PrefixResolver resolver, XPathParser xpathProcessor)
    {
      m_xpath = xpath;
      m_namespaceContext = resolver;
      m_processor = xpathProcessor;
    }
  
    /**
     * Walk through the expression and build a token queue, and a map of the 
top-level
     * elements.
     * @param pat XSLT Expression.
     */
    void tokenize(String pat)
      throws org.xml.sax.SAXException
    {
      tokenize(pat, null);
    }
  
    /**
     * Walk through the expression and build a token queue, and a map of the 
top-level
     * elements.
     * @param pat XSLT Expression.
     * @param targetStrings Vector to hold Strings, may be null.
     */
    void tokenize(String pat, Vector targetStrings)
      throws org.xml.sax.SAXException
    {
      m_xpath.m_tokenQueueSize = 0;
      m_xpath.m_currentPattern = pat;
      m_patternMapSize = 0;
      m_xpath.m_opMap = new int[XPath.MAXTOKENQUEUESIZE*5];
      int nChars = pat.length();
      int startSubstring = -1;
      int posOfNSSep = -1;
      boolean isStartOfPat = true;
      boolean isAttrName = false;
      boolean isNum = false;
  
      // Nesting of '[' so we can know if the given element should be
      // counted inside the m_patternMap.
      int nesting = 0;
  
      // char[] chars = pat.toCharArray();
      for(int i = 0; i < nChars; i++)
      {
        char c = pat.charAt(i);
        switch(c)
        {
        case '\"':
          {
            if(startSubstring != -1)
            {
              isNum = false;
              isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, 
isAttrName);
              isAttrName = false;
              if(-1 != posOfNSSep)
              {
                posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
              }
              else
              {
                addToTokenQueue(pat.substring(startSubstring, i));
              }
            }
            startSubstring = i;
            for(i++; (i < nChars) && ((c = pat.charAt(i)) != '\"'); i++);
            if(c == '\"')
            {
              addToTokenQueue(pat.substring(startSubstring, i+1));
              startSubstring = -1;
            }
            else
            {
              m_processor.error(XPATHErrorResources.ER_EXPECTED_DOUBLE_QUOTE, 
null); //"misquoted literal... expected double quote!");
            }
          }
          break;
  
        case '\'':
          if(startSubstring != -1)
          {
            isNum = false;
            isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
            isAttrName = false;
            if(-1 != posOfNSSep)
            {
              posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
            }
            else
            {
              addToTokenQueue(pat.substring(startSubstring, i));
            }
          }
          startSubstring = i;
          for(i++; (i < nChars) && ((c = pat.charAt(i)) != '\''); i++);
          if(c == '\'')
          {
            addToTokenQueue(pat.substring(startSubstring, i+1));
            startSubstring = -1;
          }
          else
          {
            m_processor.error(XPATHErrorResources.ER_EXPECTED_SINGLE_QUOTE, 
null); //"misquoted literal... expected single quote!");
          }
          break;
  
        case 0x0A:
        case 0x0D:
        case ' ':
        case '\t':
          if(startSubstring != -1)
          {
            isNum = false;
            isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
            isAttrName = false;
            if(-1 != posOfNSSep)
            {
              posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
            }
            else
            {
              addToTokenQueue(pat.substring(startSubstring, i));
            }
            startSubstring = -1;
          }
          break;
  
        case '@':
          isAttrName = true;
          // fall-through on purpose
  
        case '-':
          if('-' == c)
          {
            if(!(isNum || (startSubstring == -1)))
            {
              break;
            }
            isNum = false;
          }
          // fall-through on purpose
  
        case '(':
        case '[':
        case ')':
        case ']':
        case '|':
        case '/':
        case '*':
        case '+':
        case '=':
        case ',':
        case '\\': // Unused at the moment
        case '^': // Unused at the moment
        case '!': // Unused at the moment
        case '$':
        case '<':
        case '>':
          if(startSubstring != -1)
          {
            isNum = false;
            isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
            isAttrName = false;
            if(-1 != posOfNSSep)
            {
              posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
            }
            else
            {
              addToTokenQueue(pat.substring(startSubstring, i));
            }
            startSubstring = -1;
          }
          else if(('/' == c) && isStartOfPat)
          {
            isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
          }
          else if('*' == c)
          {
            isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
            isAttrName = false;
          }
  
          if(0 == nesting)
          {
            if('|' == c)
            {
              if(null != targetStrings)
              {
                recordTokenString(targetStrings);
              }
              isStartOfPat = true;
            }
          }
          if((')' == c) || (']' == c))
          {
            nesting--;
          }
          else if(('(' == c) || ('[' == c))
          {
            nesting++;
          }
          addToTokenQueue(pat.substring(i, i+1));
  
         break;
  
        case ':':
         if(posOfNSSep == (i-1))
         {
           if(startSubstring != -1)
           {
             if(startSubstring < (i-1))
               addToTokenQueue(pat.substring(startSubstring, i-1));
           }
           isNum = false;
           isAttrName = false;
           startSubstring = -1;
           posOfNSSep = -1;
  
           addToTokenQueue(pat.substring(i-1, i+1));
           break;
         }
         else
         {
           posOfNSSep = i;
         }
          // fall through on purpose
  
        default:
          if(-1 == startSubstring)
          {
            startSubstring = i;
            isNum = Character.isDigit(c);
          }
          else if(isNum)
          {
            isNum = Character.isDigit(c);
          }
        }
      }
      if(startSubstring != -1)
      {
        isNum = false;
        isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
        if(-1 != posOfNSSep)
        {
          posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, nChars);
        }
        else
        {
          addToTokenQueue(pat.substring(startSubstring, nChars));
        }
      }
  
      if(0 == m_xpath.m_tokenQueueSize)
      {
        m_processor.error(XPATHErrorResources.ER_EMPTY_EXPRESSION, null); 
//"Empty expression!");
      }
      else if(null != targetStrings)
      {
        recordTokenString(targetStrings);
      }
      m_processor.m_queueMark = 0;
    }
  
    /**
     * Record the current position on the token queue as long as
     * this is a top-level element.  Must be called before the
     * next token is added to the m_tokenQueue.
     */
    private boolean mapPatternElemPos(int nesting, boolean isStart, boolean 
isAttrName)
    {
      if(0 == nesting)
      {
        if(!isStart)
        {
          m_patternMap[m_patternMapSize-1] -= TARGETEXTRA;
        }
        m_patternMap[m_patternMapSize]
          = (m_xpath.m_tokenQueueSize - (isAttrName ? 1 : 0)) + TARGETEXTRA;
        m_patternMapSize++;
        isStart = false;
      }
      return isStart;
    }
    
    /**
     * Given a map pos, return the corresponding token queue pos.
     */
    private int getTokenQueuePosFromMap(int i)
    {
      int pos = m_patternMap[i];
      return (pos >= TARGETEXTRA) ? (pos - TARGETEXTRA) : pos;
    }
    
    /**
     * Reset token queue mark and m_token to a
     * given position.
     * @param mark The new position.
     */
    private final void resetTokenMark(int mark)
    {
      int qsz = m_xpath.m_tokenQueueSize;
      m_processor.m_queueMark = (mark > 0) ? ((mark <= qsz) ? mark -1 : mark) : 
0;
      if( m_processor.m_queueMark < qsz )
      {
        m_processor.m_token = 
(String)m_xpath.m_tokenQueue[m_processor.m_queueMark++];
        m_processor.m_tokenChar = m_processor.m_token.charAt(0);
      }
      else
      {
        m_processor.m_token = null;
        m_processor.m_tokenChar = 0;
      }
    }
    
    /**
     * Given a string, return the corresponding keyword token.
     */
    final int getKeywordToken(String key)
    {
      int tok;
      try
      {
        Integer itok = (Integer)Keywords.m_keywords.get(key);
        tok = (null != itok) ? itok.intValue() : 0;
      }
      catch(NullPointerException npe)
      {
        tok = 0;
      }
      catch(ClassCastException cce)
      {
        tok = 0;
      }
      return tok;
    }
  
    /**
     * Record the correct token string in the passed vector.
     */
    private void recordTokenString(Vector targetStrings)
    {
      int tokPos = getTokenQueuePosFromMap(m_patternMapSize-1);
      resetTokenMark(tokPos+1);
  
      if(m_processor.lookahead('(', 1))
      {
        int tok = getKeywordToken(m_processor.m_token);
        switch(tok)
        {
        case OpCodes.NODETYPE_COMMENT:
          targetStrings.addElement(PsuedoNames.PSEUDONAME_COMMENT);
          break;
        case OpCodes.NODETYPE_TEXT:
          targetStrings.addElement(PsuedoNames.PSEUDONAME_TEXT);
          break;
        case OpCodes.NODETYPE_NODE:
          targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
          break;
        case OpCodes.NODETYPE_ROOT:
          targetStrings.addElement(PsuedoNames.PSEUDONAME_ROOT);
          break;
        case OpCodes.NODETYPE_ANYELEMENT:
          targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
          break;
        case OpCodes.NODETYPE_PI:
          targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
          break;
        default:
          targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
        }
      }
      else
      {
        if(m_processor.tokenIs('@'))
        {
          tokPos++;
          resetTokenMark(tokPos+1);
        }
        if(m_processor.lookahead(':', 1))
        {
          tokPos += 2;
        }
        targetStrings.addElement(m_xpath.m_tokenQueue[tokPos]);
      }
    }
  
    private final void addToTokenQueue(String s)
    {
      m_xpath.m_tokenQueue[m_xpath.m_tokenQueueSize++] = s;
    }
    
    /**
     * When a seperator token is found, see if there's a element name or
     * the like to map.
     */
    private int mapNSTokens(String pat, int startSubstring, int posOfNSSep, int 
posOfScan)
    {
      String prefix = pat.substring(startSubstring, posOfNSSep);
      String uName;
      if((null != m_namespaceContext) && !prefix.equals("*") && 
!prefix.equals("xmlns"))
      {
        try
        {
          if(prefix.length() > 0)
            uName = 
((PrefixResolver)m_namespaceContext).getNamespaceForPrefix(prefix);
          else
          {
            // Assume last was wildcard. This is not legal according
            // to the draft. Set the below to true to make namespace
            // wildcards work.
            if(false)
            {
              addToTokenQueue(":");
              String s = pat.substring(posOfNSSep+1, posOfScan);
              if(s.length() > 0)
                addToTokenQueue(s);
              return -1;
            }
            else
            {
              uName = 
((PrefixResolver)m_namespaceContext).getNamespaceForPrefix(prefix);
            }
          }
        }
        catch(ClassCastException cce)
        {
          uName = m_namespaceContext.getNamespaceForPrefix(prefix);
        }
      }
      else
      {
        uName = prefix;
      }
      if((null != uName) && (uName.length() > 0))
      {
        addToTokenQueue(uName);
        addToTokenQueue(":");
        String s = pat.substring(posOfNSSep+1, posOfScan);
        if(s.length() > 0)
          addToTokenQueue(s);
      }
      else
      {
        // error("Could not locate namespace for prefix: "+prefix);
        addToTokenQueue(prefix);
        addToTokenQueue(":");
        String s = pat.substring(posOfNSSep+1, posOfScan);
        if(s.length() > 0)
          addToTokenQueue(s);
      }
      return -1;
    }
  
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/LocPathIterator.java
  
  Index: LocPathIterator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  // Java library imports
  import java.util.Vector;
  import java.util.Stack;
  
  // DOM imports
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.traversal.TreeWalker;
  import org.w3c.dom.traversal.NodeFilter;
  import org.w3c.dom.Node;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.DOMException;
  
  // Xalan imports
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.OpCodes;
  import org.apache.xalan.xpath.PsuedoNames;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.utils.IntStack;
  import org.apache.xalan.utils.PrefixResolver;
  
  import org.apache.xalan.xpath.axes.AxesWalker;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This class extends NodeSet, which implements NodeIterator, 
   * and fetches nodes one at a time in document order based on a XPath
   * <a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a>.
   * 
   * <p>If setShouldCacheNodes(true) is called, 
   * as each node is iterated via nextNode(), the node is also stored 
   * in the NodeVector, so that previousNode() can easily be done, except in 
   * the case where the LocPathIterator is "owned" by a UnionPathIterator, 
   * in which case the UnionPathIterator will cache the nodes.</p>
   */
  public class LocPathIterator extends NodeSet implements Cloneable
  {
    /**
     * Create a LocPathIterator object.
     */
    public LocPathIterator(XPathContext execContext,
                           PrefixResolver nscontext,
                           Node context)
    {    
      this.m_execContext = execContext;
      this.m_stackFrameIndex = 
execContext.getVarStack().getCurrentStackFrameIndex();
      this.m_dhelper = execContext.getDOMHelper();
      this.m_currentContextNode = execContext.getCurrentNode();
      this.m_prefixResolver = nscontext;
      this.m_context = context; // 'tis the root node
    }
  
    /**
     * Create a LocPathIterator object.
     */
    public LocPathIterator(XPath xpath, XPathContext execContext, 
                           Node context, int opPos,
                           SimpleNodeLocator locator)
    {
      m_mutable = false;
      m_cacheNodes = false;
      this.m_context = context;
      this.m_execContext = execContext;
      this.m_stackFrameIndex = 
execContext.getVarStack().getCurrentStackFrameIndex();
      this.m_prefixResolver = execContext.getNamespaceContext();
      this.m_currentContextNode = execContext.getCurrentNode();
      this.m_dhelper = execContext.getDOMHelper();
      this.m_locator = locator;
      this.m_xpath = xpath;
      this.m_opPos = opPos;
      
      m_firstStepPos = xpath.getFirstChildPos(opPos);
      this.loadIterators(m_firstStepPos, 0);
      // allocateWalkerStacks(m_firstStepPos);
    }
    
    /**
     * Create a LocPathIterator object (for match patterns.
     */
    public LocPathIterator(XPath xpath, XPathContext execContext, 
                           Node context, int opPos,
                           SimpleNodeLocator locator,
                           boolean isMatchPattern)
    {
      m_mutable = false;
      m_cacheNodes = false;
      this.m_context = context;
      this.m_execContext = execContext;
      this.m_stackFrameIndex = 
execContext.getVarStack().getCurrentStackFrameIndex();
      this.m_prefixResolver = execContext.getNamespaceContext();
      this.m_dhelper = execContext.getDOMHelper();
      this.m_locator = locator;
      this.m_xpath = xpath;
      this.m_opPos = opPos;
      
      loadOneIterator(opPos);
      // m_firstStepPos = xpath.getFirstChildPos(opPos);
      // allocateWalkerStacks(firstStepPos);
    }
    
    /**
     * Get a cloned LocPathIterator.
     */
    public Object clone()
      throws CloneNotSupportedException
    {
      LocPathIterator clone = (LocPathIterator)super.clone();
      AxesWalker walker = m_firstWalker;
      AxesWalker prevClonedWalker = null;
      while(null != walker)
      {
        AxesWalker clonedWalker = (AxesWalker)walker.clone();
        clonedWalker.setLocPathIterator(clone);
        if(clone.m_lastUsedWalker == walker)
          clone.m_lastUsedWalker = clonedWalker;
        if(null == prevClonedWalker)
        {
          clone.m_firstWalker = clonedWalker;
          prevClonedWalker = clonedWalker;
        }
        else
        {
          prevClonedWalker.setNextWalker(clonedWalker);
          clonedWalker.setPrevWalker(prevClonedWalker);
          prevClonedWalker = clonedWalker;
        }
        walker = walker.getNextWalker();
      }
  
      return clone;
    }
    
    /**
     * Reset the iterator.
     */
    public void reset()
    {
      super.reset();
      m_foundLast = false;
      m_lastFetched = null;
      m_lastUsedWalker = m_firstWalker;
      m_firstWalker.setRoot(m_context);
    }
    
    /**
     *  Returns the next node in the set and advances the position of the 
     * iterator in the set. After a NodeIterator is created, the first call 
     * to nextNode() returns the first node in the set.
     * @return  The next <code>Node</code> in the set being iterated over, or
     *   <code>null</code> if there are no more members in that set.
     * @exception DOMException
     *    INVALID_STATE_ERR: Raised if this method is called after the
     *   <code>detach</code> method was invoked.
     */
    public Node nextNode()
      throws DOMException
    {  
      // If the cache is on, and the node has already been found, then 
      // just return from the list.
      if(this.m_cacheNodes && (m_next < this.size()))
      {
        return super.nextNode();
      }
  
      if(null == m_firstWalker.getRoot())
      {
        m_next = 0;
        m_firstWalker.setRoot(m_context);
        m_lastUsedWalker = m_firstWalker;
      }
      return returnNextNode(m_firstWalker.nextNode());
    }
    
    /**
     * Bottleneck the return of a next node, to make returns 
     * easier from nextNode().
     */
    private Node returnNextNode(Node nextNode)
    {
      if(null != nextNode)
      {
        if(this.m_cacheNodes)
          this.addElement(nextNode);
        m_next++;
      }
      m_lastFetched = nextNode;
      if(null == nextNode)
        m_foundLast = true;
      return nextNode;
    }
    
    /**
     * Return the last fetched node.  Needed to support the UnionPathIterator.
     */
    public Node getCurrentNode()
    {
      return m_lastFetched;
    }
    
    /**
     * If an index is requested, NodeSet will call this method 
     * to run the iterator to the index.  By default this sets 
     * m_next to the index.  If the index argument is -1, this 
     * signals that the iterator should be run to the end.
     */
    public void runTo(int index)
    {
      if(m_foundLast || ((index >= 0) && (index <= m_next)))
        return;
      
      Node n;
      if(-1 == index)
      {
        while(null != (n = nextNode()))
          ;
      }
      else
      {
        while(null != (n = nextNode()))
        {
          if(m_next >= index)
            break;
        }
      }
    }
      
    /**
     * Create the proper iterator from the axes type.
     */
    public AxesWalker createIterator(int stepType, LocPathIterator lpi)
    {
      return AxesWalker.createDefaultWalker(stepType, lpi);
    }
                
    /**
     * List of AxesIterators.
     */
    private Stack m_savedAxesWalkers = new Stack();
    
    /**
     * <meta name="usage" content="advanced"/>
     * This method is for building an array of possible levels
     * where the target element(s) could be found for a match.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     */
    protected void loadOneIterator(int stepOpCodePos)
    {
      int stepType = m_xpath.getOpMap()[stepOpCodePos];
      if( stepType != OpCodes.ENDOP )
      {
        // m_axesWalkers = new AxesWalker[1];
        
        // As we unwind from the recursion, create the iterators.
        AxesWalker ai = createIterator(stepType, this);
        ai.init(stepOpCodePos, stepType);
        m_firstWalker = ai;
      }
    }
            
    /**
     * <meta name="usage" content="advanced"/>
     * This method is for building an array of possible levels
     * where the target element(s) could be found for a match.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     */
    protected void loadIterators(int stepOpCodePos, int stepIndex)
    {
      int stepType;
      AxesWalker walker, prevWalker = null;
      int ops[] = m_xpath.getOpMap();
      while( OpCodes.ENDOP != (stepType = ops[stepOpCodePos]) )
      {      
        // As we unwind from the recursion, create the iterators.
        walker = createIterator(stepType, this);
        walker.init(stepOpCodePos, stepType);
        if(null == m_firstWalker)
        {
          m_firstWalker = walker;
          m_lastUsedWalker = walker;
        }
        else
        {
          prevWalker.setNextWalker(walker);
          walker.setPrevWalker(prevWalker);
        }
        prevWalker = walker;
        stepOpCodePos = m_xpath.getNextStepPos(stepOpCodePos);
        if(stepOpCodePos < 0)
          break;
      }
    }
    
    /**
     * 
     */
    // protected AxesWalker[] m_axesWalkers;
    protected AxesWalker m_firstWalker;
    
    /**
     * For internal use.
     */
    public AxesWalker getFirstWalker()
    {
      return m_firstWalker;
    }
  
    /**
     * For use by the AxesWalker.
     */
    private AxesWalker m_lastUsedWalker;
  
    /**
     * For internal use.
     */
    public void setLastUsedWalker(AxesWalker walker)
    {
      m_lastUsedWalker = walker;
    }
  
    /**
     * For internal use.
     */
    public AxesWalker getLastUsedWalker()
    {
      return m_lastUsedWalker;
    }
    
    // Temp as vector.  This probably ought to be a heap/priority queue.
    public Vector m_waiting = new Vector();
    
    public void addToWaitList(AxesWalker walker)
    {
      m_waiting.addElement(walker);
    }
    
    public void removeFromWaitList(AxesWalker walker)
    {
      m_waiting.removeElement(walker);
    }
    
    /**
     * The last fetched node.
     */
    Node m_lastFetched;
      
    /**
     * Tells if we've found the last node yet.
     */
    public boolean getFoundLast() { return m_foundLast; }
    protected boolean m_foundLast = false;
    
    /**
     * The XPath we are operating on.
     */
    protected XPath m_xpath;
    public XPath getXPath() { return m_xpath; }
    
    /**
     * The op position of this iterator.
     */
    protected int m_opPos;
  
    /**
     * The first step position of this iterator.
     */
    protected int m_firstStepPos;
  
    /**
     * The XPath execution context we are operating on.
     */
    protected XPathContext m_execContext;
    public XPathContext getXPathContext() { return m_execContext; }
    
    /**
     * The DOM helper for the given context;
     */
    protected DOMHelper m_dhelper;
    public DOMHelper getDOMHelper() { return m_dhelper; }
    
    /**
     * The node context for the expression.
     */
    protected Node m_context;
    public Node getContext() { return m_context; }
  
    /**
     * The node context for the expression.
     */
    protected int m_stackFrameIndex;
    public int getStackFrameIndex() { return m_stackFrameIndex; }
  
    /**
     * The node context from where the expression is being 
     * executed from (i.e. for current() support).
     */
    protected Node m_currentContextNode;
    public Node getCurrentContextNode() { return m_currentContextNode; }
  
    /**
     * Reference to the SimpleNodeLocator that created 
     * this instance.
     */
    public SimpleNodeLocator getLocator() { return m_locator; }
    protected SimpleNodeLocator m_locator;
  
    /**
     * Return the saved reference to the prefix resolver that 
     * was in effect when this iterator was created.
     */
    public PrefixResolver getPrefixResolver() { return m_prefixResolver; }
    protected PrefixResolver m_prefixResolver;
  }
  
  
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/NodeSet.java
  
  Index: NodeSet.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  import org.w3c.dom.NamedNodeMap;
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.traversal.NodeFilter;
  import org.w3c.dom.DOMException;
  import org.apache.xalan.utils.NodeVector;
  
  /**
   * <meta name="usage" content="advanced"/>
   * The NodeSet class can act as either a NodeVector, 
   * NodeList, or NodeIterator.  However, in order for it to 
   * act as a NodeVector or NodeList, it's required that 
   * setShouldCacheNodes(true) be called before the first 
   * nextNode() is called, in order that nodes can be added 
   * as they are fetched.  Derived classes that implement iterators 
   * must override runTo(int index), in order that they may 
   * run the iteration to the given index.
   */
  public class NodeSet extends 
    NodeVector implements NodeList, NodeIterator, Cloneable
  {    
    /**
     * Create an empty nodelist.
     */
    public NodeSet() 
    {
      super();
    }
  
    /**
     * Create an empty nodelist.
     */
    public NodeSet(int blocksize) 
    {
      super(blocksize);
    }
  
    /**
     * Create a NodeSet, and copy the members of the 
     * given nodelist into it.
     */
    public NodeSet(NodeList nodelist) 
    {
      super();
      addNodes(nodelist);
    }
    
    /**
     * Create a NodeSet, and copy the members of the 
     * given NodeSet into it.
     */
    public NodeSet(NodeSet nodelist) 
    {
      super();
      addNodes((NodeIterator)nodelist);
    }
  
    
    /**
     * Create a NodeSet, and copy the members of the 
     * given nodelist into it.
     */
    public NodeSet(NodeIterator ni) 
    {
      super();
      addNodes(ni);
    }
  
  
    /**
     * Create a NodeSet, and copy the members of the 
     * given nodelist into it.
     */
    public NodeSet(Node node) 
    {
      super();
      addNode(node);
    }
    
    /**
     *  The root node of the Iterator, as specified when it was created.
     */
    public Node getRoot()
    {
      return null;
    }
    
    /**
     * Get a cloned LocPathIterator.
     */
    public Object clone()
      throws CloneNotSupportedException
    {
      NodeSet clone = (NodeSet)super.clone();
      return clone;
    }
    
    /**
     * Get a cloned LocPathIterator.
     */
    public NodeSet cloneWithReset()
      throws CloneNotSupportedException
    {
      NodeSet clone = (NodeSet)clone();
      clone.reset();
      return clone;
    }
  
    
    /**
     * Reset the iterator.
     */
    public void reset()
    {
      m_next = 0;
    }
  
    /**
     *  This attribute determines which node types are presented via the 
     * iterator. The available set of constants is defined in the 
     * <code>NodeFilter</code> interface.
     */
    public int getWhatToShow()
    {
      return NodeFilter.SHOW_ALL & ~NodeFilter.SHOW_ENTITY_REFERENCE;
    }
  
    /**
     *  The filter used to screen nodes.
     */
    public NodeFilter getFilter()
    {
      return null;
    }
  
    /**
     *  The value of this flag determines whether the children of entity 
     * reference nodes are visible to the iterator. If false, they will be 
     * skipped over.
     * <br> To produce a view of the document that has entity references 
     * expanded and does not expose the entity reference node itself, use the 
     * whatToShow flags to hide the entity reference node and set 
     * expandEntityReferences to true when creating the iterator. To produce 
     * a view of the document that has entity reference nodes but no entity 
     * expansion, use the whatToShow flags to show the entity reference node 
     * and set expandEntityReferences to false.
     */
    public boolean getExpandEntityReferences()
    {
      return true;
    }
  
    /**
     *  Returns the next node in the set and advances the position of the 
     * iterator in the set. After a NodeIterator is created, the first call 
     * to nextNode() returns the first node in the set.
     * @return  The next <code>Node</code> in the set being iterated over, or
     *   <code>null</code> if there are no more members in that set.
     * @exception DOMException
     *    INVALID_STATE_ERR: Raised if this method is called after the
     *   <code>detach</code> method was invoked.
     */
    public Node nextNode()
      throws DOMException
    {
      if((m_next) < this.size())
      {
        Node next = this.elementAt(m_next);
        m_next++;
        return next;
      }
      else
        return null;
    }
  
    /**
     *  Returns the previous node in the set and moves the position of the 
     * iterator backwards in the set.
     * @return  The previous <code>Node</code> in the set being iterated over, 
     *   or<code>null</code> if there are no more members in that set. 
     * @exception DOMException
     *    INVALID_STATE_ERR: Raised if this method is called after the
     *   <code>detach</code> method was invoked.
     */
    public Node previousNode()
      throws DOMException
    {
      if(!m_cacheNodes)
        throw new RuntimeException("This NodeSet can not iterate to a previous 
node!");
      
      if((m_next-1) > 0)
      {
        m_next--;
        return this.elementAt(m_next);
      }
      else
        return null;
    }
  
    /**
     *  Detaches the iterator from the set which it iterated over, releasing 
     * any computational resources and placing the iterator in the INVALID 
     * state. After<code>detach</code> has been invoked, calls to 
     * <code>nextNode</code> or<code>previousNode</code> will raise the 
     * exception INVALID_STATE_ERR.
     */
    public void detach()
    {
    }
    
    /**
     * Tells if this NodeSet is "fresh", in other words, if 
     * the first nextNode() that is called will return the 
     * first node in the set.
     */
    public boolean isFresh()
    {
      return (m_next == 0);
    }
      
    /**
     * If an index is requested, NodeSet will call this method 
     * to run the iterator to the index.  By default this sets 
     * m_next to the index.  If the index argument is -1, this 
     * signals that the iterator should be run to the end.
     */
    public void runTo(int index)
    {
      if(!m_cacheNodes)
        throw new RuntimeException("This NodeSet can not do indexing or 
counting functions!");
      if((index >= 0) && (m_next < m_firstFree))
        m_next = index;
      else
        m_next = m_firstFree-1;
    }
    
    /**
     * Returns the <code>index</code>th item in the collection. If 
     * <code>index</code> is greater than or equal to the number of nodes in 
     * the list, this returns <code>null</code>.
     * @param index Index into the collection.
     * @return The node at the <code>index</code>th position in the 
     *   <code>NodeList</code>, or <code>null</code> if that is not a valid 
     *   index.
     */
    public Node item(int index)
    {
      runTo(index);
      return (Node)this.elementAt(index);
    }
    
    /**
     * The number of nodes in the list. The range of valid child node indices 
is 
     * 0 to <code>length-1</code> inclusive. 
     */
    public int getLength()
    {
      runTo(-1);
      return this.size();
    }
  
    /**
     * Add a node.
     */
    public void addNode(Node n)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      this.addElement(n);
  
    }
  
    /**
     * Insert a node at a given position.
     */
    public void insertNode(Node n, int pos)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      insertElementAt(n, pos);
    }
  
    /**
     * Remove a node.
     */
    public void removeNode(Node n)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      this.removeElement(n);
    }
  
    /**
     * Copy NodeList members into this nodelist, adding in 
     * document order.  If a node is null, don't add it.
     */
    public void addNodes(NodeList nodelist)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      if(null != nodelist) // defensive to fix a bug that Sanjiva reported.
      {
        int nChildren = nodelist.getLength();
        for(int i = 0; i < nChildren; i++)
        {
          Node obj = nodelist.item(i);
          if(null != obj)
          {
            addElement(obj);
          }
        }
      }
      // checkDups();
    }
    
    /**
     * Copy NodeList members into this nodelist, adding in 
     * document order.  If a node is null, don't add it.
     */
    public void addNodes(NodeSet ns)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      addNodes((NodeIterator)ns);
    }
  
    
    /**
     * Copy NodeList members into this nodelist, adding in 
     * document order.  If a node is null, don't add it.
     */
    public void addNodes(NodeIterator iterator)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      if(null != iterator) // defensive to fix a bug that Sanjiva reported.
      {
        Node obj;
        while(null != (obj = iterator.nextNode()))
          addElement(obj);
      }
      // checkDups();
    }
  
  
    /**
     * Copy NodeList members into this nodelist, adding in 
     * document order.  If a node is null, don't add it.
     */
    public void addNodesInDocOrder(NodeList nodelist, XPathContext support)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      int nChildren = nodelist.getLength();
      for(int i = 0; i < nChildren; i++)
      {
        Node node = nodelist.item(i);
        if(null != node)
        {
          addNodeInDocOrder(node, support);
        }
      }
    }
    
    /**
     * Copy NodeList members into this nodelist, adding in 
     * document order.  If a node is null, don't add it.
     */
    public void addNodesInDocOrder(NodeIterator iterator, XPathContext support)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      Node node;
      while(null != (node = iterator.nextNode()))
        addNodeInDocOrder(node, support);
    }
  
    
    /**
     * Not yet ready for prime time.
     * I can't use recursion in this.
     */
    private boolean addNodesInDocOrder(int start, int end, int testIndex, 
                                       NodeList nodelist, XPathContext support)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
  
      boolean foundit = false;
      int i;
      Node node = nodelist.item(testIndex);
      for(i = end; i >= start; i--)
      {
        Node child = (Node)elementAt(i);
        if(child == node)
        {
          i = -2; // Duplicate, suppress insert
          break; 
        }
        if(!support.getDOMHelper().isNodeAfter(node, child))
        {
          insertElementAt(node, i+1);
          testIndex--;
          if(testIndex > 0)
          {
            boolean foundPrev 
              = addNodesInDocOrder(0, i, testIndex, nodelist, support);
            if(!foundPrev)
            {
              addNodesInDocOrder(i, size()-1, testIndex, nodelist, support);
            }
          }
          break;
        }
      }
      if(i == -1)
      {
        insertElementAt(node, 0);
      }
      return foundit;
    }
    
  
    /**
     * Add the node into a vector of nodes where it should occur in 
     * document order.
     * @param v Vector of nodes, presumably containing Nodes
     * @param obj Node object.
     * @param test true if we should test for doc order
     * @return insertIndex.
     */
    public int addNodeInDocOrder(Node node, boolean test, XPathContext support)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      
      int insertIndex = -1;
      if(test)
      {
        try
        {
          int index1 = ((org.apache.xalan.dtm.DTMProxy)node).getDTMNodeNumber();
          
          // This needs to do a binary search, but a binary search 
          // is somewhat tough because the sequence test involves 
          // two nodes.
          int size = size(), i;
          for(i = size-1; i >= 0; i--)
          {
            Node node2 = (Node)elementAt(i);
            // Check to see if the nodes share the same parent.  If they 
            // do not, then don't try to sort with it.
            if(!((((1 == index1) && (node == node2)) ||
               (node.getOwnerDocument() == node2.getOwnerDocument()))))
            {
              continue;
            }
            int index2 = 
((org.apache.xalan.dtm.DTMProxy)node2).getDTMNodeNumber();
            if((index2 == index1))
            {
              i = -2; // Duplicate, suppress insert
              break; 
            }
            if(index2 < index1)
            {
              break;
            }
          }
          if(i != -2)
          {
            insertIndex = i+1;
            insertElementAt(node, insertIndex);
          }
          
        }
        catch(ClassCastException cce)
        {
          // This needs to do a binary search, but a binary search 
          // is somewhat tough because the sequence test involves 
          // two nodes.
          int size = size(), i;
          for(i = size-1; i >= 0; i--)
          {
            Node child = (Node)elementAt(i);
            if(child == node)
            {
              i = -2; // Duplicate, suppress insert
              break; 
            }
            if(!support.getDOMHelper().isNodeAfter(node, child))
            {
              break;
            }
          }
          if(i != -2)
          {
            insertIndex = i+1;
            insertElementAt(node, insertIndex);
          }
        }
      }
      else
      {
        insertIndex = this.size();
        boolean foundit = false;
        for(int i = 0; i < insertIndex; i++)
        {
          if(this.item(i).equals(node))
          {
            foundit = true;
            break;
          }
        }
        if(!foundit)
          addElement(node);
      }
      // checkDups();
      return insertIndex;
    } // end addNodeInDocOrder(Vector v, Object obj)
  
    /**
     * Add the node into a vector of nodes where it should occur in 
     * document order.
     * @param v Vector of nodes, presumably containing Nodes
     * @param obj Node object.
     */
    public int addNodeInDocOrder(Node node, XPathContext support)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      return addNodeInDocOrder(node, true, support);
    } // end addNodeInDocOrder(Vector v, Object obj)
    
    
    /**
     * Get the length of the list.
     */
    public int size()
    {
      return super.size();
    }
  
    /**
     * Append a Node onto the vector.
     */
    public void addElement(Node value)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      super.addElement(value);
    }
  
    /**
     * Inserts the specified node in this vector at the specified index. 
     * Each component in this vector with an index greater or equal to 
     * the specified index is shifted upward to have an index one greater 
     * than the value it had previously. 
     */
    public void insertElementAt(Node value, int at)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      super.insertElementAt(value, at);
    }
    
    /**
     * Append the nodes to the list. 
     */
    public void appendNodes(NodeVector nodes)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      super.appendNodes(nodes);
    }
  
  
    /**
     * Inserts the specified node in this vector at the specified index. 
     * Each component in this vector with an index greater or equal to 
     * the specified index is shifted upward to have an index one greater 
     * than the value it had previously. 
     */
    public void removeAllElements()
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      super.removeAllElements();
    }
    
    /**
     * Removes the first occurrence of the argument from this vector. 
     * If the object is found in this vector, each component in the vector 
     * with an index greater or equal to the object's index is shifted 
     * downward to have an index one smaller than the value it had 
     * previously. 
     */
    public boolean removeElement(Node s)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      return super.removeElement(s);
    }
    
    /**
     * Deletes the component at the specified index. Each component in 
     * this vector with an index greater or equal to the specified 
     * index is shifted downward to have an index one smaller than 
     * the value it had previously. 
     */
    public void removeElementAt(int i)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      super.removeElementAt(i);
    }
    
    /**
     * Sets the component at the specified index of this vector to be the 
     * specified object. The previous component at that position is discarded. 
     * 
     * The index must be a value greater than or equal to 0 and less 
     * than the current size of the vector. 
     */
    public void setElementAt(Node node, int index)
    {
      if(!m_mutable)
        throw new RuntimeException("This NodeSet is not mutable!");
      super.setElementAt(node, index);
    }
  
    /**
     * Get the nth element.
     */
    public Node elementAt(int i)
    {
      runTo(i);
      return super.elementAt(i);
    }
    
    /**
     * Tell if the table contains the given node.
     */
    public boolean contains(Node s)
    {
      runTo(-1);
      return super.contains(s);
    }
    
    /**
     * Searches for the first occurence of the given argument, 
     * beginning the search at index, and testing for equality 
     * using the equals method. 
     * @return the index of the first occurrence of the object 
     * argument in this vector at position index or later in the 
     * vector; returns -1 if the object is not found. 
     */
    public int indexOf(Node elem, int index)
    {
      runTo(-1);
      return super.indexOf(elem, index);
    }
  
    /**
     * Searches for the first occurence of the given argument, 
     * beginning the search at index, and testing for equality 
     * using the equals method. 
     * @return the index of the first occurrence of the object 
     * argument in this vector at position index or later in the 
     * vector; returns -1 if the object is not found. 
     */
    public int indexOf(Node elem)
    {
      runTo(-1);
      return super.indexOf(elem);
    }
  
    protected int m_next = 0;
    
    /**
     * Get the current position, which is one less than 
     * the next nextNode() call will retreave.  i.e. if 
     * you call getCurrentPos() and the return is 0, the next 
     * fetch will take place at index 1.
     */
    public int getCurrentPos() { return m_next;  }
    
    /**
     * Set the current position in the node set.
     * @param i Must be a valid index.
     */
    public void setCurrentPos(int i) 
    { 
      if(!m_cacheNodes)
        throw new RuntimeException("This NodeSet can not do indexing or 
counting functions!");
      m_next = i; 
    }
    
    /**
     * Return the last fetched node.  Needed to support the UnionPathIterator.
     */
    public Node getCurrentNode()
    {
      if(!m_cacheNodes)
        throw new RuntimeException("This NodeSet can not do indexing or 
counting functions!");
      return elementAt(m_next);
    }
    
    protected boolean m_mutable = true;
    
    protected boolean m_cacheNodes = true;
    public boolean getShouldCacheNodes() { return m_cacheNodes; }
  
    /**
     * If setShouldCacheNodes(true) is called, then nodes will 
     * be cached.  They are not cached by default.
     */
    public void setShouldCacheNodes(boolean b)
    {
      if(!isFresh())
        throw new RuntimeException("Can not call setShouldCacheNodes after 
nextNode has been called!");
      m_cacheNodes = b;
      m_mutable = true;
    }
  
  }
  
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/OpCodes.java
  
  Index: OpCodes.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  /**
   * Operations codes for XPath.
   *
   * Code for the descriptions of the operations codes:
   * [UPPER CASE] indicates a literal value,
   * [lower case] is a description of a value,
   *      ([length] always indicates the length of the operation,
   *       including the operations code and the length integer.)
   * {UPPER CASE} indicates the given production,
   * {description} is the description of a new production,
   *      (For instance, {boolean expression} means some expression 
   *       that should be resolved to a boolean.)
   *  * means that it occurs zero or more times,
   *  + means that it occurs one or more times,
   *  ? means that it is optional.
   *
   * returns: indicates what the production should return.
   */
  public class OpCodes
  {
  
    /**
     * <meta name="usage" content="advanced"/>
     * [ENDOP]
     * Some operators may like to have a terminator.
     */
    public static final int ENDOP = -1;
    
    /**
     * [EMPTY]
     * Empty slot to indicate NULL.
     */
    public static final int EMPTY = -2;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [ELEMWILDCARD]
     * Means ELEMWILDCARD ("*"), used instead 
     * of string index in some places.
     */
    public static final int ELEMWILDCARD = -3;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_XPATH]
     * [length]
     *  {expression}
     * 
     * returns: 
     *  XNodeSet
     *  XNumber
     *  XString
     *  XBoolean
     *  XRTree
     *  XObject
     */
    public static final int OP_XPATH = 1;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_OR]
     * [length]
     *  {boolean expression}
     *  {boolean expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_OR = 2;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_AND]
     * [length]
     *  {boolean expression}
     *  {boolean expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_AND = 3;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_NOTEQUALS]
     * [length]
     *  {expression}
     *  {expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_NOTEQUALS = 4;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_EQUALS]
     * [length]
     *  {expression}
     *  {expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_EQUALS = 5;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_LTE] (less-than-or-equals)
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_LTE = 6;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_LT] (less-than)
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_LT = 7;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_GTE] (greater-than-or-equals)
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_GTE = 8;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_GT] (greater-than)
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_GT = 9;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_PLUS]
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XNumber
     */
    public static final int OP_PLUS = 10;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_MINUS]
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XNumber
     */
    public static final int OP_MINUS = 11;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_MULT]
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XNumber
     */
    public static final int OP_MULT = 12;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_DIV]
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XNumber
     */
    public static final int OP_DIV = 13;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_MOD]
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XNumber
     */
    public static final int OP_MOD = 14;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_QUO]
     * [length]
     *  {number expression}
     *  {number expression}
     * 
     * returns: 
     *  XNumber
     */
    public static final int OP_QUO = 15;
  
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_NEG]
     * [length]
     *  {number expression}
     * 
     * returns: 
     *  XNumber
     */
    public static final int OP_NEG = 16;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_STRING] (cast operation)
     * [length]
     *  {expression}
     * 
     * returns: 
     *  XString
     */
    public static final int OP_STRING = 17;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_BOOL] (cast operation)
     * [length]
     *  {expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_BOOL = 18;
  
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_NUMBER] (cast operation)
     * [length]
     *  {expression}
     * 
     * returns: 
     *  XBoolean
     */
    public static final int OP_NUMBER = 19;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_UNION]
     * [length]
     *  {PathExpr}+
     * 
     * returns: 
     *  XNodeSet
     */
    public static final int OP_UNION = 20;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_LITERAL]
     * [3]
     * [index to token]
     * 
     * returns: 
     *  XString
     */
    public static final int OP_LITERAL = 21;
    
    static final int FIRST_NODESET_OP = 22;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_VARIABLE]
     * [3]
     * [index to token]
     * 
     * returns: 
     *  XString
     */
    public static final int OP_VARIABLE = 22;
      
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_GROUP]
     * [length]
     *  {expression}
     * 
     * returns: 
     *  XNodeSet
     *  XNumber
     *  XString
     *  XBoolean
     *  XRTree
     *  XObject
     */
    public static final int OP_GROUP = 23;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_EXTFUNCTION] (Extension function.)
     * [length]
     * [index to namespace token]
     * [index to function name token]
     *  {OP_ARGUMENT}*
     * 
     * returns: 
     *  XNodeSet
     *  XNumber
     *  XString
     *  XBoolean
     *  XRTree
     *  XObject
     */
    public static final int OP_EXTFUNCTION = 24;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_FUNCTION]
     * [length]
     * [FUNC_name]
     *  {OP_ARGUMENT}*
     * [ENDOP]
     * 
     * returns: 
     *  XNodeSet
     *  XNumber
     *  XString
     *  XBoolean
     *  XRTree
     *  XObject
     */
    public static final int OP_FUNCTION = 25;
    
    static final int LAST_NODESET_OP = 25;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_ARGUMENT] (Function argument.)
     * [length]
     *  {expression}
     * 
     * returns: 
     *  XNodeSet
     *  XNumber
     *  XString
     *  XBoolean
     *  XRTree
     *  XObject
     */
    public static final int OP_ARGUMENT = 26;
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_NUMBERLIT] (Number literal.)
     * [3]
     * [index to token]
     * 
     * returns: 
     *  XString
     */
    public static final int OP_NUMBERLIT = 27;  
      
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_LOCATIONPATH]
     * [length]
     *   {FROM_stepType}
     * | {function}
     * {predicate}*
     * [ENDOP]
     * 
     * (Note that element and attribute namespaces and 
     * names can be wildcarded '*'.)
     * 
     * returns: 
     *  XNodeSet
     */
    public static final int OP_LOCATIONPATH = 28;
    public static final int LOCATIONPATHEX_MASK = 0x0000FFFF;
    public static final int LOCATIONPATHEX_ISSIMPLE = 0x00010000;
    public static final int OP_LOCATIONPATH_EX = (28 | 0x00010000);
      
  
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_PREDICATE]
     * [length]
     *  {expression}
     * [ENDOP] (For safety)
     * 
     * returns: 
     *  XBoolean or XNumber
     */
    public static final int OP_PREDICATE = 29;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_MATCHPATTERN]
     * [length]
     *  {PathExpr}+
     * 
     * returns: 
     *  XNodeSet
     */
    public static final int OP_MATCHPATTERN = 30;
    
    
    /**
     * <meta name="usage" content="advanced"/>
     * [OP_LOCATIONPATHPATTERN]
     * [length]
     *   {FROM_stepType}
     * | {function}{predicate}*
     * [ENDOP]
     * returns: 
     *  XNodeSet
     */
    public static final int OP_LOCATIONPATHPATTERN = 31;
  
    
    /**
     * <meta name="usage" content="advanced"/>
     * [NODETYPE_COMMENT]
     * No size or arguments.
     * Note: must not overlap function OP number!
     * 
     * returns: 
     *  XBoolean
     */
    public static final int NODETYPE_COMMENT = 1030;
      
    /**
     * <meta name="usage" content="advanced"/>
     * [NODETYPE_TEXT]
     * No size or arguments.
     * Note: must not overlap function OP number!
     * 
     * returns: 
     *  XBoolean
     */
    public static final int NODETYPE_TEXT = 1031;
      
    /**
     * <meta name="usage" content="advanced"/>
     * [NODETYPE_PI]
     * [index to token]
     * Note: must not overlap function OP number!
     * 
     * returns: 
     *  XBoolean
     */
    public static final int NODETYPE_PI = 1032;
      
    /**
     * <meta name="usage" content="advanced"/>
     * [NODETYPE_NODE]
     * No size or arguments.
     * Note: must not overlap function OP number!
     * 
     * returns: 
     *  XBoolean
     */
    public static final int NODETYPE_NODE = 1033;
      
    /**
     * <meta name="usage" content="advanced"/>
     * [NODENAME]
     * [index to ns token or EMPTY]
     * [index to name token]
     * 
     * returns: 
     *  XBoolean
     */
    public static final int NODENAME = 34;
      
    /**
     * <meta name="usage" content="advanced"/>
     * [NODETYPE_ROOT]
     * No size or arguments.
     * 
     * returns: 
     *  XBoolean
     */
    public static final int NODETYPE_ROOT = 35;
      
    /**
     * <meta name="usage" content="advanced"/>
     * [NODETYPE_ANY]
     * No size or arguments.
     * 
     * returns: 
     *  XBoolean
     */
    public static final int NODETYPE_ANYELEMENT = 36;
    
    /**
     * <meta name="usage" content="advanced"/>
     * [FROM_stepType]
     * [length, including predicates]
     * [length of just the step, without the predicates]
     * {node test}
     * {predicates}?
     * 
     * returns: 
     *  XBoolean
     */
    public static final int AXES_START_TYPES = 37;
    public static final int FROM_ANCESTORS = 37;
    public static final int FROM_ANCESTORS_OR_SELF = 38;
    public static final int FROM_ATTRIBUTES = 39;
    public static final int FROM_CHILDREN = 40;
    public static final int FROM_DESCENDANTS = 41;
    public static final int FROM_DESCENDANTS_OR_SELF = 42;
    public static final int FROM_FOLLOWING = 43;
    public static final int FROM_FOLLOWING_SIBLINGS = 44; 
    public static final int FROM_PARENT = 45;
    public static final int FROM_PRECEDING = 46;
    public static final int FROM_PRECEDING_SIBLINGS = 47;
    public static final int FROM_SELF = 48;
    public static final int FROM_NAMESPACE = 49;  
    public static final int FROM_ROOT = 50;  
    
    /**
     * <meta name="usage" content="advanced"/>
     * For match patterns.
     */
    public static final int MATCH_ATTRIBUTE = 51;  
    
    /**
     * <meta name="usage" content="advanced"/>
     * For match patterns.
     */
    public static final int MATCH_ANY_ANCESTOR = 52;  
    
    /**
     * <meta name="usage" content="advanced"/>
     * For match patterns.
     */
    public static final int MATCH_IMMEDIATE_ANCESTOR = 53; 
    
    public static final int AXES_END_TYPES = 53;
   
    private static final int NEXT_FREE_ID = 99;  
    
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/OpMap.java
  
  Index: OpMap.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import java.util.Vector;
  import org.apache.xalan.utils.QName;
  
  /**
   * This class represents the data structure basics of the XPath 
   * object.
   */
  public class OpMap
  {
    /**
     * The current pattern string, for diagnostics purposes
     */
    protected String m_currentPattern;
    
    /**
     * Get the pattern string.
     */
    public String getPatternString()
    {
      return m_currentPattern;
    }
    
    /**
     * The max size that the token queue can grow to.
     */
    static final int MAXTOKENQUEUESIZE = 500;
  
    /**
     *  TokenStack is the queue of used tokens. The current token is the token 
at the 
     * end of the m_tokenQueue. The idea is that the queue can be marked and a 
sequence
     * of tokens can be reused.
     */
    Object[] m_tokenQueue = new Object[MAXTOKENQUEUESIZE];
    
    /**
     * <meta name="usage" content="advanced"/>
     * Get the XPath as a list of tokens.
     */
    public Object[] getTokenQueue()
    {
      return m_tokenQueue;
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Get the XPath as a list of tokens.
     */
    public Object getToken(int pos)
    {
      return m_tokenQueue[pos];
    }
  
    /**
     * The current size of the token queue.
     */
    int m_tokenQueueSize = 0;
  
    /**
     * <meta name="usage" content="advanced"/>
     * Get size of the token queue.
     */
    public int getTokenQueueSize()
    {
      return m_tokenQueueSize;
    }
  
    /**
     * An operations map is used instead of a proper parse tree.  It contains 
     * operations codes and indexes into the m_tokenQueue.
     * I use an array instead of a full parse tree in order to cut down 
     * on the number of objects created.
     */
    int m_opMap[] = null;
    
    /**
     * <meta name="usage" content="advanced"/>
     * Get the opcode list that describes the XPath operations.  It contains 
     * operations codes and indexes into the m_tokenQueue.
     * I use an array instead of a full parse tree in order to cut down 
     * on the number of objects created.
     */
    public int[] getOpMap()
    {
      return m_opMap;
    }
    
    // Position indexes
    
    /**
     * <meta name="usage" content="advanced"/>
     * The length is always the opcode position + 1.
     * Length is always expressed as the opcode+length bytes, 
     * so it is always 2 or greater.
     */
    public static final int MAPINDEX_LENGTH = 1;
    
    /**
     * Replace the large arrays 
     * with a small array.
     */
    void shrink()
    {
      int map[] = m_opMap;
      int n = m_opMap[MAPINDEX_LENGTH];;
      m_opMap = new int[n+4];
      int i;
      for(i = 0; i < n; i++)
      {
        m_opMap[i] = map[i];
      }
      m_opMap[i] = 0;
      m_opMap[i+1] = 0;
      m_opMap[i+2] = 0;
          
      Object[] tokens = m_tokenQueue;
      n = m_tokenQueueSize;
      m_tokenQueue = new Object[n+4];
      for(i = 0; i < n; i++)
      {
        m_tokenQueue[i] = tokens[i];
      }
      m_tokenQueue[i] = null;
      m_tokenQueue[i+1] = null;
      m_tokenQueue[i+2] = null;
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Given an operation position, return the current op.
     * @return position of next operation in m_opMap.
     */
    public int getOp(int opPos)
    {
      return m_opMap[opPos];
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Given an operation position, return the end position, i.e. the 
     * beginning of the next operation.
     * @return position of next operation in m_opMap.
     */
    public int getNextOpPos(int opPos)
    {
      return opPos+m_opMap[opPos+1];
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * Given an operation position, return the end position, i.e. the 
     * beginning of the next operation.
     * @return position of next operation in m_opMap.
     */
    public int getNextStepPos(int opPos)
    {
      int stepType = getOp(opPos);
      if((stepType >= OpCodes.AXES_START_TYPES) && (stepType <= 
OpCodes.AXES_END_TYPES))
      {
        return getNextOpPos(opPos);
      }
      else if((stepType >= OpCodes.FIRST_NODESET_OP) && (stepType <= 
OpCodes.LAST_NODESET_OP))
      {
        int newOpPos = getNextOpPos(opPos);
        
        while(OpCodes.OP_PREDICATE == getOp(newOpPos))
          newOpPos = getNextOpPos(newOpPos);
  
        stepType = getOp(newOpPos);
        if(!((stepType >= OpCodes.AXES_START_TYPES) && (stepType <= 
OpCodes.AXES_END_TYPES)))
        {
          return OpCodes.ENDOP;
        }
        return newOpPos;
      }
      else
      {
        throw new RuntimeException("Programmer's assertion in getNextStepPos: 
unknown stepType: "+stepType);
      }
    }
  
    
    /**
     * <meta name="usage" content="advanced"/>
     * Given an operation position, return the end position, i.e. the 
     * beginning of the next operation.
     * @return position of next operation in m_opMap.
     */
    public static int getNextOpPos(int[] opMap, int opPos)
    {
      return opPos+opMap[opPos+1];
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * Given an FROM_stepType position, return the position of the 
     * first predicate, if there is one, or else this will point 
     * to the end of the FROM_stepType.
     * Example:
     *  int posOfPredicate = xpath.getNextOpPos(stepPos);
     *  boolean hasPredicates = 
     *            OpCodes.OP_PREDICATE == xpath.getOp(posOfPredicate);
     * @return position of predicate in FROM_stepType structure.
     */
    public int getFirstPredicateOpPos(int opPos)
    {
      int stepType = m_opMap[opPos];
      if((stepType >= OpCodes.AXES_START_TYPES) && (stepType <= 
OpCodes.AXES_END_TYPES))
      {
        return opPos+m_opMap[opPos+2];
      }
      else if((stepType >= OpCodes.FIRST_NODESET_OP) && (stepType <= 
OpCodes.LAST_NODESET_OP))
      {
        return opPos+m_opMap[opPos+1];
      }
      else
      {
        throw new RuntimeException("Programmer's assertion in getNextStepPos: 
unknown stepType: "+stepType);
      }
    }
  
    
    /**
     * <meta name="usage" content="advanced"/>
     * Go to the first child of a given operation.
     */
    public static int getFirstChildPos(int opPos)
    {
      return opPos+2;
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Go to the first child of a given operation.
     */
    public int getArgLengthOfStep(int opPos)
    {
      return m_opMap[opPos+MAPINDEX_LENGTH+1]-3;
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Go to the first child of a given operation.
     */
    public static int getFirstChildPosOfStep(int opPos)
    {
      return opPos+3;
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Get the test type of the step, i.e. NODETYPE_XXX value.
     * @param opPosOfStep The position of the FROM_XXX step. 
     */
    public int getStepTestType(int opPosOfStep)
    {
      return m_opMap[opPosOfStep+3]; // skip past op, len, len without 
predicates
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Get the namespace of the step.
     * @param opPosOfStep The position of the FROM_XXX step. 
     */
    public String getStepNS(int opPosOfStep)
    {
      int argLenOfStep = m_opMap[opPosOfStep+1];
      return (argLenOfStep > 4) ? (String)m_tokenQueue[m_opMap[opPosOfStep+4]] 
: null;
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * Get the local name of the step.
     * @param opPosOfStep The position of the FROM_XXX step. 
     */
    public String getStepLocalName(int opPosOfStep)
    {
      int argLenOfStep = m_opMap[opPosOfStep+1];
      return (argLenOfStep == 5) ? (String)m_tokenQueue[m_opMap[opPosOfStep+4]]
                                   : (argLenOfStep == 4) 
                                   ? 
(String)m_tokenQueue[m_opMap[opPosOfStep+3]] 
                                                           : null;
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * This method is for building indexes of match patterns for fast lookup.
     * This allows a caller to get the QName, and quickly 
     * find the likely candidates that may match.  Note that this will 
     * produce QName objects that aren't strictly legal, like "*".
     */
    public Vector getTargetElementQNames()
    {
      Vector targetQNames = new Vector();
  
      int opPos = 2;
  
      while(m_opMap[opPos] == OpCodes.OP_LOCATIONPATHPATTERN)
      {
        int nextOpPos = getNextOpPos(opPos);
        opPos = getFirstChildPos(opPos);
        
        while( m_opMap[opPos] != OpCodes.ENDOP )
        {
          int nextStepPos = getNextOpPos(opPos);
          int nextOp = m_opMap[nextStepPos];
          if((nextOp == OpCodes.OP_PREDICATE) || (nextOp == OpCodes.ENDOP))
          {
            int stepType = m_opMap[opPos];
            opPos += 3;
            switch(stepType)
            {
            case OpCodes.OP_FUNCTION:
              targetQNames.addElement(new QName(PsuedoNames.PSEUDONAME_ANY));
              break;
            case OpCodes.FROM_ROOT:
              targetQNames.addElement(new QName(PsuedoNames.PSEUDONAME_ROOT));
              break;
            case OpCodes.MATCH_ATTRIBUTE:
            case OpCodes.MATCH_ANY_ANCESTOR:
            case OpCodes.MATCH_IMMEDIATE_ANCESTOR:
              int tok = m_opMap[opPos];
              opPos++;
              switch(tok)
              {
              case OpCodes.NODETYPE_COMMENT:
                targetQNames.addElement(new 
QName(PsuedoNames.PSEUDONAME_COMMENT));
                break;
              case OpCodes.NODETYPE_TEXT:
                targetQNames.addElement(new QName(PsuedoNames.PSEUDONAME_TEXT));
                break;
              case OpCodes.NODETYPE_NODE:
                targetQNames.addElement(new QName(PsuedoNames.PSEUDONAME_ANY));
                break;
              case OpCodes.NODETYPE_ROOT:
                targetQNames.addElement(new QName(PsuedoNames.PSEUDONAME_ROOT));
                break;
              case OpCodes.NODETYPE_ANYELEMENT:
                targetQNames.addElement(new QName(PsuedoNames.PSEUDONAME_ANY));
                break;
              case OpCodes.NODETYPE_PI:
                targetQNames.addElement(new QName(PsuedoNames.PSEUDONAME_ANY));
                break;
              case OpCodes.NODENAME:
                int tokenIndex = m_opMap[opPos+1];
                String namespace = (tokenIndex >= 0) ? 
                                   (String)m_tokenQueue[tokenIndex] : null;
                tokenIndex = m_opMap[opPos+1];
                if(tokenIndex >= 0)
                {
                  String targetName = (String)m_tokenQueue[tokenIndex];
                  if(targetName.equals("*"))
                  {
                    targetQNames.addElement(new QName(namespace, 
PsuedoNames.PSEUDONAME_ANY));
                  }
                  else
                  {
                    targetQNames.addElement(new QName(namespace, targetName));
                  }
                }
                else
                {
                  // ?? -sboag
                  targetQNames.addElement(new QName(namespace, 
PsuedoNames.PSEUDONAME_ANY));
                }
                break;
              default:
                targetQNames.addElement(new QName(PsuedoNames.PSEUDONAME_ANY));
                break;
              }
              break;
            }
          }
          opPos = nextStepPos;
        }
        
        opPos = nextOpPos;
      }
      return targetQNames;
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/Process.java
  
  Index: Process.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import java.util.*;
  import org.w3c.dom.*;
  import org.w3c.dom.traversal.NodeIterator;
  import java.lang.reflect.*;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.res.XSLMessages;
  
  /**
   * Provides command-line interface to the XPath processor
   */
  public class Process
  {
    /**
     * Print argument options.
     */
    protected static void printArgOptions(XPATHErrorResources resbundle)
    {
      System.out.println(resbundle.getString("xpath_option"));
      System.out.println(resbundle.getString("optionIN"));
      System.out.println(resbundle.getString("optionSelect"));
      System.out.println(resbundle.getString("optionMatch"));
      System.out.println(resbundle.getString("optionAnyExpr"));
    }
  
    /**
     * Command line interface to the XPath processor.
     * <pre>
     *    xpath
     *    [xml doc]
     * </pre>
     */
    public static void main( String argv[] )
      throws org.xml.sax.SAXException
    {
        XPATHErrorResources resbundle = 
(XPATHErrorResources)(XSLMessages.loadResourceBundle(XPATHErrorResources.ERROR_RESOURCES));
      if(argv.length > 1)
      {
        XPathContext callbacks = null;
        String parserLiaisonClassName = "org.apache.xalan.xpath.DOM2Helper";
        try
        {
          Class parserLiaisonClass = Class.forName(parserLiaisonClassName);
  
          Constructor parserLiaisonCtor = 
parserLiaisonClass.getConstructor(null);
          callbacks
            = (XPathContext)parserLiaisonCtor.newInstance(null);
          // XPathContext callbacks = new org.apache.xalan.xpath.DOM2Helper();
        }
        catch(Exception e)
        {
                  
System.err.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_COULDNOT_CREATE_XMLPROCESSORLIAISON,
 new Object [] {parserLiaisonClassName})); //"Could not create XML Processor 
Liaison: "+parserLiaisonClassName);
          return;
        }
        XPathParser processor = new XPathParser();
        XPath xpath = new XPath();
        String inputURI = null;
        String path = null;
        String match = null;
        for (int i = 0;  i < argv.length;  i ++)
        {
          if("-in".equalsIgnoreCase(argv[i]))
          {
            i++;
            inputURI = argv[i];
          }
          else if("-select".equalsIgnoreCase(argv[i]))
          {
            i++;
            path = argv[i];
          }
          else if("-match".equalsIgnoreCase(argv[i]))
          {
            i++;
            match = argv[i];
          }
        }
  
        if(null == path)
        {
          
System.out.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_DIDNOT_FIND_XPATH_SELECT_EXP,
 null)); //"Error! Did not find xpath select expression (-select).");
          return;
        }
  
        Document doc;
        if(null != inputURI)
        {
          System.out.println("Parsing XML...");
          java.net.URL url = callbacks.getURLFromString(inputURI, null);
          // doc = callbacks.parseXML(url, null, null);
          doc = null; // TBD:
        }
        else
        {
          doc = callbacks.getDOMHelper().getDOMFactory();
        }
        processor.initXPath(xpath, path, null);
  
        XPath matchPat = null;
        if(null != match)
        {
          matchPat = new XPath();
          processor.initMatchPattern(matchPat, match, null);
        }
  
        // TODO: Do something about the prefix resolver.
        XObject result = xpath.execute(callbacks, doc, null);
  
        if(result.getType() == XObject.CLASS_NODESET)
        {
          System.out.println("<results>");
          NodeIterator nl = result.nodeset();
          Node n;
          while(null != (n = nl.nextNode()))
          {
            System.out.print("  <node name='"+n.getNodeName()+"'");
            if(null != matchPat)
            {
              System.out.print(" 
match-value='"+matchPat.getMatchScore(callbacks, n)+"'");
            }
            if(Node.ATTRIBUTE_NODE != n.getNodeType())
            {
              Document owner = (Node.DOCUMENT_NODE == n.getNodeType()) ?
                             (Document)n : n.getOwnerDocument();
              String docURI = 
callbacks.getSourceTreeManager().findURIFromDoc(owner);
              System.out.print(" doc-ref='"+docURI+"'");
            }
            System.out.println("/>");
          }
          System.out.println("</results>");
        }
        else
        {
          System.out.println("XPath Result: \n"+result.str());
        }
      }
      else if(argv.length == 1)
      {
        XPathDumper.diagnoseXPathString(argv[0]);
      }
      else
      {
        printArgOptions(resbundle);
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/PsuedoNames.java
  
  Index: PsuedoNames.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  public class PsuedoNames
  {
    /**
     * <meta name="usage" content="advanced"/>
     * used mainly for keys in the pattern lookup table,
     * for those nodes that don't have unique lookup values.
     */
    public static final String PSEUDONAME_ANY = "*";
    
    /**
     * <meta name="usage" content="advanced"/>
     * used mainly for keys in the pattern lookup table,
     * for those nodes that don't have unique lookup values.
     */
    public static final String PSEUDONAME_ROOT = "/";
    
    /**
     * <meta name="usage" content="advanced"/>
     * used mainly for keys in the pattern lookup table,
     * for those nodes that don't have unique lookup values.
     */
    public static final String PSEUDONAME_TEXT = "#text";
    
    /**
     * <meta name="usage" content="advanced"/>
     * used mainly for keys in the pattern lookup table,
     * for those nodes that don't have unique lookup values.
     */
    public static final String PSEUDONAME_COMMENT = "#comment";
    
    /**
     * <meta name="usage" content="advanced"/>
     * used mainly for keys in the pattern lookup table,
     * for those nodes that don't have unique lookup values.
     */
    public static final String PSEUDONAME_PI = "#pi";
    
    /**
     * <meta name="usage" content="advanced"/>
     * used mainly for keys in the pattern lookup table,
     * for those nodes that don't have unique lookup values.
     */
    public static final String PSEUDONAME_OTHER = "*";
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/SimpleNodeLocator.java
  
  Index: SimpleNodeLocator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import java.util.*;
  import java.io.*;
  import org.w3c.dom.*;
  import org.w3c.dom.traversal.NodeIterator;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  /**
   * <meta name="usage" content="advanced"/>
   * SimpleNodeLocator implements a search of one or more DOM trees.
   * By using the connect function as an extension, the user may 
   * specify a directory and a filter specification for XML files 
   * that will be searched.
   * This is a singleton class.
   */
  public class SimpleNodeLocator implements XLocator, Serializable
  {  
    /**
     * Create a SimpleNodeLocator object.
     */
    public SimpleNodeLocator()
    {
    }
    
    /**
     * The singleton instance of this class.
     */
    private static SimpleNodeLocator m_locater = null;
  
    /**
     * The the default locator.
     */
    public static XLocator getDefaultLocator()
    {
      m_locater = (null == m_locater) ? new SimpleNodeLocator() : m_locater;
      return m_locater;
    }
  
    /**
     * Execute the proprietary connect() function, which returns an 
     * instance of XLocator.  When the XPath object sees a return type 
     * of XLocator, it will call the locationPath function that passes 
     * in the connectArgs.  The opPos and args params are not used 
     * by this function.  This really is just a factory function 
     * for the XLocator instance, but this fact is hidden from the 
     * user.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param args The function args.
     * @returns A node set of Document nodes.
     */
    public static XLocator query(String path, String fileSpec) 
    {    
      m_locater = (null == m_locater) ? new SimpleNodeLocator() : m_locater;
      return m_locater;
    }
    
    /**
     * (Same as query for the moment).
     * @param opPos The current position in the xpath.m_opMap array.
     * @param args The function args.
     * @returns A node set of Document nodes.
     */
    public static XLocator connect(String path, String fileSpec) 
    {    
      m_locater = (null == m_locater) ? new SimpleNodeLocator() : m_locater;
      return m_locater;
    }
    
    /**
     * Execute a connection (if it was not executed by the static 
     * connect method) and process the following LocationPath, 
     * if it is present.  Normally, the connection functionality 
     * should be executed by this function and not the static connect 
     * function, which is really a factory method for the XLocator 
     * instance.  The arguments to the static connect function
     * are re-passed to this function.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param connectArgs The same arguments that were passed to the 
     * static connect function.
     * @returns the result of the query in an XNodeSet object.
     */
    public XNodeSet connectToNodes(XPath xpath, XPathContext xctxt, Node 
context, 
                                   int opPos, Vector connectArgs) 
      throws org.xml.sax.SAXException
    {    
      String fileSpec = ((XObject)connectArgs.elementAt(0)).str();
      FileFilter filter = null;
      String filterSpec = null;
      if(connectArgs.size() > 1)
      {
        filterSpec = ((XObject)connectArgs.elementAt(1)).str();
        filter = new FileFilter(filterSpec);
      }
      
      File dir = new File(fileSpec);
      
      XNodeSet results = new XNodeSet();
      NodeSet mnl = results.mutableNodeset();
      
      if(null != dir)
      {
        String filenames[] = (filter != null) ? dir.list(filter) : dir.list();
        if(null != filenames)
        {
          int nFiles = filenames.length;
          for(int i = 0; i < nFiles; i++)
          {
            try
            {
              String urlString = 
"file:"+dir.getAbsolutePath()+File.separatorChar+filenames[i];
              // java.net.URL url = xctxt.getURLFromString(filenames[i], null);
              java.net.URL url = new java.net.URL(urlString);
              // Document doc = xctxt.parseXML(url, null, null);
              Document doc = null; // TBD:
              if(null != doc)
              {
                int op = xpath.m_opMap[opPos];
                if(OpCodes.OP_LOCATIONPATH == (op & 
OpCodes.LOCATIONPATHEX_MASK))
                {
                  XNodeSet xnl = xpath.locationPath(xctxt, doc, opPos);
                  if(null != xnl)
                  {
                    mnl.addNodes(xnl.nodeset());
                    xctxt.getSourceTreeManager().associateXLocatorToNode(doc, 
url, this);
                  }
                }
                else
                {
                  mnl.addNode(doc);
                  xctxt.getSourceTreeManager().associateXLocatorToNode(doc, 
url, this);
                }
              }
            }
            catch(Exception e)
            {
              System.out.println("Couldn't parse file: "+e.getMessage());
            }
          }
        }
        else
        {
          System.out.println("Couldn't get a file list from filespec");
        }
      }
      else
      {
        System.out.println("Filespec was bad in connect");
      }
      
      return results;
    }
    
    /**
     * Computes the union of its operands which must be node-sets.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns the union of node-set operands, or an empty set if 
     * callback methods are used.
     */
    public XNodeSet union(XPath xpath, XPathContext xctxt, 
                          Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      
      return new XNodeSet(new UnionPathIterator(xpath, xctxt, context, opPos, 
this));
    }
  
    /**
     * Execute a location path.  Normally, this method simply 
     * moves past the OP_LOCATIONPATH and it's length member, 
     * and calls the Step function, which will recursivly process 
     * the rest of the LocationPath, and then wraps the NodeList result
     * in an XNodeSet object.
     * @param xpath The xpath that is executing.
     * @param xctxt The execution context.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param callback Interface that implements the processLocatedNode method.
     * @param callbackInfo Object that will be passed to the processLocatedNode 
method.
     * @returns the result of the query in an XNodeSet object.
     */
    public XNodeSet locationPath(XPath xpath, XPathContext xctxt, 
                                 Node context, int opPos) 
      throws org.xml.sax.SAXException
    {    
      return new XNodeSet(new LocPathIterator(xpath, xctxt, context, opPos, 
this));
    }
      
    /**
     * Execute a single predicate for a single node.
     * @returns True if the node should not be filtered.
     */
    protected boolean predicate(XPath xpath, XPathContext xctxt, Node context, 
int opPos) 
      throws org.xml.sax.SAXException
    {
      boolean shouldNotFilter = true;
  
      int nextStepType = xpath.m_opMap[opPos];
      if(OpCodes.OP_PREDICATE == nextStepType)
      {
        XObject pred = xpath.predicate(xctxt, context, opPos);
        if(XObject.CLASS_NUMBER == pred.getType())
        {
          throw new FoundIndex(); // Ugly, but... see comment in the Step 
function.
        }
        else if(!pred.bool())
        {
          shouldNotFilter = false;
        }
      }
      return shouldNotFilter;
    }
    
    /**
     * Execute a a location path pattern.  This will return a score
     * of MATCH_SCORE_NONE, MATCH_SCORE_NODETEST, 
     * MATCH_SCORE_OTHER, MATCH_SCORE_QNAME.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @returns score, one of MATCH_SCORE_NODETEST, 
     * MATCH_SCORE_NONE, MATCH_SCORE_OTHER, MATCH_SCORE_QNAME.
     */
    public double locationPathPattern(XPath xpath, XPathContext xctxt, Node 
context, int opPos) 
      throws org.xml.sax.SAXException
    {    
      opPos = xpath.getFirstChildPos(opPos);
      double[] scoreHolder = 
      {
        XPath.MATCH_SCORE_NONE};
      stepPattern(xpath, xctxt, context, opPos, scoreHolder, 0);
      return scoreHolder[0];
    }
  
    /**
     * Execute a step in a location path.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @returns the last matched context node.
     */
    protected Node stepPattern(XPath xpath, XPathContext xctxt, 
                               Node context, int opPos, double scoreHolder[],
                               int stepCount) 
      throws org.xml.sax.SAXException
    {    
      int startOpPos = opPos;
      int stepType = xpath.m_opMap[opPos];
      
      int endStep = xpath.getNextOpPos(opPos);
      int nextStepType = xpath.m_opMap[endStep];
      double score;
      
      if(OpCodes.ENDOP != nextStepType)
      {
        // Continue step via recursion...
        context = stepPattern(xpath, xctxt, context, endStep, scoreHolder, 
stepCount+1);
        if(null == context)
          scoreHolder[0] = XPath.MATCH_SCORE_NONE;
        if(scoreHolder[0] == XPath.MATCH_SCORE_NONE)
          return null;
        
        scoreHolder[0] = XPath.MATCH_SCORE_OTHER;
        context = xctxt.getDOMHelper().getParentOfNode(context);
        if(null == context)
          return null;
      }
      // System.out.println("stepCount: "+stepCount);
      boolean isSimple = ((OpCodes.ENDOP == nextStepType) && (stepCount == 0));
      
      int argLen;
  
      switch(stepType)
      {
      case OpCodes.OP_FUNCTION:
        {
          argLen = xpath.m_opMap[opPos+XPath.MAPINDEX_LENGTH];
          XObject obj = xpath.execute(xctxt, context, opPos);
          NodeIterator nl = obj.nodeset();
          score = XPath.MATCH_SCORE_NONE;
          Node n;
          while(null != (n = nl.nextNode()))
          {
            score = (n.equals(context)) ? XPath.MATCH_SCORE_OTHER : 
XPath.MATCH_SCORE_NONE;
            if(score == XPath.MATCH_SCORE_OTHER)
            {
              context = n;
              break;
            }
          }
        }
        break;
      case OpCodes.FROM_ROOT:
        {
          argLen = xpath.getArgLengthOfStep(opPos);
          opPos = xpath.getFirstChildPosOfStep(opPos);
          Document docContext = (Node.DOCUMENT_NODE == context.getNodeType()) 
                                ? (Document)context : 
context.getOwnerDocument();
          score = (docContext.equals( context )) ? XPath.MATCH_SCORE_OTHER : 
XPath.MATCH_SCORE_NONE;
          if(score == XPath.MATCH_SCORE_OTHER)
          {
            context = docContext;
          }
        }
        break;
      case OpCodes.MATCH_ATTRIBUTE:
        {
          argLen = xpath.getArgLengthOfStep(opPos);
          opPos = xpath.getFirstChildPosOfStep(opPos);
          score = nodeTest(xpath, xctxt, context, opPos, argLen, 
OpCodes.FROM_ATTRIBUTES);
          break;
        }
      case OpCodes.MATCH_ANY_ANCESTOR:
        argLen = xpath.getArgLengthOfStep(opPos);
        if(context.getNodeType() != Node.ATTRIBUTE_NODE)
        {
          opPos = xpath.getFirstChildPosOfStep(opPos);
          score = XPath.MATCH_SCORE_NONE;
          while(null != context)
          {
            score = nodeTest(xpath, xctxt, context, opPos, argLen, stepType);
            if(XPath.MATCH_SCORE_NONE != score)
              break;
            // context = xctxt.getParentOfNode(context);
            context = context.getParentNode();
          }
        }
        else
        {
          score = XPath.MATCH_SCORE_NONE;
        }
        break;
      case OpCodes.MATCH_IMMEDIATE_ANCESTOR:
        argLen = xpath.getArgLengthOfStep(opPos);
        if(context.getNodeType() != Node.ATTRIBUTE_NODE)
        {
          opPos = xpath.getFirstChildPosOfStep(opPos);
          score = nodeTest(xpath, xctxt, context, opPos, argLen, stepType);
        }
        else
        {
          score = XPath.MATCH_SCORE_NONE;
        }
        break;
      default:
        argLen = xpath.getArgLengthOfStep(opPos);
        opPos = xpath.getFirstChildPosOfStep(opPos);
        score = XPath.MATCH_SCORE_NONE;
        xpath.error(xctxt, context, 
XPATHErrorResources.ER_UNKNOWN_MATCH_OPERATION, null); //"unknown match 
operation!");
        break;
      }
      opPos += argLen;
      nextStepType = xpath.m_opMap[opPos];
      
      if(((score != XPath.MATCH_SCORE_NONE)) && (OpCodes.OP_PREDICATE == 
nextStepType))
      {
        score = XPath.MATCH_SCORE_OTHER;
        // Execute the xpath.predicates, but if we have an index, then we have 
        // to start over and do a search from the parent.  It would be nice 
        // if I could sense this condition earlier...
        try
        {
          // BUG: m_throwFoundIndex is not threadsafe
          
          int startPredicates = opPos;
          opPos = startPredicates;
          nextStepType = xpath.m_opMap[opPos];
          xctxt.setThrowFoundIndex(true);
          for(int i = 0; OpCodes.OP_PREDICATE == nextStepType; i++)
          {
            XObject pred = xpath.predicate(xctxt, context, opPos);
            if(XObject.CLASS_NUMBER == pred.getType())
            {
              if((i == 0) && isSimple)
              {
                NodeSet cnl = xctxt.getContextNodeList();
                // System.out.println("cnl.getCurrentPos(): 
"+cnl.getCurrentPos());
                if(cnl.getCurrentPos() != pred.num())
                {
                  score = XPath.MATCH_SCORE_NONE;
                  break; // from while(OpCodes.OP_PREDICATE == nextStepType)
                }
              }
              else
              {
                throw new FoundIndex();
              }
            }
            else if(!pred.bool())
            {
              score = XPath.MATCH_SCORE_NONE;
              break; // from while(OpCodes.OP_PREDICATE == nextStepType)
            }
            opPos = xpath.getNextOpPos(opPos);
            nextStepType = xpath.m_opMap[opPos];
          }
          xctxt.setThrowFoundIndex(false);
        }
        catch(FoundIndex fi)
        {
          // We have an index somewhere in our pattern.  So, we have 
          // to do a full search for our step, using the parent as 
          // context, then see if the current context is found in the 
          // node set.  Seems crazy, but, so far, it seems like the 
          // easiest way.
          xctxt.setThrowFoundIndex(false);
          Node parentContext = xctxt.getDOMHelper().getParentOfNode(context);
          LocPathIterator lpi 
            = new LocPathIterator(xpath, xctxt, parentContext, startOpPos, 
this, true);
          
          score = XPath.MATCH_SCORE_NONE;
          Node child;
          while(null != (child=lpi.nextNode()))
          {
            if(child.equals( context ))
            {
              score = XPath.MATCH_SCORE_OTHER;
              break;
            }
          }
        }
      }
      // If we haven't found a score yet, or the test was 
      // negative, assign the score.
      if((scoreHolder[0] == XPath.MATCH_SCORE_NONE) || 
         (score == XPath.MATCH_SCORE_NONE))
        scoreHolder[0] = score;
      
      return (score == XPath.MATCH_SCORE_NONE) ? null : context;
    }
  
    
    /**
     * Test a node to see if it matches the given node test.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param len The length of the argument.
     * @param len The type of the step.
     * @returns score in an XNumber, one of MATCH_SCORE_NODETEST, 
     * MATCH_SCORE_NONE, MATCH_SCORE_OTHER, MATCH_SCORE_QNAME.
     */
    public double nodeTest(XPath xpath, XPathContext xctxt, Node context, 
                           int opPos, int argLen, int stepType)
      throws org.xml.sax.SAXException
    {
      double score;
      int testType = xpath.m_opMap[opPos];
      int nodeType = context.getNodeType();
      opPos++;
      switch(testType)
      {
      case OpCodes.NODETYPE_COMMENT:
        score = (Node.COMMENT_NODE == nodeType)
                ? XPath.MATCH_SCORE_NODETEST : XPath.MATCH_SCORE_NONE;
        break;
      case OpCodes.NODETYPE_TEXT:
        score = (((Node.CDATA_SECTION_NODE == nodeType) 
                  || (Node.TEXT_NODE == nodeType)) &&
                 (!xctxt.getDOMHelper().shouldStripSourceNode(context)))
                ? XPath.MATCH_SCORE_NODETEST : XPath.MATCH_SCORE_NONE;
        break;
      case OpCodes.NODETYPE_PI:
        if( (Node.PROCESSING_INSTRUCTION_NODE == nodeType) )
        {
          if(argLen == 2)
          {
            XString name = (XString)xpath.m_tokenQueue[xpath.m_opMap[opPos]];
            score = 
((ProcessingInstruction)context).getNodeName().equals(name.str())
                    ? XPath.MATCH_SCORE_QNAME : XPath.MATCH_SCORE_NONE;
          }
          else if(argLen == 1)
          {
            score = XPath.MATCH_SCORE_NODETEST;
          }
          else
          {
            score = XPath.MATCH_SCORE_NONE;
            xpath.error(xctxt, context, 
XPATHErrorResources.ER_INCORRECT_ARG_LENGTH, null); //"Arg length of 
processing-instruction() node test is incorrect!");
          }
        }
        else
        {
          score = XPath.MATCH_SCORE_NONE;
        }
        break;
      case OpCodes.NODETYPE_NODE:
        if((Node.CDATA_SECTION_NODE == nodeType) 
           || (Node.TEXT_NODE == nodeType))
        {
          score = (!xctxt.getDOMHelper().shouldStripSourceNode(context))
                  ? XPath.MATCH_SCORE_NODETEST : XPath.MATCH_SCORE_NONE;
        }
        else
        {
          score = XPath.MATCH_SCORE_NODETEST;
        }
        break;
      case OpCodes.NODETYPE_ROOT:
        score = ( (Node.DOCUMENT_FRAGMENT_NODE == nodeType) 
                  || (Node.DOCUMENT_NODE == nodeType))
                ? XPath.MATCH_SCORE_OTHER : XPath.MATCH_SCORE_NONE;
        break;
        
      case OpCodes.NODENAME:
        {
          if(!((Node.ATTRIBUTE_NODE == nodeType) || (Node.ELEMENT_NODE == 
nodeType)))
            return XPath.MATCH_SCORE_NONE;
                                          
          boolean test;
          int queueIndex = xpath.m_opMap[opPos];
          String targetNS = (queueIndex >= 0) ? 
(String)xpath.m_tokenQueue[xpath.m_opMap[opPos]]
                                                : null;
          opPos++;
          
          // From the draft: "Two expanded names are equal if they 
          // have the same local part, and either both have no URI or 
          // both have the same URI."
          // "A node test * is true for any node of the principal node type. 
          // For example, child::* will select all element children of the 
          // context node, and attribute::* will select all attributes of 
          // the context node."
          // "A node test can have the form NCName:*. In this case, the prefix 
          // is expanded in the same way as with a QName using the context 
          // namespace declarations. The node test will be true for any node 
          // of the principal type whose expanded name has the URI to which 
          // the prefix expands, regardless of the local part of the name."
          boolean isTotallyWild = (null == targetNS) 
                                  && (xpath.m_opMap[opPos] == 
OpCodes.ELEMWILDCARD);
          boolean didMatchNS = false;
          if(!isTotallyWild)
          {
            String contextNS = xctxt.getDOMHelper().getNamespaceOfNode(context);
            if((null != targetNS) && (null != contextNS))
            {
              test = contextNS.equals(targetNS);
              didMatchNS = true;
            }
            else
            {
              test = (OpCodes.ELEMWILDCARD == queueIndex) || 
                     (((null == contextNS) || (contextNS.length() == 0)) &&
                      ((null == targetNS) || (targetNS.length() == 0)));
            }
          }
          else 
            test = true;
          
          queueIndex = xpath.m_opMap[opPos];
          String targetLocalName = (queueIndex >= 0) ? 
(String)xpath.m_tokenQueue[xpath.m_opMap[opPos]]
                                                       : null;
          
          if(!test)
          {
            score = XPath.MATCH_SCORE_NONE;
          }
          else
          {
            switch(nodeType)
            {
            case Node.ATTRIBUTE_NODE:
              if((stepType == OpCodes.FROM_ATTRIBUTES) || (stepType == 
OpCodes.FROM_NAMESPACE))
              {            
                boolean isNamespace = 
xctxt.getDOMHelper().isNamespaceNode(context);
                if(OpCodes.ELEMWILDCARD == queueIndex)
                {
                  if(stepType == OpCodes.FROM_ATTRIBUTES)
                  {
                    score = !isNamespace ? XPath.MATCH_SCORE_NODETEST : 
XPath.MATCH_SCORE_NONE;
                  }
                  else
                  {
                    score = isNamespace ? XPath.MATCH_SCORE_NODETEST : 
XPath.MATCH_SCORE_NONE;
                  }
                }
                else
                {
                  if(stepType == OpCodes.FROM_ATTRIBUTES)
                  {
                    if(!isNamespace)
                    {
                      String localAttrName 
                        = xctxt.getDOMHelper().getLocalNameOfNode(context);
                      score = localAttrName.equals(targetLocalName)
                              ? XPath.MATCH_SCORE_QNAME : 
XPath.MATCH_SCORE_NONE;
                    }
                    else
                    {
                      score = XPath.MATCH_SCORE_NONE;
                    }
                  }
                  else
                  {
                    if(isNamespace)
                    {
                      String namespace = ((Attr)context).getValue();
                      
                      score = namespace.equals(targetLocalName)
                              ? XPath.MATCH_SCORE_QNAME : 
XPath.MATCH_SCORE_NONE;
                    }
                    else
                    {
                      score = XPath.MATCH_SCORE_NONE;
                    }
                  }
                }
              }
              else
              {
                score  = XPath.MATCH_SCORE_NONE;
              }
              break;
  
            case Node.ELEMENT_NODE:
              if(stepType != OpCodes.FROM_ATTRIBUTES)
              {
                if(OpCodes.ELEMWILDCARD == queueIndex)
                {
                  score = (didMatchNS ? 
                           XPath.MATCH_SCORE_NSWILD : 
XPath.MATCH_SCORE_NODETEST);
                }
                else
                {
                  
                  score = 
(xctxt.getDOMHelper().getLocalNameOfNode(context).equals(targetLocalName))
                          ? XPath.MATCH_SCORE_QNAME : XPath.MATCH_SCORE_NONE;
                }
              }
              else
              {
                score  = XPath.MATCH_SCORE_NONE;
              }
              break;
              
            default:
              // Trying to match on anything else causes nasty bugs.
              score  = XPath.MATCH_SCORE_NONE;
              break;
  
            } // end switch(nodeType)
          } // end if(test)
        } // end case OpCodes.NODENAME
        break;
      default:
        score  = XPath.MATCH_SCORE_NONE;
      } // end switch(testType)
      
      return score;    
    }
    
    /**
     * Create an XPathFactory for this XLocator.
     */
    public static XPathFactory factory() 
    {
      return new SimpleNodeLocatorFactory();
    }
  
    /**
     * Very crude file filter.
     */
    class FileFilter implements FilenameFilter
    {
      private String m_filterSpec;
      
      public FileFilter(String filter)
      {
        m_filterSpec = filter;
      }
      
      /**
       * Tests if a specified file should be included in a file list.
       *
       * @param   dir    the directory in which the file was found.
       * @param   name   the name of the file.
       * @return  <code>true</code> if the name should be included in the file
       *          list; <code>false</code> otherwise.
       * @since   JDK1.0
       */
      public boolean accept(File dir, String name)
      {
        return name.endsWith(m_filterSpec);
      }
    }
    
  }
  
  /**
   * Override the createXLocatorHandler method.
   */
  class DOMXPath extends XPath
  {
    public DOMXPath()
    {
      super();
    }
    
    /**
     * getXLocatorHandler.
     */
    public XLocator createXLocatorHandler(XPath xpath)
    {
      return new SimpleNodeLocator();
    }
  }
  
  /**
   * Implement an XPath factory.
   */
  class SimpleNodeLocatorFactory implements XPathFactory
  {
    public XPath create()
    {
      return new DOMXPath();
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/SourceTree.java
  
  Index: SourceTree.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.Node;
  import java.net.URL;
  
  /**
   * <meta name="usage" content="internal"/>
   * This object represents a Source Tree, and any associated 
   * information.
   */
  public class SourceTree
  {
    public SourceTree(Node root, URL url, XLocator locator)
    {
      m_root = root;
      m_locator = locator;
      m_url = url;
    }
    
    public URL m_url;
    public Node m_root;
    public XLocator m_locator;
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/SourceTreeManager.java
  
  Index: SourceTreeManager.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import java.net.URL;
  import java.net.MalformedURLException;
  import java.io.File;
  import java.io.IOException;
  import java.util.StringTokenizer;
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import trax.URIResolver;
  import trax.TransformException;
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  import org.xml.sax.SAXParseException;
  import org.xml.sax.helpers.XMLReaderFactory;
  import org.xml.sax.XMLReader;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.stree.SourceTreeHandler;
  
  /**
   * This class bottlenecks all management of source trees.  The methods
   * in this class should allow easy garbage collection of source 
   * trees, and should centralize parsing for those source trees.
   * The SourceTreeManager is also the default 
   */
  public class SourceTreeManager implements URIResolver
  {
    private int m_size = 0;
    private SourceTree m_sourceTree[] = new SourceTree[20];
    
    /**
     * <meta name="usage" content="advanced"/>
     * Associate an XLocator provider to a node.  This makes
     * the association based on the root of the tree that the 
     * node is parented by.
     */
    public void associateXLocatorToNode(Node node, URL url, XLocator xlocator)
    {
      Node root = node.getOwnerDocument();
      if(null == root)
        root = node;
      XLocator found = null;
      int n = m_size;
      for(int i = 0; i < n; i++)
      {
        SourceTree ass = m_sourceTree[i];
        if(root == ass.m_root)
        {
          found = ass.m_locator;
          break;
        }
      }
      if(null == found)
      {
        m_sourceTree[m_size] = new SourceTree(root, url, xlocator);
        m_size++;
      }
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Get an XLocator provider keyed by node.  This get's
     * the association based on the root of the tree that the 
     * node is parented by.
     */
    public XLocator getXLocatorFromNode(Node node)
    {
      Node root = node.getOwnerDocument();
      if(null == root)
        root = node;
      XLocator xlocator = null;
      int n = m_size;
      for(int i = 0; i < n; i++)
      {
        SourceTree ass = m_sourceTree[i];
        if(root == ass.m_root)
        {
          xlocator = ass.m_locator;
          break;
        }
      }
      return xlocator;
    }
    
    /**
     * Given a document, find the URL associated with that document.
     * @param owner Document that was previously processed by this liaison.
     */
    public String findURIFromDoc(Document owner)
    {
      Node root = owner.getOwnerDocument();
      if(null == root)
        root = owner;
      URL url = null;
      int n = m_size;
      for(int i = 0; i < n; i++)
      {
        SourceTree ass = m_sourceTree[i];
        if(root == ass.m_root)
        {
          url = ass.m_url;
          break;
        }
      }
      return url.toExternalForm();
    }
    
    /**
     * Given a document, find the URL associated with that document.
     * @param owner Document that was previously processed by this liaison.
     */
    public Node findNodeFromURL(URL url)
    {
      Node node = null;
      int n = m_size;
      for(int i = 0; i < n; i++)
      {
        SourceTree ass = m_sourceTree[i];
        if(url == ass.m_url)
        {
          node = ass.m_root;
          break;
        }
      }
      return node;
    }
    
    /**
     * Given a document, find the URL associated with that document.
     * @param owner Document that was previously processed by this liaison.
     */
    public Node findNodeFromURL(String url)
    {
      Node node = null;
      int n = m_size;
      for(int i = 0; i < n; i++)
      {
        SourceTree ass = m_sourceTree[i];
        if(url == ass.m_url.toExternalForm())
        {
          node = ass.m_root;
          break;
        }
      }
      return node;
    }
  
    /**
     * Return a string suitible for telling the user what parser is being used.
     */
    public String getParserDescription()
    {
      return "(No parser - generic DOM)";
    }
    
    /**
     * This will be called by the processor when it encounters 
     * an xsl:include, xsl:import, or document() function.
     * 
     * @param base The base URI that should be used.
     * @param uri Value from an xsl:import or xsl:include's href attribute, 
     * or a URI specified in the document() function.
     * @returns a InputSource that can be used to process the resource.
     */
    public InputSource resolveURI (String base, String urlString)
      throws TransformException, IOException
    {
      String origURLString = urlString;
      String origBase = base;
      
      // System.out.println("getURLFromString - urlString: "+urlString+", base: 
"+base);
      Object doc;
      URL url = null;
      int fileStartType = 0;
      try
      {
        
        if(null != base)
        {
          if(base.toLowerCase().startsWith("file:/"))
          {
            fileStartType = 1;
          }
          else if(base.toLowerCase().startsWith("file:"))
          {
            fileStartType = 2;
          }
        }
        
        boolean isAbsoluteURL;
        
        // From http://www.ics.uci.edu/pub/ietf/uri/rfc1630.txt
        // A partial form can be distinguished from an absolute form in that the
        // latter must have a colon and that colon must occur before any slash
        // characters. Systems not requiring partial forms should not use any
        // unencoded slashes in their naming schemes.  If they do, absolute URIs
        // will still work, but confusion may result.
        int indexOfColon = urlString.indexOf(':');
        int indexOfSlash = urlString.indexOf('/');
        if((indexOfColon != -1) && (indexOfSlash != -1) && (indexOfColon < 
indexOfSlash))
        {
          // The url (or filename, for that matter) is absolute.
          isAbsoluteURL = true;
        }
        else
        {
          isAbsoluteURL = false;
        }
        
        if(isAbsoluteURL || (null == base) || (base.length() == 0))
        {
          try 
          {
            url = new URL(urlString);
          }
          catch (MalformedURLException e) {}
        }
        // The Java URL handling doesn't seem to handle relative file names.
        else if(!((urlString.charAt(0) == '.') || (fileStartType > 0)))
        {
          try 
          {
            URL baseUrl = new URL(base);
            url = new URL(baseUrl, urlString);
          }
          catch (MalformedURLException e) 
          {
          }
        }
        
        if(null == url)
        {
          // Then we're going to try and make a file URL below, so strip 
          // off the protocol header.
          if(urlString.toLowerCase().startsWith("file:/"))
          {
            urlString = urlString.substring(6);
          }
          else if(urlString.toLowerCase().startsWith("file:"))
          {
            urlString = urlString.substring(5);
          }
        }
        
        if((null == url) && ((null == base) || (fileStartType > 0)))
        {
          if(1 == fileStartType)
          {
            if(null != base)
              base = base.substring(6);
            fileStartType = 1;
          }
          else if(2 == fileStartType)
          {
            if(null != base)
              base = base.substring(5);
            fileStartType = 2;
          }
          
          File f = new File(urlString);
          
          if(!f.isAbsolute() && (null != base))
          {
            // String dir = f.isDirectory() ? f.getAbsolutePath() : 
f.getParent();
            // System.out.println("prebuiltUrlString (1): "+base);
            StringTokenizer tokenizer = new StringTokenizer(base, "\\/");
            String fixedBase = null;
            while(tokenizer.hasMoreTokens())
            {
              String token = tokenizer.nextToken();
              if (null == fixedBase) 
              {
                // Thanks to Rick Maddy for the bug fix for UNIX here.
                if (base.charAt(0) == '\\' || base.charAt(0) == '/') 
                {
                  fixedBase = File.separator + token;
                }
                else 
                {
                  fixedBase = token;
                }
              }
              else 
              {
                fixedBase+= File.separator + token;
              }
            }
            // System.out.println("rebuiltUrlString (1): "+fixedBase);
            f = new File(fixedBase);
            String dir = f.isDirectory() ? f.getAbsolutePath() : f.getParent();
            // System.out.println("dir: "+dir);
            // System.out.println("urlString: "+urlString);
            // f = new File(dir, urlString);
            // System.out.println("f (1): "+f.toString());
            // urlString = f.getAbsolutePath();
            f = new File(urlString); 
            boolean isAbsolute =  f.isAbsolute() 
                                  || (urlString.charAt( 0 ) == '\\')
                                  || (urlString.charAt( 0 ) == '/');
            if(!isAbsolute)
            {
              // Getting more and more ugly...
              if(dir.charAt( dir.length()-1 ) != File.separator.charAt(0) && 
                 urlString.charAt( 0 ) != File.separator.charAt(0))
              {
                urlString = dir + File.separator + urlString;
              }
              else
              {
                urlString = dir + urlString;
              }
  
              // System.out.println("prebuiltUrlString (2): "+urlString);
              tokenizer = new StringTokenizer(urlString, "\\/");
              String rebuiltUrlString = null;
              while(tokenizer.hasMoreTokens())
              {
                String token = tokenizer.nextToken();
                if (null == rebuiltUrlString) 
                {
                  // Thanks to Rick Maddy for the bug fix for UNIX here.
                  if (urlString.charAt(0) == '\\' || urlString.charAt(0) == 
'/') 
                  {
                    rebuiltUrlString = File.separator + token;
                  }
                  else 
                  {
                    rebuiltUrlString = token;
                  }
                }
                else 
                {
                  rebuiltUrlString+= File.separator + token;
                }
              }
              // System.out.println("rebuiltUrlString (2): "+rebuiltUrlString);
              if(null != rebuiltUrlString)
                urlString = rebuiltUrlString;
            }
            // System.out.println("fileStartType: "+fileStartType);
            if(1 == fileStartType)
            {
              if (urlString.charAt(0) == '/') 
              {
                urlString = "file://"+urlString;
              }
              else
              {
                urlString = "file:/"+urlString;
              }
            }
            else if(2 == fileStartType)
            {
              urlString = "file:"+urlString;
            }
            try 
            {
              // System.out.println("Final before try: "+urlString);
              url = new URL(urlString);
            }
            catch (MalformedURLException e) 
            {
              // System.out.println("Error trying to make URL from "+urlString);
            }
          }
        }
        if(null == url)
        {
          // The sun java VM doesn't do this correctly, but I'll 
          // try it here as a second-to-last resort.
          if((null != origBase) && (origBase.length() > 0))
          {
            try 
            {
              URL baseURL = new URL(origBase);
              // System.out.println("Trying to make URL from "+origBase+" and 
"+origURLString);
              url = new URL(baseURL, origURLString);
              // System.out.println("Success! New URL is: "+url.toString());
            }
            catch (MalformedURLException e) 
            {
              // System.out.println("Error trying to make URL from "+origBase+" 
and "+origURLString);
            }
          }
          
          if(null == url)
          {
            try 
            {
              String lastPart;
              if(null != origBase)
              {
                File baseFile = new File(origBase);
                if(baseFile.isDirectory())
                {
                  lastPart = new File(baseFile, urlString).getAbsolutePath ();
                }
                else
                {
                  String parentDir = baseFile.getParent();
                  lastPart = new File(parentDir, urlString).getAbsolutePath ();
                }
              }
              else
              {
                lastPart = new File (urlString).getAbsolutePath ();
              }
              // Hack
              // if((lastPart.charAt(0) == '/') && (lastPart.charAt(2) == ':'))
              //   lastPart = lastPart.substring(1, lastPart.length() - 1);
              
              String fullpath;
              if (lastPart.charAt(0) == '\\' || lastPart.charAt(0) == '/') 
              {
                fullpath = "file://" + lastPart;
              }
              else
              {
                fullpath = "file:" + lastPart;
              }
              url = new URL(fullpath);
            }
            catch (MalformedURLException e2)
            {
              throw new TransformException( 
XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CANNOT_CREATE_URL, new 
Object[]{urlString}),e2); //"Cannot create url for: " + urlString, e2 );
            }
          }
        }
      }
      catch(SecurityException se)
      {
        try
        {
          url = new URL("http://xml.apache.org/xslt/"+java.lang.Math.random()); 
// dummy
        }
        catch (MalformedURLException e2)
        {
          // I give up
        }
      }
  
      InputSource source = new InputSource();
      
      source.setSystemId(url.toExternalForm());
      return source;
    }
  
    /**
     * This will be called by the processor when it encounters 
     * an xsl:include, xsl:import, or document() function, if it needs 
     * a DOM tree.
     * 
     * @param base The base URI that should be used.
     * @param uri Value from an xsl:import or xsl:include's href attribute, 
     * or a URI specified in the document() function.
     * @returns a DOM node that represents the resolution of the URI to a tree.
     */
    public Node resolveURIToDOMTree (String base, String uri)
      throws TransformException, IOException
    {
      InputSource source = resolveURI (base, uri);
      try
      {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SourceTreeHandler handler = new SourceTreeHandler();
        reader.setContentHandler(handler);
        reader.parse(source);
        return handler.getRoot();
      }
      catch(SAXException se)
      {
        throw new TransformException(se);
      }
    }
  
  
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/UnionPathIterator.java
  
  Index: UnionPathIterator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  // DOM Imports
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.Node;
  import org.w3c.dom.DOMException;
  
  // Xalan Imports
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XPathContext;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This class extends NodeSet, which implements NodeIterator, 
   * and fetches nodes one at a time in document order based on a XPath
   * <a href="http://www.w3.org/TR/xpath#NT-UnionExpr";>UnionExpr</a>.
   * As each node is iterated via nextNode(), the node is also stored 
   * in the NodeVector, so that previousNode() can easily be done.
   */
  public class UnionPathIterator extends NodeSet implements Cloneable
  {
    /**
     * Constructor to create an instance which you can add location paths to.
     */
    public UnionPathIterator()
    {
      super();
      m_mutable = false;
      m_cacheNodes = false;
      m_iterators = null;
    }
    
    /**
     * Add an iterator to the union list.
     */
    public void addIterator(LocPathIterator iter)
    {
      // Increase array size by only 1 at a time.  Fix this
      // if it looks to be a problem.
      if(null == m_iterators)
      {
        m_iterators = new LocPathIterator[1];
        m_iterators[0] = iter;
      }
      else
      {
        LocPathIterator[] iters = m_iterators;
        int len = m_iterators.length;
        m_iterators = new LocPathIterator[len+1];
        System.arraycopy(iters, 0, m_iterators, 0, len);
        m_iterators[len] = iter;
      }
    
    }
  
    /**
     * Package-private constructor, which takes the 
     * same arguments as XLocator's union() function, plus the 
     * locator reference.
     */
    UnionPathIterator(XPath xpath, XPathContext execContext, 
                      Node context, int opPos,
                      SimpleNodeLocator locator)
    {
      super();
      m_mutable = false;
      m_cacheNodes = false;
  
      this.m_xpath = xpath;
      this.m_execContext = execContext;
      this.m_currentContextNode = execContext.getCurrentNode();
      this.m_context = context;
      this.m_locator = locator;
      opPos = xpath.getFirstChildPos(opPos); 
      loadLocationPaths(opPos, 0);
      
      // Swoop through all iterators, asking them to find
      // their first node.
      int n = m_iterators.length;
      for(int i = 0; i < n; i++)
      {
        m_iterators[i].nextNode();
      }
    }
    
    /**
     * Get a cloned LocPathIterator.
     */
    public Object clone()
      throws CloneNotSupportedException
    {
      UnionPathIterator clone = (UnionPathIterator)super.clone();
      int n = m_iterators.length;
      clone.m_iterators = new LocPathIterator[n];
      for(int i = 0; i < n; i++)
      {
        clone.m_iterators[i] = (LocPathIterator)m_iterators[i].clone();
      }
      return clone;
    }
    
    /**
     * Reset the iterator.
     */
    public void reset()
    {
      super.reset();
      m_foundLast = false;
      int n = m_iterators.length;
      for(int i = 0; i < n; i++)
      {
        m_iterators[i].reset();
      }
    }
    
    /**
     * Initialize the location path iterators.
     */
    protected void loadLocationPaths(int opPos, int count)
    {    
      // TODO: Handle unwrapped FilterExpr
      int steptype = m_xpath.m_opMap[opPos];
      if((steptype & OpCodes.LOCATIONPATHEX_MASK) == OpCodes.OP_LOCATIONPATH)
      {
        loadLocationPaths(m_xpath.getNextOpPos(opPos), count+1);
        m_iterators[count] = createLocPathIterator(opPos);
      }
      else
      {
        // Have to check for unwrapped functions, which the LocPathIterator
        // doesn't handle. 
        switch(steptype)
        {
        case OpCodes.OP_VARIABLE:
        case OpCodes.OP_EXTFUNCTION:
        case OpCodes.OP_FUNCTION:
        case OpCodes.OP_GROUP:
          loadLocationPaths(m_xpath.getNextOpPos(opPos), count+1);
          LocPathIterator iter = new LocPathIterator(m_execContext,
                                                     
m_execContext.getNamespaceContext(),
                                                     m_context);
          iter.m_xpath = m_xpath;
          iter.m_opPos = opPos;
          iter.m_firstWalker = new 
org.apache.xalan.xpath.axes.FilterExprWalker(iter);
          iter.m_firstWalker.setOpPos(opPos);
          m_iterators[count] = iter;
          break;
        default:
          m_iterators = new LocPathIterator[count];
        }
  
        
      }
    }
    
    /**
     * Create a new location path iterator.
     */
    protected LocPathIterator createLocPathIterator(int opPos)
    {
      return new LocPathIterator(m_xpath, m_execContext,
                                          m_context, opPos, m_locator);
    }
  
    /**
     *  Returns the next node in the set and advances the position of the 
     * iterator in the set. After a NodeIterator is created, the first call 
     * to nextNode() returns the first node in the set.
     * @return  The next <code>Node</code> in the set being iterated over, or
     *   <code>null</code> if there are no more members in that set.
     * @exception DOMException
     *    INVALID_STATE_ERR: Raised if this method is called after the
     *   <code>detach</code> method was invoked.
     */
    public Node nextNode()
      throws DOMException
    {    
      // If the cache is on, and the node has already been found, then 
      // just return from the list.
      if(this.m_cacheNodes && (m_next < (this.size() -1)))
        return super.nextNode();
  
      if(m_foundLast)
        return null;
      
      // Loop through the iterators getting the current fetched 
      // node, and get the earliest occuring in document order
      Node earliestNode = null;
      int n = m_iterators.length;
      int iteratorUsed = -1;
      for(int i = 0; i < n; i++)
      {
        Node node = m_iterators[i].getCurrentNode();
        if(null == node)
          continue;
        else if(null == earliestNode)
        {
          iteratorUsed = i;
          earliestNode = node;
        }
        else
        {
          if(node.equals(earliestNode))
          {
            // Found a duplicate, so skip past it.
            m_iterators[i].nextNode();
          }
          else
          {
            DOMHelper dh = m_execContext.getDOMHelper();
            if(dh.isNodeAfter(node, earliestNode))
            {
              iteratorUsed = i;
              earliestNode = node;
            }
          }
        }
      }
      
      if(null != earliestNode)
      {
        m_iterators[iteratorUsed].nextNode();
        if(this.m_cacheNodes)
          this.addElement(earliestNode);
        m_next++;
      }
      else
        m_foundLast = true;
      
      return earliestNode;
    }
    
    /**
     * If an index is requested, NodeSet will call this method 
     * to run the iterator to the index.  By default this sets 
     * m_next to the index.  If the index argument is -1, this 
     * signals that the iterator should be run to the end.
     */
    public void runTo(int index)
    {
      if(m_foundLast || ((index >= 0) && (index <= m_next)))
        return;
      
      Node n;
      while(null == (n = nextNode()))
      {
        if(m_next >= index)
          break;
      }
    }
    
    /**
     * Tells if we've found the last node yet.
     */
    protected boolean m_foundLast = false;
    
    /**
     * The XPath that contains the union expression.
     */
    protected XPath m_xpath;
    
    /**
     * The execution context for the expression.
     */
    protected XPathContext m_execContext;
    
    /**
     * The node context for the expression.
     */
    protected Node m_context;
    
    /**
     * The node context from where the Location Path is being 
     * executed from (i.e. for current() support).
     */
    protected Node m_currentContextNode;
    public Node getCurrentContextNode() { return m_currentContextNode; }
      
    /**
     * Reference to the SimpleNodeLocator that created 
     * this instance.
     */
    protected SimpleNodeLocator m_locator;
    
    /**
     * The location path iterators, one for each 
     * <a href="http://www.w3.org/TR/xpath#NT-LocationPath";>location 
     * path</a> contained in the union expression.
     */
    protected LocPathIterator[] m_iterators;
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/VariableStack.java
  
  Index: VariableStack.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import java.util.Stack;
  import java.util.Vector;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XRTreeFrag;
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  import org.xml.sax.SAXException;
  
  /**
   * <meta name="usage" content="internal"/>
   * Defines a class to keep track of a stack for
   * template arguments and variables, since we can't 
   * simply bind the variables to templates and walk 
   * the preceding children and ancestors.  The stack 
   * is delimited by context markers which bound call 
   * frames, and which you can't search past for a variable, 
   * and by element frames, which are Arg objects with 
   * the given ElemTemplateElement instead of a qname. You 
   * can search past element frames, and they accumulate
   * until they are popped.
   * 
   * Note: Someone recently made the suggestion that the 
   * globals should not be kept at the bottom of the stack, 
   * but should be implemented in a hash table.
   */
  public class VariableStack extends Stack
  {
    /**
     * Constructor for a variable stack.
     */
    public VariableStack()
    {
      pushContextMarker();
    }
  
    private static final Integer contextMarker = new Integer(0);
    private static final Arg m_elemFrameBoundry = new Arg();
    private int m_globalStackFrameIndex = -1;
  
    /**
     * This is the top of the stack frame from where a search 
     * for a variable or param should take place.  It may not 
     * be the real stack top.
     */
    private int m_currentStackFrameIndex = 0;
  
    /**
     * Mark the top of the global stack frame.
     */
    public void markGlobalStackFrame()
    {
      m_globalStackFrameIndex = this.size();
      push(contextMarker);
    }
      
    /**
     * Set the top of the stack frame from where a search 
     * for a variable or param should take place.
     */
    public void setCurrentStackFrameIndex(int currentStackFrameIndex)
    {
      m_currentStackFrameIndex = currentStackFrameIndex;
    }
    
    /**
     * Get the top of the stack frame from where a search 
     * for a variable or param should take place.
     */
    public int getCurrentStackFrameIndex()
    {
      return m_currentStackFrameIndex;
    }
    
    // Push a context marker onto the stack to let us know when
    // to stop searching for a var.
    public void pushContextMarker()
    {
      push(contextMarker);
    }
    
    /**
     * Override the push in order to track the 
     * m_currentStackFrameIndex correctly.
     */
    public Object push(Object o)
    {
      if(m_currentStackFrameIndex == this.size())
        m_currentStackFrameIndex+=1;
      return super.push(o);
    }
  
    /**
     * Override the pop in order to track the 
     * m_currentStackFrameIndex correctly.
     */
    public Object pop()
    {
      if(m_currentStackFrameIndex == this.size())
        m_currentStackFrameIndex-=1;
      return super.pop();
    }
  
    /**
     * Override the setSize in order to track the 
     * m_currentStackFrameIndex correctly.
     */
    public void setStackSize(int sz)
    {
      boolean b = (m_currentStackFrameIndex == this.size());
      setSize(sz);
      if(b)
        m_currentStackFrameIndex = this.size();
    }
  
    /**
     * Pop the current context from the current context stack.
     */
    public void popCurrentContext()
    {
      int nElems = size();
      // Sub 1 extra for the context marker.
      for(int i = (nElems - 1); i >= 0; i--)
      {
        if(this.elementAt(i) == contextMarker)
        {
          this.setStackSize(i);
          break;
        }
      }
    }
    
    /**
     * Push an argument onto the stack.  Don't forget
     * to call startContext before pushing a series of
     * arguments for a given macro call.
     */
    public void pushVariable(QName qname, XObject val)
    {
      push(new Arg(qname, val, false));
    }
  
    /**
     * Same as getVariable, except don't look in the
     * global space.
     */
    public XObject getParamVariable(QName qname)
      throws SAXException
    {
      XObject val = null;
      int nElems = getCurrentStackFrameIndex();
  
      for(int i = (nElems - 1); i >= 0; i--)
      {
        Object obj = elementAt(i);
        
        if(obj == contextMarker)
        {
          break;
        }
        else if(((Arg)obj).equals(qname))
        {
          val = ((Arg)obj).getVal();
          break;
        }
      }
      return val;
    }
  
  
    /**
     * Given a name, return a string representing
     * the value.
     */
    public Object getVariable(QName name)
      throws SAXException
    {
      int nElems = getCurrentStackFrameIndex();
      // Sub 1 extra for the context marker.
      for(int i = (nElems - 1); i >= 0; i--)
      {
        Object obj = elementAt(i);
        if(obj == contextMarker)
        {
          break;
        }
        else if(((Arg)obj).equals(name))
        {
          return ((Arg)obj).getVal();
        }
      }
  
      // Look in the global space
      for(int i = (m_globalStackFrameIndex-1); i >= 2; i--)
      {
        Object obj = elementAt(i);
        if(obj == contextMarker)
          break;
        else if(((Arg)obj).equals(name))
          return ((Arg)obj).getVal();
      }
      
      return null;
    }
      
    /**
     * Push an argument onto the stack.  Don't forget
     * to call startContext before pushing a series of
     * arguments for a given macro call.
     */
    public void pushElemFrame()
    {
      push(m_elemFrameBoundry);
    }
    
    /**
     * Pop the current context from the current context stack.
     */
    public void popElemFrame()
    {
      int nElems = size();
      // Sub 1 extra for the context marker.
      for(int i = (nElems - 1); i >= 0; i--)
      {
        Object obj = this.elementAt(i);
        if(obj == contextMarker)
        {
          break;
        }
        else if(obj == m_elemFrameBoundry)
        {
          this.setStackSize(i);
          break;
        }
      }
    }
  
  
    
  } // end XSLArgStack
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XBoolean.java
  
  Index: XBoolean.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.*;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This class represents an XPath boolean object, and is capable of 
   * converting the boolean to other types, such as a string.
   */
  public class XBoolean extends XObject
  {
    /**
     * <meta name="usage" content="internal"/>
     * A true boolean object so we don't have to keep creating them.
     */
    public static XBoolean S_TRUE = new XBooleanStatic(true);
    
    /**
     * <meta name="usage" content="internal"/>
     * A true boolean object so we don't have to keep creating them.
     */
    public static XBoolean S_FALSE = new XBooleanStatic(false);
  
    boolean m_val;
    /**
     * Construct a XNodeSet object.
     */
    public XBoolean(boolean b)
    {
      super();
      m_val = b;
    }
    
    /**
     * Tell that this is a CLASS_BOOLEAN.
     */
    public int getType()
    {
      return CLASS_BOOLEAN;
    }
    
    /**
     * Given a request type, return the equivalent string. 
     * For diagnostic purposes.
     */
    private String getTypeString()
    {
      return "#BOOLEAN";
    }
    
    /**
     * Cast result object to a number.
     */
    public double num()
    {
      return m_val ? 1.0 : 0.0;
    }
  
    /**
     * Cast result object to a boolean.
     */
    public boolean bool()
    {
      return m_val;
    }
  
    /**
     * Cast result object to a string.
     */
    public String str()
    {
      return m_val ? "true" : "false";
    }
    
    /**
     * Return a java object that's closes to the represenation 
     * that should be handed to an extension.
     */
    public Object object()
    {
      return new Boolean(m_val);
    }
  
    /**
     * Tell if two objects are functionally equal.
     */
    public boolean equals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.equals(this);
  
      return m_val == obj2.bool();
  }
  
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/XBooleanStatic.java
  
  Index: XBooleanStatic.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.*;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.res.XSLMessages;
  
  /**
   * <meta name="usage" content="internal"/>
   * This class doesn't have any XPathContext, so override 
   * whatever to ensure it works OK.
   */
  public class XBooleanStatic extends XBoolean
  {
    boolean m_val;
    
    /**
     * Construct a XNodeSet object.
     */
    public XBooleanStatic(boolean b)
    {
      super(b);
      m_val = b;
    }
    
    /**
     * Tell if two objects are functionally equal.
     */
    public boolean equals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      return m_val == obj2.bool();
    }
  
  }
  
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XLocator.java
  
  Index: XLocator.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.*;
  import java.util.*;
  import java.io.Serializable;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This interface provides services for processing a 
   * XPath LocationPath.  Either the default implementation 
   * (SimpleNodeLocator) will be used to implement this interface, 
   * or an extension function that serves as a factory method can be 
   * used that returns an XLocator.
   */
  public interface XLocator extends Serializable
  {
    /**
     * Execute a connection (if it was not executed by the static 
     * connect method) and process the following LocationPath, 
     * if it is present.  Normally, the connection functionality 
     * should be executed by this function and not the static connect 
     * function, which is really a factory method for the XLocator 
     * instance.  The arguments to the static connect function
     * are re-passed to this function.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param connectArgs The same arguments that were passed to the 
     * static connect function.
     * @returns the result of the query in an XNodeSet object.
     */
    XNodeSet connectToNodes(XPath xpath, XPathContext xctxt, Node context, 
                                 int opPos, Vector connectArgs)
      throws org.xml.sax.SAXException;
    
    /**
     * Execute a union. The union of its operands, which are locationPaths,
     * must be node-sets.
     * @param xpath The xpath that is executing.
     * @param xctxt The execution context.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param callback Interface that implements the processLocatedNode method.
     * @param callbackInfo Object that will be passed to the processLocatedNode 
method.
     * @returns the result of the query in an XNodeSet object.
     */
    XNodeSet union(XPath xpath, XPathContext xctxt, Node context, 
                   int opPos) 
      throws org.xml.sax.SAXException;
  
    /**
     * Execute a location path.  Normally, this method simply 
     * moves past the OP_LOCATIONPATH and it's length member, 
     * and calls the Step function, which will recursivly process 
     * the rest of the LocationPath, and then wraps the NodeList result
     * in an XNodeSet object.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param callback Interface that implements the processLocatedNode method.
     * @param callbackInfo Object that will be passed to the processLocatedNode 
method.
     * @param stopAtFirst True if only the first found node in doc order is 
needed.
     * @returns the result of the query in an XNodeSet object.
     */
    XNodeSet locationPath(XPath xpath, XPathContext xctxt, 
                          Node context, int opPos)
      throws org.xml.sax.SAXException;
    
    /**
     * Execute a location path pattern.  This will return a score
     * of MATCH_SCORE_NONE, MATCH_SCORE_NODETEST, 
     * MATCH_SCORE_OTHER, MATCH_SCORE_QNAME.
     * @param xpath The xpath that is executing.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @returns score, one of MATCH_SCORE_NODETEST, 
     * MATCH_SCORE_NONE, MATCH_SCORE_OTHER, MATCH_SCORE_QNAME.
     */
    double locationPathPattern(XPath xpath, XPathContext xctxt, Node context, 
int opPos)
      throws org.xml.sax.SAXException;
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XNodeSet.java
  
  Index: XNodeSet.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Text;
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.traversal.NodeIterator;
  import org.apache.xalan.xpath.DOMHelper;
  import org.apache.xalan.utils.StringVector;
  
  /**
   * <meta name="usage" content="general"/>
   * This class represents an XPath nodeset object, and is capable of 
   * converting the nodeset to other types, such as a string.
   */
  public class XNodeSet extends XObject
  {  
    /**
     * Construct a XNodeSet object.
     */
    public XNodeSet(NodeIterator val)
    {
      super(val);
    }
    
    /**
     * Construct an empty XNodeSet object.
     */
    public XNodeSet()
    {
      super(new NodeSet());
    }
  
    /**
     * Construct a XNodeSet object for one node.
     */
    public XNodeSet(Node n)
    {
      super(new NodeSet());
      if(null != n)
      {
        ((NodeSet)m_obj).addNode(n);
      }
    }
   
   
    /**
     * Tell that this is a CLASS_NODESET.
     */
    public int getType()
    {
      return CLASS_NODESET;
    }
    
    /**
     * Given a request type, return the equivalent string. 
     * For diagnostic purposes.
     */
    private String getTypeString()
    {
      return "#NODESET";
    }
    
    /**
     * Get the string conversion from a single node.
     */
    double getNumberFromNode(Node n)
    {
      return XString.castToNum(getStringFromNode(n));
    }
  
    /**
     * Cast result object to a number.
     */
    public double num()
    {
      NodeIterator nl = nodeset();
      Node node = nl.nextNode();
      return (node != null) ? getNumberFromNode(node) : Double.NaN;
    }
  
    /**
     * Cast result object to a boolean.
     */
    public boolean bool()
    {
      return (nodeset().nextNode() != null);
    }
    
  
    /**
     * Get the string conversion from a single node.
     */
    public static String getStringFromNode(Node n)
    {
      switch(n.getNodeType())
      {
      case Node.ELEMENT_NODE:
      case Node.DOCUMENT_NODE:
        return DOMHelper.getNodeData(n);
      case Node.CDATA_SECTION_NODE:
      case Node.TEXT_NODE:
        return ((Text)n).getData();
      case Node.COMMENT_NODE:
      case Node.PROCESSING_INSTRUCTION_NODE:
      case Node.ATTRIBUTE_NODE:
        return n.getNodeValue();
      default:
        return DOMHelper.getNodeData(n);
      }
    }
  
    /**
     * Cast result object to a string.
     */
    public String str()
    {
      NodeIterator nl = nodeset();
      Node node = nl.nextNode();
      return (node != null) ? getStringFromNode(node) : "";
    }
    
    /**
     * Cast result object to a result tree fragment.
     */
    public DocumentFragment rtree(XPathContext support)
    {
      DocumentFragment frag = 
support.getDOMHelper().getDOMFactory().createDocumentFragment();
      NodeIterator nl = nodeset();
      Node node;
      while(null != (node = nl.nextNode()))
      {
        frag.appendChild(node.cloneNode(true));
      }
      return frag;
    }
  
    /**
     * Cast result object to a nodelist.
     */
    public NodeSet nodeset()
    {
      NodeSet ns = (NodeSet)m_obj;
      if(ns.isFresh())
      {
        return ns;
      }
      else
      {
        try
        {
          return ns.cloneWithReset();
        }
        catch(CloneNotSupportedException cnse)
        {
          throw new RuntimeException(cnse.getMessage());
        }
      }
    }  
  
    /**
     * Cast result object to a nodelist.
     */
    public NodeSet mutableNodeset()
    {
      NodeSet mnl;
      if (m_obj instanceof NodeSet)
      {
        mnl = (NodeSet)m_obj;
      }
      else
      {
        mnl = new NodeSet(nodeset());
        m_obj = mnl;
      }
      
      return mnl;
    }  
    
    static LessThanComparator S_LT = new LessThanComparator();
    static LessThanOrEqualComparator S_LTE = new LessThanOrEqualComparator();
    static GreaterThanComparator S_GT = new GreaterThanComparator();
    static GreaterThanOrEqualComparator S_GTE = new 
GreaterThanOrEqualComparator();
    static EqualComparator S_EQ = new EqualComparator();
    static NotEqualComparator S_NEQ = new NotEqualComparator();
    
    /**
     * Tell if one object is less than the other.
     */
    public boolean compare(XObject obj2, Comparator comparator)
      throws org.xml.sax.SAXException
    {
      boolean result = false;
      int type = obj2.getType();
      if(XObject.CLASS_NODESET == type)
      {
        // From http://www.w3.org/TR/xpath: 
        // If both objects to be compared are node-sets, then the comparison 
        // will be true if and only if there is a node in the first node-set 
        // and a node in the second node-set such that the result of performing 
        // the comparison on the string-values of the two nodes is true.
  
        // Note this little gem from the draft:
        // NOTE: If $x is bound to a node-set, then $x="foo" 
        // does not mean the same as not($x!="foo"): the former 
        // is true if and only if some node in $x has the string-value 
        // foo; the latter is true if and only if all nodes in $x have 
        // the string-value foo.
  
        NodeIterator list1 = nodeset();
        NodeIterator list2 = ((XNodeSet)obj2).nodeset();
        Node node1;
        StringVector node2Strings = null;
        while(null != (node1 = list1.nextNode()))
        {
          String s1 = getStringFromNode(node1);
          if(null == node2Strings)
          {
            Node node2;
            while(null != (node2 = list2.nextNode()))
            {
              String s2 = getStringFromNode(node2);
              if(comparator.compareStrings(s1, s2))
              {
                result = true;
                break;
              }
              if(null == node2Strings)
                node2Strings = new StringVector();
              node2Strings.addElement(s2);
            }
          }
          else
          {
            int n = node2Strings.size();
            for(int i = 0; i < n; i++)
            {
              if(comparator.compareStrings(s1, node2Strings.elementAt(i)))
              {
                result = true;
                break;
              }
            }
          }
        }
      }
      else if(XObject.CLASS_BOOLEAN == type)
      {
        // From http://www.w3.org/TR/xpath: 
        // If one object to be compared is a node-set and the other is a 
boolean, 
        // then the comparison will be true if and only if the result of 
        // performing the comparison on the boolean and on the result of 
        // converting the node-set to a boolean using the boolean function 
        // is true.
        double num1 = bool() ? 1.0 : 0.0;
        double num2 = obj2.num();
        result = comparator.compareNumbers(num1, num2);
      }
      else if(XObject.CLASS_NUMBER == type)
      {
        // From http://www.w3.org/TR/xpath: 
        // If one object to be compared is a node-set and the other is a 
number, 
        // then the comparison will be true if and only if there is a 
        // node in the node-set such that the result of performing the 
        // comparison on the number to be compared and on the result of 
        // converting the string-value of that node to a number using 
        // the number function is true. 
              
        NodeIterator list1 = nodeset();
        double num2 = obj2.num();
        Node node;
        while(null != (node = list1.nextNode()))
        {
          double num1 = getNumberFromNode(node);
          if(comparator.compareNumbers(num1, num2))
          {
            result = true;
            break;
          }
        }
      }
      else if(XObject.CLASS_RTREEFRAG == type)
      {
        // hmmm... 
        double num2 = obj2.num();
        if(num2 != Double.NaN)
        {
          NodeIterator list1 = nodeset();
          Node node;
          while(null != (node = list1.nextNode()))
          {
            double num1 = getNumberFromNode(node);
            if(comparator.compareNumbers(num1, num2))
            {
              result = true;
              break;
            }
          }
        }
        else
        {
          String s2 = obj2.str();
          NodeIterator list1 = nodeset();
          Node node;
          while(null != (node = list1.nextNode()))
          {
            String s1 = getStringFromNode(node);
            if(comparator.compareStrings(s1, s2))
            {
              result = true;
              break;
            }
          }
        }
      }
      else if(XObject.CLASS_STRING == type)
      {
        // From http://www.w3.org/TR/xpath: 
        // If one object to be compared is a node-set and the other is a 
        // string, then the comparison will be true if and only if there 
        // is a node in the node-set such that the result of performing 
        // the comparison on the string-value of the node and the other 
        // string is true. 
        String s2 = obj2.str();
        NodeIterator list1 = nodeset();
        Node node;
        while(null != (node = list1.nextNode()))
        {
          String s1 = getStringFromNode(node);
          if(comparator.compareStrings(s1, s2))
          {
            result = true;
            break;
          }
        }
      }
      else
      {
        result = comparator.compareNumbers(this.num(), obj2.num());
      }
      return result;
    }
  
  
    /**
     * Tell if one object is less than the other.
     */
    public boolean lessThan(XObject obj2)
      throws org.xml.sax.SAXException
    {
      return compare(obj2, S_LT);
    }
  
    /**
     * Tell if one object is less than or equal to the other.
     */
    public boolean lessThanOrEqual(XObject obj2)
      throws org.xml.sax.SAXException
    {
      return compare(obj2, S_LTE);
    }
  
    /**
     * Tell if one object is less than the other.
     */
    public boolean greaterThan(XObject obj2)
      throws org.xml.sax.SAXException
    {
      return compare(obj2, S_GT);
    }
  
    /**
     * Tell if one object is less than the other.
     */
    public boolean greaterThanOrEqual(XObject obj2)
      throws org.xml.sax.SAXException
    {
      return compare(obj2, S_GTE);
    }
  
    /**
     * Tell if two objects are functionally equal.
     */
    public boolean equals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      return compare(obj2, S_EQ);
    }
    
    /**
     * Tell if two objects are functionally not equal.
     */
    public boolean notEquals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      return compare(obj2, S_NEQ);
    }
  
  }
  
  /**
   * compares nodes for various boolean operations.
   */
  abstract class Comparator
  {
    abstract boolean compareStrings(String s1, String s2);
    abstract boolean compareNumbers(double n1, double n2);
  }
    
  /**
   * Compare strings or numbers for less than.
   */
  class LessThanComparator extends Comparator
  {
    boolean compareStrings(String s1, String s2) 
    {
      return s1.compareTo(s2) < 0;
    }
    
    boolean compareNumbers(double n1, double n2)
    {
      return n1 < n2;
    }
  }
  
  /**
   * Compare strings or numbers for less than or equal.
   */
  class LessThanOrEqualComparator extends Comparator
  {
    boolean compareStrings(String s1, String s2) 
    {
      return s1.compareTo(s2) <= 0;
    }
    
    boolean compareNumbers(double n1, double n2)
    {
      return n1 <= n2;
    }
  }
    
  /**
   * Compare strings or numbers for greater than.
   */
  class GreaterThanComparator extends Comparator
  {
    boolean compareStrings(String s1, String s2) 
    {
      return s1.compareTo(s2) > 0;
    }
    
    boolean compareNumbers(double n1, double n2)
    {
      return n1 > n2;
    }
  }
    
  /**
   * Compare strings or numbers for greater than or equal.
   */
  class GreaterThanOrEqualComparator extends Comparator
  {
    boolean compareStrings(String s1, String s2) 
    {
      return s1.compareTo(s2) >= 0;
    }
    
    boolean compareNumbers(double n1, double n2)
    {
      return n1 >= n2;
    }
  }
    
  /**
   * Compare strings or numbers for equality.
   */
  class EqualComparator extends Comparator
  {
    boolean compareStrings(String s1, String s2) 
    {
      return s1.equals(s2);
    }
    
    boolean compareNumbers(double n1, double n2)
    {
      return n1 == n2;
    }
  }
  
  /**
   * Compare strings or numbers for non-equality.
   */
  class NotEqualComparator extends Comparator
  {
    boolean compareStrings(String s1, String s2) 
    {
      return !s1.equals(s2);
    }
    
    boolean compareNumbers(double n1, double n2)
    {
      return n1 != n2;
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XNull.java
  
  Index: XNull.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.DocumentFragment;
  
  /**
   * <meta name="usage" content="general"/>
   * This class represents an XPath null object, and is capable of 
   * converting the null to other types, such as a string.
   */
  public class XNull extends XObject
  {
    /**
     * Create an XObject.
     */
    public XNull()
    {
      super();
    }
  
    /**
     * Tell what kind of class this is.
     */
    public int getType()
    {
      return CLASS_NULL;
    }
  
    /**
     * Given a request type, return the equivalent string. 
     * For diagnostic purposes.
     */
    private String getTypeString()
    {
      return "#CLASS_NULL";
    }
  
  /**
     * Cast result object to a number.
     */
    public double num()
    {
      return 0.0;
    }
  
    /**
     * Cast result object to a boolean.
     */
    public boolean bool()
    {
      return false;
    }
  
    /**
     * Cast result object to a string.
     */
    public String str()
    {
      return "";
    }
    
    /**
     * Cast result object to a result tree fragment.
     */
    public DocumentFragment rtree(XPathContext support)
    {
      DocumentFragment result = 
support.getDOMHelper().getDOMFactory().createDocumentFragment();
      return result;
    }
  
    /**
     * Cast result object to a nodelist.
     */
    public NodeSet nodeset()
    {
      return null;
    }  
     
    /**
     * Tell if two objects are functionally equal.
     */
    public boolean equals(XObject obj2)
    {
      return obj2.getType() == CLASS_NULL;
  }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XNumber.java
  
  Index: XNumber.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.*;
  
  /**
   * <meta name="usage" content="general"/>
   * This class represents an XPath number, and is capable of 
   * converting the number to other types, such as a string.
   */
  public class XNumber extends XObject
  {
    double m_val;
    
    /**
     * Construct a XNodeSet object.
     */
    public XNumber(double d)
    {
      super();
      m_val = d;
    }
    
    /**
     * Tell that this is a CLASS_NUMBER.
     */
    public int getType()
    {
      return CLASS_NUMBER;
    }
    
    /**
     * Given a request type, return the equivalent string. 
     * For diagnostic purposes.
     */
    private String getTypeString()
    {
      return "#NUMBER";
    }
    
    /**
     * Cast result object to a number.
     */
    public double num()
    {
      return m_val;
    }
  
    /**
     * Cast result object to a boolean.
     */
    public boolean bool()
    {
      return (Double.isNaN(m_val) || (m_val == 0.0)) ? false : true;
    }
    
    /**
     * Cast result object to a string.
     */
    public String str()
    {
      if(Double.isNaN(m_val))
      {
        return "NaN";
      }
      else if(Double.isInfinite(m_val))
      {
        if(m_val > 0)
          return "Infinity";
        else
          return "-Infinity";
      }
      
      // java.text.NumberFormat formatter 
      //         = java.text.NumberFormat.getNumberInstance();
      java.text.DecimalFormat formatter = new 
java.text.DecimalFormat("0.##################");
    
      String s = formatter.format(m_val);
      
      // Hack to get around some VMs tendency to format integers to '1.0' 
      // instead of '1'.  I would rather do that than muck with the pattern 
      // handed in to NumberFormat, since that is locale specific.
      // (not that this is locale sensitive... but at least it should be 
      // non-harmful in the case of a different locale...).
      if(s.endsWith(".0"))
      {
        s = s.substring(0, s.length() - 2);
      }
      return s;
    }
    
    /**
     * Return a java object that's closes to the represenation 
     * that should be handed to an extension.
     */
    public Object object()
    {
      return new Double(m_val);
    }
  
    /**
     * Tell if two objects are functionally equal.
     */
    public boolean equals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.equals(this);
  
      return m_val == obj2.num();
    }
  
  }
  
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XObject.java
  
  Index: XObject.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.Text;
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import java.io.Serializable;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.res.XSLMessages;
  
  /**
   * <meta name="usage" content="general"/>
   * This class represents an XPath object, and is capable of 
   * converting the object to various types, such as a string.
   * This class acts as the base class to other XPath type objects, 
   * such as XString, and provides polymorphic casting capabilities.
   */
  public class XObject extends Object implements Serializable
  {
    protected Object m_obj; // This may be NULL!!!
    
    /**
     * Create an XObject.
     */
    public XObject()
    {
    }
  
    /**
     * Create an XObject.
     */
    public XObject(Object obj)
    {
      m_obj = obj;
    }
    
    /**
     * Create the right XObject based on the type of the object passed.
     */
    static public XObject create(Object val)
    {
      XObject result;
      if(val instanceof XObject)
      {
        result = (XObject)val;
      }
      else if(val instanceof String)
      {
        result = new XString((String)val);
      }
      else if(val instanceof Boolean)
      {
        result = ((Boolean)val).booleanValue() ? XBoolean.S_TRUE : 
XBoolean.S_FALSE;
      }
      else if(val instanceof Double)
      {
        result = new XNumber(((Double)val).doubleValue());
      }
      else if(val instanceof DocumentFragment)
      {
        result = new XRTreeFrag((DocumentFragment)val);
      }
      else if(val instanceof Node)
      {
        result = new XNodeSet((Node)val);
      }
      else if(val instanceof NodeIterator)
      {
        result = new XNodeSet((NodeIterator)val);
      }
      else
      {
        result = new XObject(val);
      }
      return result;
    }
    
    public static final int CLASS_NULL = -1;
    public static final int CLASS_UNKNOWN = 0;
    public static final int CLASS_BOOLEAN = 1;
    public static final int CLASS_NUMBER = 2;
    public static final int CLASS_STRING = 3;
    public static final int CLASS_NODESET = 4;
    public static final int CLASS_RTREEFRAG = 5;
    
    /**
     * Tell what kind of class this is.
     */
    public int getType()
    {
      return CLASS_UNKNOWN;
    }
  
    /**
     * Given a request type, return the equivalent string. 
     * For diagnostic purposes.
     */
    private String getTypeString()
    {
      return "#UNKNOWN";
    }
    
    /**
     * Cast result object to a number.
     */
    public double num()
      throws org.xml.sax.SAXException
    {
          error(XPATHErrorResources.ER_CANT_CONVERT_TO_NUMBER, new Object[] 
{getTypeString()}); //"Can not convert "+getTypeString()+" to a number");
  
      return 0.0;
    }
  
    /**
     * Cast result object to a boolean.
     */
    public boolean bool()
      throws org.xml.sax.SAXException
    {
      error(XPATHErrorResources.ER_CANT_CONVERT_TO_NUMBER, new Object[] 
{getTypeString()}); //"Can not convert "+getTypeString()+" to a number");
  
      return false;
    }
  
    /**
     * Cast result object to a string.
     */
    public String str()
    {
      return m_obj.toString();
    }
    
    public String toString()
    {
      return str();
    }
    
    /**
     * Cast result object to a result tree fragment.
     */
    public DocumentFragment rtree(XPathContext support)
    {
      DocumentFragment result = rtree();
      if(null == result)
      {
        result = 
support.getDOMHelper().getDOMFactory().createDocumentFragment();
        Text textNode = 
support.getDOMHelper().getDOMFactory().createTextNode(str());
        result.appendChild(textNode);
      }
      return result;
    }
    
    /**
     * For functions to override.
     */
    public DocumentFragment rtree()
    {
      return null;
    }
    
    /**
     * Return a java object that's closes to the represenation 
     * that should be handed to an extension.
     */
    public Object object()
    {
      return m_obj;
    }
  
    /**
     * Cast result object to a nodelist.
     */
    public NodeSet nodeset()
      throws org.xml.sax.SAXException
    {
      error(XPATHErrorResources.ER_CANT_CONVERT_TO_NODELIST, new Object[] 
{getTypeString()}); //"Can not convert "+getTypeString()+" to a NodeList!");
      return null;
    }  
    
    /**
     * Cast result object to a nodelist.
     */
    public NodeSet mutableNodeset()
      throws org.xml.sax.SAXException
    {
      error(XPATHErrorResources.ER_CANT_CONVERT_TO_MUTABLENODELIST, new 
Object[] {getTypeString()}); //"Can not convert "+getTypeString()+" to a 
NodeSet!");
      return (NodeSet)m_obj;
    }  
   
    /**
     * Cast object to type t.
     */
    public Object castToType(int t, XPathContext support)
      throws org.xml.sax.SAXException
    {
      Object result;
      switch(t)
      {
      case CLASS_STRING:
        result = str();
        break;
      case CLASS_NUMBER:
        result = new Double(num());
        break;
      case CLASS_NODESET:
        result = nodeset();
        break;
      case CLASS_BOOLEAN:
        result = new Boolean( bool() );
        break;
      case CLASS_UNKNOWN:
        result = m_obj;
        break;
      case CLASS_RTREEFRAG:
        result = rtree(support);
        break;
      default:
        error(XPATHErrorResources.ER_CANT_CONVERT_TO_TYPE, new Object[] 
{getTypeString(), Integer.toString(t)}); //"Can not convert "+getTypeString()+" 
to a type#"+t);
        result = null;
      }
      return result;
    }
  
    /**
     * Tell if one object is less than the other.
     */
    public boolean lessThan(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.  Because the arguments 
      // are backwards, we call the opposite comparison
      // function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.greaterThan(this);
  
      return this.num() < obj2.num();
    }
  
    /**
     * Tell if one object is less than or equal to the other.
     */
    public boolean lessThanOrEqual(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.  Because the arguments 
      // are backwards, we call the opposite comparison
      // function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.greaterThanOrEqual(this);
      
      return this.num() <= obj2.num();
    }
  
    /**
     * Tell if one object is less than the other.
     */
    public boolean greaterThan(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.  Because the arguments 
      // are backwards, we call the opposite comparison
      // function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.lessThan(this);
  
      return this.num() > obj2.num();
    }
  
    /**
     * Tell if one object is less than the other.
     */
    public boolean greaterThanOrEqual(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.  Because the arguments 
      // are backwards, we call the opposite comparison
      // function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.lessThanOrEqual(this);
  
      return this.num() >= obj2.num();
    }
  
    /**
     * Tell if two objects are functionally equal.
     */
    public boolean equals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.equals(this);
  
      return m_obj.equals(obj2.m_obj);
    }
    
    /**
     * Tell if two objects are functionally not equal.
     */
    public boolean notEquals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.notEquals(this);
  
      return !equals(obj2);
    }
  
    /**
     * Tell the user of an error, and probably throw an 
     * exception.
     */
    protected void error(int msg)
      throws org.xml.sax.SAXException
    {
          error (msg, null);
    }      
  
    /**
     * Tell the user of an error, and probably throw an 
     * exception.
     */
    protected void error(int msg, Object[] args)
      throws org.xml.sax.SAXException
    {
      String fmsg = XSLMessages.createXPATHMessage(msg, args);  
      // boolean shouldThrow = support.problem(m_support.XPATHPROCESSOR, 
      //                                      m_support.ERROR,
      //                                      null, 
      //                                      null, fmsg, 0, 0);
      // if(shouldThrow)
      {
        throw new XPathException(fmsg);
      }
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XPath.java
  
  Index: XPath.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
   
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.DocumentFragment;
  import java.util.Vector;
  import java.io.Serializable;
  import java.io.ObjectInputStream;
  import java.io.IOException;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.utils.QName;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.xpath.functions.Function;
  import org.apache.xalan.xpath.functions.FuncLoader;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.extensions.ExtensionsTable;
  import org.xml.sax.ErrorHandler;
  import trax.TransformException;
  
  /** 
   * <meta name="usage" content="general"/>
   * The XPath class represents the semantic parse tree of the XPath pattern.
   * It is the representation of the grammar which filters out
   * the choice for replacement order of the production rules.
   * In order to conserve memory and reduce object creation, the 
   * tree is represented as an array of integers:
   *    [op code][length][...]
   * where strings are represented within the array as 
   * indexes into the token tree.
   */
  public class XPath extends OpMap
    implements Serializable
  {      
     
    /**
     * Construct an XPath object.  The object must be initialized by the 
     * XPathParser.initXPath method.
     */
    public XPath()
    {
    }
    
    /**
     * getXLocatorHandler.
     */
    private XLocator createXLocatorHandler(XPathContext callbacks)
    {
      return callbacks.createXLocatorHandler();
    }
  
    /**
     * <meta name="usage" content="experimental"/>
     * Given an expression and a context, evaluate the XPath 
     * and call the callback as nodes are found.  Only some simple 
     * types of expresions right now can call back, so if this 
     * method returns null, then the callbacks have been called, otherwise
     * a valid XObject will be returned.
     * @param xctxt The execution context.
     * @param contextNode The node that "." expresses.
     * @param namespaceContext The context in which namespaces in the 
     * XPath are supposed to be expanded.
     * @exception SAXException thrown if the active ProblemListener decides 
     * the error condition is severe enough to halt processing.
     * @param callback Interface that implements the processLocatedNode method.
     * @param callbackInfo Object that will be passed to the processLocatedNode 
method.
     * @param stopAtFirst True if the search should stop once the first node in 
document 
     * order is found.
     * @return The result of the XPath or null if callbacks are used.
     * @exception SAXException thrown if 
     * the error condition is severe enough to halt processing.
     */
    public XObject execute(XPathContext xctxt, Node contextNode, 
                           PrefixResolver namespaceContext)
      throws org.xml.sax.SAXException
    {    
      PrefixResolver savedPrefixResolver = xctxt.getNamespaceContext();
      xctxt.setNamespaceContext(namespaceContext);
      xctxt.setCurrentNode(contextNode);
      XObject xobj = null;
      try
      {
        xobj = execute(xctxt, contextNode, 0);
      }
      finally
      {
        xctxt.setNamespaceContext(savedPrefixResolver);
        xctxt.setCurrentNode(null); // I think this is probably fine
      }
      return xobj;
    }
    
    /**
     * Get the match score of the given node.
     * @param context The current source tree context node.
     * @returns score, one of MATCH_SCORE_NODETEST, 
     * MATCH_SCORE_NONE, MATCH_SCORE_OTHER, MATCH_SCORE_QNAME.
     */
    public double getMatchScore(XPathContext xctxt, Node context) 
      throws org.xml.sax.SAXException
    {
      double score = MATCH_SCORE_NONE;
      int opPos = 0;
      if(m_opMap[opPos] == OpCodes.OP_MATCHPATTERN)
      {
        opPos = getFirstChildPos(opPos);
        
        XLocator locator = 
xctxt.getSourceTreeManager().getXLocatorFromNode(context);
        
        if(null == locator)
          locator = xctxt.createXLocatorHandler();
  
        while(m_opMap[opPos] == OpCodes.OP_LOCATIONPATHPATTERN)
        {
          int nextOpPos = getNextOpPos(opPos);
          
          // opPos = getFirstChildPos(opPos);        
          score = locator.locationPathPattern(this, xctxt, context, opPos);
  
          if(score != MATCH_SCORE_NONE)
            break;
          opPos = nextOpPos;
        }
        
      }
      else
      {
        error(xctxt, context, XPATHErrorResources.ER_EXPECTED_MATCH_PATTERN, 
null); //"Expected match pattern in getMatchScore!");
      }
      
      return score;
    }
    
    /**
     * Install a built-in function.
     * @param name The unqualified name of the function.
     * @param funcIndex The index of the function in the table.
     * @param func A Implementation of an XPath Function object.
     * @return the position of the function in the internal index.
     */
    public void installFunction (String name, int funcIndex, Function func)
    {            
      FunctionTable.m_functions[funcIndex] = func;    
    }
  
    /**
     * OR two expressions and return the boolean result.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns XBoolean set to true if the one of the two arguments are true.
     */
    protected XBoolean or(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      XObject expr1 = execute(xctxt, context, opPos);
      if(!expr1.bool())
      {
        XObject expr2 = execute(xctxt, context, expr2Pos);
        return expr2.bool() ? XBoolean.S_TRUE : XBoolean.S_FALSE;
      }
      else
        return XBoolean.S_TRUE;
    }
  
    /**
     * OR two expressions and return the boolean result.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns XBoolean set to true if the two arguments are both true.
     */
    protected XBoolean and(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      XObject expr1 = execute(xctxt, context, opPos);
      if(expr1.bool())
      {
        XObject expr2 = execute(xctxt, context, expr2Pos);
        return expr2.bool() ? XBoolean.S_TRUE : XBoolean.S_FALSE;
      }
      else
        return XBoolean.S_FALSE;
    }
  
    /**
     * Tell if two expressions are functionally not equal.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns XBoolean set to true if the two arguments are not equal.
     */
    protected XBoolean notequals(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return (expr1.notEquals(expr2)) ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
  
  
    /**
     * Tell if two expressions are functionally equal.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns XBoolean set to true if the two arguments are equal.
     */
    protected XBoolean equals(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return expr1.equals(expr2) ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
      
    /**
     * Tell if one argument is less than or equal to the other argument.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns XBoolean set to true if arg 1 is less than or equal to arg 2.
     */
    protected XBoolean lte(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return expr1.lessThanOrEqual(expr2) ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
  
    /**
     * Tell if one argument is less than the other argument.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns XBoolean set to true if arg 1 is less than arg 2.
     */
    protected XBoolean lt(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return expr1.lessThan(expr2) ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
  
    /**
     * Tell if one argument is greater than or equal to the other argument.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns XBoolean set to true if arg 1 is greater than or equal to arg 2.
     */
    protected XBoolean gte(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return expr1.greaterThanOrEqual(expr2) ? XBoolean.S_TRUE : 
XBoolean.S_FALSE;
    }
  
  
    /**
     * Tell if one argument is greater than the other argument.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns XBoolean set to true if arg 1 is greater than arg 2.
     */
    protected XBoolean gt(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return expr1.greaterThan(expr2) ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
  
    /**
     * Give the sum of two arguments.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns sum of arg1 and arg2.
     */
    protected XNumber plus(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return new XNumber(expr1.num() +  expr2.num());
    }
  
    /**
     * Give the difference of two arguments.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns difference of arg1 and arg2.
     */
    protected XNumber minus(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return new XNumber(expr1.num() -  expr2.num());
    }
  
    /**
     * Multiply two arguments.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns arg1 * arg2.
     */
    protected XNumber mult(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return new XNumber(expr1.num() *  expr2.num());
    }
  
    /**
     * Divide a number.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns arg1 / arg2.
     */
    protected XNumber div(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return new XNumber(expr1.num() / expr2.num());
    }
  
    /**
     * Return the remainder from a truncating division.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns arg1 mod arg2.
     */
    protected XNumber mod(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return new XNumber(expr1.num() %  expr2.num());
    }
  
    /**
     * Return the remainder from a truncating division.
     * (Quo is no longer supported by xpath).
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns arg1 mod arg2.
     */
    protected XNumber quo(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      // Actually, this is no longer supported by xpath...
      warn(xctxt, context, XPATHErrorResources.WG_QUO_NO_LONGER_DEFINED, null); 
//"Old syntax: quo(...) is no longer defined in XPath.");
      
      opPos = getFirstChildPos(opPos);
      int expr2Pos = getNextOpPos(opPos);
      
      XObject expr1 = execute(xctxt, context, opPos);
      XObject expr2 = execute(xctxt, context, expr2Pos);
      
      return new XNumber((int)(expr1.num() /  expr2.num()));
    }
  
    /**
     * Return the negation of a number.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns -arg.
     */
    protected XNumber neg(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      XObject expr1 = execute(xctxt, context, opPos+2);
      
      return new XNumber(-expr1.num());
    }
  
    /**
     * Cast an expression to a string.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns arg cast to a string.
     */
    protected XString string(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      XObject expr1 = execute(xctxt, context, opPos+2);
      
      return new XString(expr1.str());
    }
  
    /**
     * Cast an expression to a boolean.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns arg cast to a boolean.
     */
    protected XBoolean bool(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      XObject expr1 = execute(xctxt, context, opPos+2);
      
      return expr1.bool() ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
   
    /**
     * Cast an expression to a number.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns arg cast to a number.
     */
    protected XNumber number(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      XObject expr1 = execute(xctxt, context, opPos+2);
      
      return new XNumber(expr1.num());
    }
    
    /**
     * Computes the union of its operands which must be node-sets.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @param callback Interface that implements the processLocatedNode method.
     * @param callbackInfo Object that will be passed to the processLocatedNode 
method.
     * @returns the union of node-set operands.
     */
    protected XNodeSet union(XPathContext xctxt, 
                             Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      XLocator xlocator = 
xctxt.getSourceTreeManager().getXLocatorFromNode(context);
      
      if(null == xlocator)
          xlocator = xctxt.createXLocatorHandler();
        
      XNodeSet results = xlocator.union(this, xctxt, 
                                        context, opPos);
      
      return results;
    }
  
    /**
     * Get a literal value.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns an XString object.
     */
    protected XString literal(XPathContext xctxt, Node context, int opPos) 
    {
      opPos = getFirstChildPos(opPos);
      
      // TODO: It's too expensive to create an object every time...
      return (XString)m_tokenQueue[m_opMap[opPos]];
    }
    
    /**
     * Get a literal value.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns an XObject object.
     */
    protected XObject variable(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      opPos = getFirstChildPos(opPos);
      String varName = (String)m_tokenQueue[m_opMap[opPos]];
      // System.out.println("variable name: "+varName);
      // TODO: I don't this will be parsed right in the first place...
      QName qname = new QName(varName, xctxt.getNamespaceContext());
      XObject result;
      try
      {
        result = xctxt.getVariable(qname);
      }
      catch(Exception e)
      {
        error(xctxt, context, XPATHErrorResources.ER_COULDNOT_GET_VAR_NAMED, 
new Object[] {varName}); //"Could not get variable named "+varName);
        result = null;
      }
  
      if(null == result)
      {
        error(xctxt, context, 
XPATHErrorResources.ER_ILLEGAL_VARIABLE_REFERENCE, new Object[] {varName}); 
//"VariableReference given for variable out "+
                      //"of context or without definition!  Name = " + varName);
        result = new XNodeSet();
      }
  
      return result;
    }
  
  
    /**
     * Execute an expression as a group.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns arg.
     */
    protected XObject group(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {    
      return execute(xctxt, context, opPos+2);
    }
  
  
    /**
     * Get a literal value.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns an XString object.
     */
    protected XNumber numberlit(XPathContext xctxt, Node context, int opPos) 
    {
      opPos = getFirstChildPos(opPos);
      
      return (XNumber)m_tokenQueue[m_opMap[opPos]];
    }
    
    /**
     * Execute a function argument.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns the result of the argument expression.
     */
    protected XObject arg(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {    
      return execute(xctxt, context, opPos+2);
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Execute a location path.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @param callback Interface that implements the processLocatedNode method.
     * @param callbackInfo Object that will be passed to the processLocatedNode 
method.
     * @returns a node-set.
     */
    public XNodeSet locationPath(XPathContext xctxt, 
                                 Node context, int opPos) 
      throws org.xml.sax.SAXException
    {    
      XLocator xlocator = 
xctxt.getSourceTreeManager().getXLocatorFromNode(context);
      
      if(null == xlocator)
          xlocator = xctxt.createXLocatorHandler();
        
      XNodeSet results = xlocator.locationPath(this, xctxt, context, opPos);
      
      return results;
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * Evaluate a predicate.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns either a boolean or a number.
     */
    public XObject predicate(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      XObject expr1 = execute(xctxt, context, opPos+2);
      int objType = expr1.getType();
      if((XObject.CLASS_NUMBER != objType) && (XObject.CLASS_BOOLEAN != 
objType))
      {
        expr1 = expr1.bool() ? XBoolean.S_TRUE : XBoolean.S_FALSE;
      }
      
      return expr1;
    }
    
    /**
     * Handle an extension function.
     */
    protected XObject extfunction(XPathContext xctxt, Node context, int opPos, 
                                  String namespace, String extensionName, 
                                  Vector argVec, Object methodKey) 
      throws org.xml.sax.SAXException
    {
      XObject result;
      ExtensionsTable etable = xctxt.getExtensionsTable();
      Object val = etable.extFunction(namespace, extensionName, 
                                      argVec, methodKey);
      if(null != val)
      {
        if(val instanceof XObject)
        {
          result = (XObject)val;
        }
        else if(val instanceof XLocator)
        {
          XLocator locator = (XLocator)val;
          opPos = getNextOpPos(opPos+1);
          result = locator.connectToNodes(this, xctxt, context, opPos, argVec); 
 
          // System.out.println("nodeset len: "+result.nodeset().getLength());
        }
        else if(val instanceof String)
        {
          result = new XString((String)val);
        }
        else if(val instanceof Boolean)
        {
          result = ((Boolean)val).booleanValue() ? XBoolean.S_TRUE : 
XBoolean.S_FALSE;
        }
        else if(val instanceof Double)
        {
          result = new XNumber(((Double)val).doubleValue());
        }
        else if(val instanceof DocumentFragment)
        {
          result = new XRTreeFrag((DocumentFragment)val);
        }
        else if(val instanceof Node)
        {
          // First, see if we need to follow-up with a location path.
          opPos = getNextOpPos(opPos);
          XNodeSet mnl = null;
          if((opPos < m_opMap[MAPINDEX_LENGTH]) &&
             (OpCodes.OP_LOCATIONPATH == (m_opMap[opPos] & 
OpCodes.LOCATIONPATHEX_MASK)))
          {
            mnl = locationPath(xctxt, (Node)val, opPos);
          }
          result = (null == mnl) ? new XNodeSet((Node)val)
                                   : mnl;
        }
        else if(val instanceof NodeIterator)
        {
          // First, see if we need to follow-up with a location path.
          opPos = getNextOpPos(opPos);
          XNodeSet mnl = null;
          if((opPos < m_opMap[MAPINDEX_LENGTH]) &&
             (OpCodes.OP_LOCATIONPATH == (m_opMap[opPos] & 
OpCodes.LOCATIONPATHEX_MASK)))
          {
            NodeIterator nl = (NodeIterator)val;
            Node node;
            while(null != (node = nl.nextNode()))
            {
              XNodeSet xnl = locationPath(xctxt, node, opPos);
              if(null == xnl)
                mnl = xnl;
              else
                mnl.mutableNodeset().addNodes(xnl.nodeset());
            }
          }
          result = (null == mnl) ? new XNodeSet((NodeIterator)val)
                                   : mnl;
        }
        else
        {
          result = new XObject(val);
        }
      }
      else
      {
        result = new XNull();
      }
      return result;
    }
  
  
    /**
     * Computes the union of its operands which must be node-sets.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns the match score in the form of an XObject.
     */
    protected XObject matchPattern(XPathContext xctxt, Node context, int opPos) 
      throws org.xml.sax.SAXException
    {
      XObject score = null;
  
      while(m_opMap[opPos] == OpCodes.OP_LOCATIONPATHPATTERN)
      {
        int nextOpPos = getNextOpPos(opPos);
        score = execute(xctxt, context, opPos);
        if(score.num() != MATCH_SCORE_NONE)
          break;
        opPos = nextOpPos;
      }
      if(null == score)
      {
        score = new XNumber(MATCH_SCORE_NONE);
      }
      
      return score;
    }
  
    /**
     * Execute a location path.
     * @param context The current source tree context node.
     * @param opPos The current position in the m_opMap array.
     * @returns score in an XNumber, one of MATCH_SCORE_NODETEST, 
     * MATCH_SCORE_NONE, MATCH_SCORE_OTHER, MATCH_SCORE_QNAME.
     */
    protected XNumber locationPathPattern(XPathContext xctxt, Node context, int 
opPos) 
      throws org.xml.sax.SAXException
    {    
      // opPos = getFirstChildPos(opPos);
      XLocator locator = 
xctxt.getSourceTreeManager().getXLocatorFromNode(context);
      
      if(null == locator)
          locator = xctxt.createXLocatorHandler();
        
      double results = locator.locationPathPattern(this, xctxt, context, opPos);
      
      return new XNumber(results);
    }
  
    /**
     * <meta name="usage" content="advanced"/>
     * This method is for building indexes of match patterns for fast lookup.
     * This allows a caller to get the name or type of a node, and quickly 
     * find the likely candidates that may match.
     */
    public Vector getTargetElementStrings()
    {
      Vector targetStrings = new Vector();
  
      int opPos = 2;
  
      while(m_opMap[opPos] == OpCodes.OP_LOCATIONPATHPATTERN)
      {
        int nextOpPos = getNextOpPos(opPos);
        opPos = getFirstChildPos(opPos);
        
        while( m_opMap[opPos] != OpCodes.ENDOP )
        {
          int nextStepPos = getNextOpPos(opPos);
          int nextOp = m_opMap[nextStepPos];
          if((nextOp == OpCodes.OP_PREDICATE) || (nextOp == OpCodes.ENDOP))
          {
            int stepType = m_opMap[opPos];
            opPos += 3;
            switch(stepType)
            {
            case OpCodes.OP_FUNCTION:
              targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
              break;
            case OpCodes.FROM_ROOT:
              targetStrings.addElement(PsuedoNames.PSEUDONAME_ROOT);
              break;
            case OpCodes.MATCH_ATTRIBUTE:
            case OpCodes.MATCH_ANY_ANCESTOR:
            case OpCodes.MATCH_IMMEDIATE_ANCESTOR:
              int tok = m_opMap[opPos];
              opPos++;
              switch(tok)
              {
              case OpCodes.NODETYPE_COMMENT:
                targetStrings.addElement(PsuedoNames.PSEUDONAME_COMMENT);
                break;
              case OpCodes.NODETYPE_TEXT:
                targetStrings.addElement(PsuedoNames.PSEUDONAME_TEXT);
                break;
              case OpCodes.NODETYPE_NODE:
                targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
                break;
              case OpCodes.NODETYPE_ROOT:
                targetStrings.addElement(PsuedoNames.PSEUDONAME_ROOT);
                break;
              case OpCodes.NODETYPE_ANYELEMENT:
                targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
                break;
              case OpCodes.NODETYPE_PI:
                targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
                break;
              case OpCodes.NODENAME:
                // Skip the namespace
                int tokenIndex = m_opMap[opPos+1];
                if(tokenIndex >= 0)
                {
                  String targetName = (String)m_tokenQueue[tokenIndex];
                  if(targetName.equals("*"))
                  {
                    targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
                  }
                  else
                  {
                    targetStrings.addElement(targetName);
                  }
                }
                else
                {
                  targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
                }
                break;
              default:
                targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY);
                break;
              }
              break;
            }
          }
          opPos = nextStepPos;
        }
        
        opPos = nextOpPos;
      }
      return targetStrings;
    }
      
    /**
     * Execute an extension function from an op code.
     */
    private XObject executeExtension(XPathContext xctxt, Node context, int 
opPos)
      throws org.xml.sax.SAXException
    {
      int endExtFunc = opPos+m_opMap[opPos+1]-1;
      opPos = getFirstChildPos(opPos);
      String ns = (String)m_tokenQueue[m_opMap[opPos]];
      opPos++;
      String funcName = (String)m_tokenQueue[m_opMap[opPos]];
      opPos++;
      Vector args = new Vector();
      while(opPos < endExtFunc)
      {
        int nextOpPos = getNextOpPos(opPos);
        args.addElement( execute(xctxt, context, opPos) );
        opPos = nextOpPos;
      }
      return extfunction(xctxt, context, opPos, ns, funcName, args, 
                         // Create a method key, for faster lookup.
        
String.valueOf(m_opMap[opPos])+String.valueOf(((Object)this).hashCode()));
    }
  
    /**
     * Execute a function from an op code.
     */
    XObject executeFunction(XPathContext xctxt, Node context, int opPos)
      throws org.xml.sax.SAXException
    {
      int endFunc = opPos+m_opMap[opPos+1]-1;
      opPos = getFirstChildPos(opPos);
      int funcID = m_opMap[opPos];
      opPos++;
      if(-1 != funcID)
      {
        return FunctionTable.m_functions[funcID].execute(this, xctxt, context, 
opPos, funcID, endFunc);
      }
      else
      {
        warn(xctxt, context, XPATHErrorResources.WG_FUNCTION_TOKEN_NOT_FOUND, 
null); //"function token not found.");
        return null;
      }
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * Execute the XPath object from a given opcode position.
     * @param xctxt The execution context.
     * @param context The current source tree context node.
     * @param opPos The current position in the xpath.m_opMap array.
     * @param callback Interface that implements the processLocatedNode method.
     * @param callbackInfo Object that will be passed to the processLocatedNode 
method.
     * @return The result of the XPath.
     */
    public XObject execute(XPathContext xctxt, 
                           Node context, int opPos)
      throws org.xml.sax.SAXException
    {
      int op = m_opMap[opPos];
      switch(op)
      {
      case OpCodes.OP_XPATH: return execute(xctxt, context, opPos+2);
      case OpCodes.OP_OR: return or(xctxt, context, opPos);
      case OpCodes.OP_AND: return and(xctxt, context, opPos);
      case OpCodes.OP_NOTEQUALS: return notequals(xctxt, context, opPos);
      case OpCodes.OP_EQUALS: return equals(xctxt, context, opPos);
      case OpCodes.OP_LTE: return lte(xctxt, context, opPos);
      case OpCodes.OP_LT: return lt(xctxt, context, opPos);
      case OpCodes.OP_GTE: return gte(xctxt, context, opPos);
      case OpCodes.OP_GT: return gt(xctxt, context, opPos);
      case OpCodes.OP_PLUS: return plus(xctxt, context, opPos);
      case OpCodes.OP_MINUS: return minus(xctxt, context, opPos);
      case OpCodes.OP_MULT: return mult(xctxt, context, opPos);
      case OpCodes.OP_DIV: return div(xctxt, context, opPos);
      case OpCodes.OP_MOD: return mod(xctxt, context, opPos);
      case OpCodes.OP_QUO: return quo(xctxt, context, opPos);
      case OpCodes.OP_NEG: return neg(xctxt, context, opPos);
      case OpCodes.OP_STRING: return string(xctxt, context, opPos);
      case OpCodes.OP_BOOL: return bool(xctxt, context, opPos);
      case OpCodes.OP_NUMBER: return number(xctxt, context, opPos);
      case OpCodes.OP_UNION: return union(xctxt, context, opPos);
      case OpCodes.OP_LITERAL: return literal(xctxt, context, opPos);
      case OpCodes.OP_VARIABLE: return variable(xctxt, context, opPos);
      case OpCodes.OP_GROUP: return group(xctxt, context, opPos);
      case OpCodes.OP_NUMBERLIT: return numberlit(xctxt, context, opPos);
      case OpCodes.OP_ARGUMENT: return arg(xctxt, context, opPos);
      case OpCodes.OP_EXTFUNCTION: return executeExtension(xctxt, context, 
opPos);
      case OpCodes.OP_FUNCTION: return executeFunction(xctxt, context, opPos);
      case OpCodes.OP_LOCATIONPATH: return locationPath(xctxt, context, opPos);
      case OpCodes.OP_PREDICATE: return null; // should never hit this here.
      case OpCodes.OP_MATCHPATTERN: return matchPattern(xctxt, context, 
opPos+2);
      case OpCodes.OP_LOCATIONPATHPATTERN: return locationPathPattern(xctxt, 
context, opPos);
      default: if(op == OpCodes.OP_LOCATIONPATH_EX) return locationPath(xctxt, 
context, opPos);
               else error(xctxt, context, 
XPATHErrorResources.ER_UNKNOWN_OPCODE, new Object[] 
{Integer.toString(m_opMap[opPos])}); //"ERROR! Unknown op code: 
"+m_opMap[opPos]);
      }
      return null;
    }
    
    /**
     * Warn the user of an problem.
     */
    public void warn(XPathContext xctxt,
                     Node sourceNode, int msg, Object[] args)
      throws org.xml.sax.SAXException
    {
      String fmsg = XSLMessages.createXPATHWarning(msg, args); 
      
      ErrorHandler ehandler = xctxt.getPrimaryReader().getErrorHandler();
  
      if(null != ehandler)
      {
        // TO DO: Need to get stylesheet Locator from here.
        ehandler.warning(new TransformException(fmsg));
      }
    }
  
    /**
     * Tell the user of an assertion error, and probably throw an 
     * exception.
     */
    public void assert(boolean b, String msg)
      throws org.xml.sax.SAXException
    {
      if(!b)
      {
        String fMsg = 
XSLMessages.createXPATHMessage(XPATHErrorResources.ER_INCORRECT_PROGRAMMER_ASSERTION,
 new Object[] {msg}); 
        throw new RuntimeException(fMsg);
      }
    }
  
    /**
     * Tell the user of an error, and probably throw an 
     * exception.
     */
    public void error(XPathContext xctxt, Node sourceNode, int msg, Object[] 
args)
      throws org.xml.sax.SAXException
    {
      String fmsg = XSLMessages.createXPATHMessage(msg, args); 
      
      ErrorHandler ehandler = xctxt.getPrimaryReader().getErrorHandler();
  
      TransformException te = new TransformException(fmsg, 
                                                     xctxt.getSAXLocator());
                                                     
      if(null != ehandler)
        ehandler.fatalError(te);
      else
      {
        System.out.println(te.getMessage()
                           +"; file "+te.getSystemId()
                           +"; line "+te.getLineNumber()
                           +"; column "+te.getColumnNumber());
      }
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * The match score if no match is made.
     */
    public static final double MATCH_SCORE_NONE = Double.NEGATIVE_INFINITY;
  
    /**
     * <meta name="usage" content="advanced"/>
     * The match score if the pattern has the form 
     * of a QName optionally preceded by an @ character.
     */
    public static final double MATCH_SCORE_QNAME = 0.0;
    
    /**
     * <meta name="usage" content="advanced"/>
     * The match score if the pattern pattern has the form NCName:*.
     */
    public static final double MATCH_SCORE_NSWILD = -0.25;
  
    /**
     * <meta name="usage" content="advanced"/>
     * The match score if the pattern consists of just a NodeTest.
     */
    public static final double MATCH_SCORE_NODETEST = -0.5;
  
    /**
     * <meta name="usage" content="advanced"/>
     * The match score if the pattern consists of something 
     * other than just a NodeTest or just a qname.
     */
    public static final double MATCH_SCORE_OTHER = 0.5;
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XPathAPI.java
  
  Index: XPathAPI.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.xml.sax.SAXException;
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import org.w3c.dom.traversal.NodeIterator;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XPathParser;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.utils.PrefixResolverDefault;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.xpath.XObject;
  
  
  /**
   * The methods in this class are convenience methods into the
   * low-level XPath API.  We would like to eventually move these
   * methods into the XPath core, but would like to do some peer
   * review first to make sure we have it right.
   * Please note that these methods execute pure XPaths. They do not
   * implement those parts of XPath extended by XSLT, such as the
   * document() function).  If you want to install XSLT functions, you
   * have to use the low-level API.
   * These functions tend to be a little slow, since a number of objects must be
   * created for each evaluation.  A faster way is to precompile the
   * XPaths using the low-level API, and then just use the XPaths
   * over and over.
   * @see <a href="http://www.w3.org/TR/xpath";>XPath Specification</a>
   */
  public class XPathAPI
  {
    /**
     * Use an XPath string to select a single node. XPath namespace
     * prefixes are resolved from the context node, which may not
     * be what you want (see the next method).
     *
     * @param contextNode The node to start searching from.
     * @param str A valid XPath string.
     * @return The first node found that matches the XPath, or null.
     */
    public static Node selectSingleNode(Node contextNode, String str)
      throws SAXException
    {
      return selectSingleNode(contextNode, str, contextNode);
    }
  
    /**
     * Use an XPath string to select a single node.
     * XPath namespace prefixes are resolved from the namespaceNode.
     *
     * @param contextNode The node to start searching from.
     * @param str A valid XPath string.
     * @param namespaceNode The node from which prefixes in the XPath will be 
resolved to namespaces.
     * @return The first node found that matches the XPath, or null.
     */
    public static Node selectSingleNode(Node contextNode, String str, Node 
namespaceNode)
      throws SAXException
    {
      // Have the XObject return its result as a NodeSet.
      NodeIterator nl = selectNodeList(contextNode, str, namespaceNode);
  
      // Return the first node, or null
      return nl.nextNode();
    }
  
   /**
     * Use an XPath string to select a nodelist.
     * XPath namespace prefixes are resolved from the contextNode.
     *
     * @param contextNode The node to start searching from.
     * @param str A valid XPath string.
     * @return A nodelist, should never be null.
     */
    public static NodeIterator selectNodeList(Node contextNode, String str)
      throws SAXException
    {
      return selectNodeList(contextNode, str, contextNode);
    }
  
   /**
     * Use an XPath string to select a nodelist.
     * XPath namespace prefixes are resolved from the namespaceNode.
     *
     * @param contextNode The node to start searching from.
     * @param str A valid XPath string.
     * @param namespaceNode The node from which prefixes in the XPath will be 
resolved to namespaces.
     * @return A nodelist, should never be null.
     */
    public static NodeIterator selectNodeList(Node contextNode, String str, 
Node namespaceNode)
      throws SAXException
    {
      // Execute the XPath, and have it return the result
      XObject list = eval(contextNode, str, namespaceNode);
  
      // Have the XObject return its result as a NodeSet.
      return list.nodeset();
  
    }
  
   /**
     * Evaluate XPath string to an XObject.  Using this method,
     * XPath namespace prefixes will be resolved from the namespaceNode.
     * @param contextNode The node to start searching from.
     * @param str A valid XPath string.
     * @param namespaceNode The node from which prefixes in the XPath will be 
resolved to namespaces.
     * @return An XObject, which can be used to obtain a string, number, 
nodelist, etc, should never be null.
     * @see org.apache.xalan.xpath.XObject
     * @see org.apache.xalan.xpath.XNull
     * @see org.apache.xalan.xpath.XBoolean
     * @see org.apache.xalan.xpath.XNumber
     * @see org.apache.xalan.xpath.XString
     * @see org.apache.xalan.xpath.XRTreeFrag
     */
    public static XObject eval(Node contextNode, String str)
      throws SAXException
    {
      return eval(contextNode, str, contextNode);
    }
  
   /**
     * Evaluate XPath string to an XObject.
     * XPath namespace prefixes are resolved from the namespaceNode.
     * The implementation of this is a little slow, since it creates
     * a number of objects each time it is called.  This could be optimized
     * to keep the same objects around, but then thread-safety issues would 
arise.
     *
     * @param contextNode The node to start searching from.
     * @param str A valid XPath string.
     * @param namespaceNode The node from which prefixes in the XPath will be 
resolved to namespaces.
     * @return An XObject, which can be used to obtain a string, number, 
nodelist, etc, should never be null.
     * @see org.apache.xalan.xpath.XObject
     * @see org.apache.xalan.xpath.XNull
     * @see org.apache.xalan.xpath.XBoolean
     * @see org.apache.xalan.xpath.XNumber
     * @see org.apache.xalan.xpath.XString
     * @see org.apache.xalan.xpath.XRTreeFrag
     */
    public static XObject eval(Node contextNode, String str, Node namespaceNode)
      throws SAXException
    {
      // Since we don't have a XML Parser involved here, install some default 
support
      // for things like namespaces, etc.
      // (Changed from: XPathContext xpathSupport = new XPathContext();
      //    because XPathContext is weak in a number of areas... perhaps
      //    XPathContext should be done away with.)
      XPathContext xpathSupport = new XPathContext();
  
      // Create an object to resolve namespace prefixes.
      // XPath namespaces are resolved from the input context node's document 
element
      // if it is a root node, or else the current context node (for lack of a 
better
      // resolution space, given the simplicity of this sample code).
      PrefixResolverDefault prefixResolver = new 
PrefixResolverDefault((namespaceNode.getNodeType() == Node.DOCUMENT_NODE)
                                                           ? 
((Document)namespaceNode).getDocumentElement() :
                                                             namespaceNode);
  
      // Create the XPath object.
      XPath xpath = new XPath();
  
      // Create a XPath parser.
      XPathParser parser = new XPathParser();
      parser.initXPath(xpath, str, prefixResolver);
  
      // Execute the XPath, and have it return the result
      return xpath.execute(xpathSupport, contextNode, prefixResolver);
    }
    
  /**
     * Evaluate XPath string to an XObject.
     * XPath namespace prefixes are resolved from the namespaceNode.
     * The implementation of this is a little slow, since it creates
     * a number of objects each time it is called.  This could be optimized
     * to keep the same objects around, but then thread-safety issues would 
arise.
     *
     * @param contextNode The node to start searching from.
     * @param str A valid XPath string.
     * @param namespaceNode The node from which prefixes in the XPath will be 
resolved to namespaces.
     * @return An XObject, which can be used to obtain a string, number, 
nodelist, etc, should never be null.
     * @see org.apache.xalan.xpath.XObject
     * @see org.apache.xalan.xpath.XNull
     * @see org.apache.xalan.xpath.XBoolean
     * @see org.apache.xalan.xpath.XNumber
     * @see org.apache.xalan.xpath.XString
     * @see org.apache.xalan.xpath.XRTreeFrag
     */
    public static XObject eval(Node contextNode, String str, PrefixResolver 
prefixResolver)
      throws SAXException
    {
      // Since we don't have a XML Parser involved here, install some default 
support
      // for things like namespaces, etc.
      // (Changed from: XPathContext xpathSupport = new XPathContext();
      //    because XPathContext is weak in a number of areas... perhaps
      //    XPathContext should be done away with.)
      XPathContext xpathSupport = new XPathContext();
  
      // Create the XPath object.
      XPath xpath = new XPath();
  
      // Create a XPath parser.
      XPathParser parser = new XPathParser();
      parser.initXPath(xpath, str, prefixResolver);
  
      // Execute the XPath, and have it return the result
      return xpath.execute(xpathSupport, contextNode, prefixResolver);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/XPathContext.java
  
  Index: XPathContext.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  // Java lib imports
  import java.io.File;
  import java.io.IOException;
  
  import java.net.URL;
  import java.net.MalformedURLException;
  
  import java.util.Stack;
  
  // Xalan imports
  import org.apache.xalan.utils.IntStack;
  import org.apache.xalan.utils.NSInfo;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.utils.QName;
  
  import org.apache.xalan.res.XSLMessages;
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  // DOM Imports
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.traversal.TreeWalker;
  import org.w3c.dom.Node;
  
  // SAX2 imports
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.SAXException;
  import org.xml.sax.InputSource;
  import org.xml.sax.XMLReader;
  import org.xml.sax.Locator;
  
  // TRaX imports
  import trax.URIResolver;
  import trax.TransformException;
  
  // Temporary!!!
  import org.apache.xalan.extensions.ExtensionsTable;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Default class for the execution context for XPath. Many 
   * of the functions in this class need to be overridden in order to 
   * perform correct execution of the XPath (for instance, variable 
   * execution).
   */
  public class XPathContext
  {
    /**
     * Create an XPathContext instance.
     */
    public XPathContext()
    {
    }
  
    /**
     * Create an XPathContext instance.
     * @param owner Value that can be retreaved via the getOwnerObject() method.
     * @see getOwnerObject
     */
    public XPathContext(Object owner)
    {
      m_owner = owner;
    }
  
    /**
     * Copy attributes from another liaison.
     */
    public void copyFromOtherLiaison(XPathContext from)
      throws SAXException
    {
    }
  
    /**
     * Reset for new run.
     */
    public void reset()
    {
    }
    
    Locator m_saxLocation;
    
    public void setSAXLocator(Locator location)
    {
      m_saxLocation = location;
    }
    
    public Locator getSAXLocator()
    {
      return m_saxLocation;
    }
    
    private Object m_owner;
    
    /**
     * Get the "owner" context of this context, which should be, 
     * in the case of XSLT, the Transformer object.  This is needed 
     * so that XSLT functions can get the Transformer.
     * @return The owner object passed into the constructor, or null.
     */
    public Object getOwnerObject()
    {
      return m_owner;
    }
  
    // ================ extensionsTable ===================
    
    /**
     * The table of Extension Handlers.
     */
    private ExtensionsTable m_extensionsTable = new ExtensionsTable();
    
    /**
     * Get the extensions table object.
     */
    public ExtensionsTable getExtensionsTable()
    {
      return m_extensionsTable;
    }
    
    void setExtensionsTable(ExtensionsTable table)
    {
      m_extensionsTable = table;
    }
    
    // ================ VarStack ===================
  
    /**
     * The stack of Variable stacks.  A VariableStack will be
     * pushed onto this stack for each template invocation.
     */
    private VariableStack m_variableStacks = new VariableStack();
    
    /**
     * Get the variable stack, which is in charge of variables and
     * parameters.
     */
    public VariableStack getVarStack() { return m_variableStacks; }
  
    /**
     * Get the variable stack, which is in charge of variables and
     * parameters.
     */
    public void setVarStack(VariableStack varStack) { m_variableStacks = 
varStack; }
  
    /**
     * Given a name, locate a variable in the current context, and return
     * the Object.
     */
    public XObject getVariable(QName qname)
      throws org.xml.sax.SAXException
    {
      Object obj = getVarStack().getVariable(qname);
      if((null != obj) && !(obj instanceof XObject))
      {
        obj = new XObject(obj);
      }
      return (XObject)obj;
    }
    
    
    // ================ DOMHelper ===================
  
    private DOMHelper m_domHelper;
    
    /**
     * Get the DOMHelper associated with this execution context.
     */
    public DOMHelper getDOMHelper()
    {
      if(null == m_domHelper)
        m_domHelper = new DOMHelper();
      return m_domHelper;
    }
    
    /**
     * Set the DOMHelper associated with this execution context.
     */
    public void setDOMHelper(DOMHelper helper)
    {
      m_domHelper = helper;
    }
                                                  
    // ================ SourceTreeManager ===================
  
    private SourceTreeManager m_sourceTreeManager = new SourceTreeManager();
    
    /**
     * Get the DOMHelper associated with this execution context.
     */
    public SourceTreeManager getSourceTreeManager()
    {
      return m_sourceTreeManager;
    }
    
    /**
     * Set the DOMHelper associated with this execution context.
     */
    public void setSourceTreeManager(SourceTreeManager mgr)
    {
      m_sourceTreeManager = mgr;
    }
    
    // =================================================
  
    private URIResolver m_uriResolver;
    
    /**
     * Get the URIResolver associated with this execution context.
     */
    public URIResolver getURIResolver()
    {
      return m_uriResolver;
    }
    
    /**
     * Set the URIResolver associated with this execution context.
     */
    public void setURIResolver(URIResolver resolver)
    {
      m_uriResolver = resolver;
    }
    
    // =================================================
     
    public XMLReader m_primaryReader;
    
    /**
     * Get primary XMLReader associated with this execution context.
     */
    public XMLReader getPrimaryReader()
    {
      return m_primaryReader;
    }
    
    /**
     * Set primary XMLReader associated with this execution context.
     */
    public void setPrimaryReader(XMLReader reader)
    {
      m_primaryReader = reader;
    }
  
    // =================================================
  
    /**
     * Get a factory to create XPaths.
     */
    public XPathFactory getDefaultXPathFactory()
    {
      return SimpleNodeLocator.factory();
    }
    
    /**
     * <meta name="usage" content="advanced"/>
     * getXLocatorHandler.
     */
    public XLocator createXLocatorHandler()
    {
      return new SimpleNodeLocator();
    }
  
    /**
     * Take a user string (system ID) return the url.
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide 
     * the error condition is severe enough to halt processing.
     */
    public URL getURLFromString(String urlString, String base)
      throws SAXException 
    {
      InputSource inputSource;
      try
      {
        inputSource = getSourceTreeManager().resolveURI(base, urlString);
      }
      catch(IOException ioe)
      {
        inputSource = null; // shutup compiler.
        throw new SAXException(ioe);
      }
      // System.out.println("url: "+url.toString());
      try
      {
        return new URL(inputSource.getSystemId());
      }
      catch(MalformedURLException mue)
      {
        throw new SAXException(mue);
      }
    }
    
    private static XSLMessages m_XSLMessages = new XSLMessages();
  
    /**
     * Tell the user of an assertion error, and probably throw an 
     * exception.
     */
    private void assert(boolean b, String msg)
      throws org.xml.sax.SAXException
    {
      ErrorHandler errorHandler = getPrimaryReader().getErrorHandler();
      if (errorHandler != null) {
        errorHandler.fatalError(new 
TransformException(m_XSLMessages.createMessage(XPATHErrorResources.ER_INCORRECT_PROGRAMMER_ASSERTION,
 new Object[] {msg})));
      }
    }
    
    //==========================================================
    // SECTION: Execution context state tracking
    //==========================================================
             
    /**
     * The current context node list.
     */
    private Stack m_contextNodeLists = new Stack();
          
    /**
     * Get the current context node list.
     */
    public NodeSet getContextNodeList()
    {
      if (m_contextNodeLists.size()>0)
        return (NodeSet)m_contextNodeLists.peek();
      else 
        return null;
    }
   
    /**
     * <meta name="usage" content="internal"/>
     * Set the current context node list.
     * @param A nodelist that represents the current context 
     * list as defined by XPath.
     */
    public void pushContextNodeList(NodeSet nl)
    {
      m_contextNodeLists.push(nl);
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * Pop the current context node list.
     */
    public void popContextNodeList()
    {
      m_contextNodeLists.pop();
    }
  
    /**
     * Tells if FoundIndex should be thrown if index is found.
     * This is an optimization for match patterns.
     */
    private boolean m_throwFoundIndex = false;
    
    /**
     * <meta name="usage" content="internal"/>
     * ThrowFoundIndex tells if FoundIndex should be thrown
     * if index is found.
     * This is an optimization for match patterns, and
     * is used internally by the XPath engine.
     */
    public boolean getThrowFoundIndex()
    {
      return m_throwFoundIndex;
    }
  
    /**
     * <meta name="usage" content="internal"/>
     * ThrowFoundIndex tells if FoundIndex should be thrown
     * if index is found.
     * This is an optimization for match patterns, and
     * is used internally by the XPath engine.
     */
    public void setThrowFoundIndex(boolean b)
    {
      m_throwFoundIndex = b;
    }
    
    /**
     * The current node.
     */
    private Node m_currentNode = null;
    
    /**
     * The current prefixResolver for the execution context (not
     * the source tree context).
     * (Is this really needed?)
     */
    private PrefixResolver m_currentPrefixResolver = null;
    
    /**
     * Get the current context node.
     */
    public Node getCurrentNode()
    {
      return m_currentNode;
    }
  
    /**
     * Set the current context node.
     */
    public void setCurrentNode(Node n)
    {
      m_currentNode = n;
    }
    
    /**
     * Get the current namespace context for the xpath.
     */
    public PrefixResolver getNamespaceContext()
    {
      return m_currentPrefixResolver;
    }
  
    /**
     * Get the current namespace context for the xpath.
     */
    public void setNamespaceContext(PrefixResolver pr)
    {
      m_currentPrefixResolver = pr;
    } 
    
    //==========================================================
    // SECTION: Current TreeWalker contexts (for internal use)
    //==========================================================
  
    /**
     * Stack of AxesIterators.
     */
    private Stack m_axesIteratorStack = new Stack();
    
    /**
     * <meta name="usage" content="internal"/>
     * Push a TreeWalker on the stack.
     */
    public void pushTreeWalkerContext(TreeWalker iter)
    {
      m_axesIteratorStack.push(iter);
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Pop the last pushed axes iterator.
     */
    public void popTreeWalkerContext()
    {
      m_axesIteratorStack.pop();
    }
    
    /**
     * <meta name="usage" content="internal"/>
     * Get the current axes iterator, or return null if none.
     */
    public TreeWalker getTreeWalkerContext()
    {
      return m_axesIteratorStack.isEmpty() 
             ? null : (TreeWalker)m_axesIteratorStack.peek();
                                             
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/XPathDumper.java
  
  Index: XPathDumper.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  
  /**
   * Class for XPath diagnostic functions.
   */
  public class XPathDumper
  {
    /**
     * Dump an XPath string to System.out.
     */
    public static void diagnoseXPathString( String str )
      throws org.xml.sax.SAXException
    {
      XPathParser processor = new XPathParser();
      XPath xpath = new XPath();
      processor.initXPath(xpath, str, null);
      diagnoseXPath(xpath, 0, 0);
    }
  
    static int diagnoseXPathBinaryOperation(String op, XPath xpath, int opPos, 
int indent)
    {
      System.out.println(op+" {");
      opPos+=2;
  
      opPos = diagnoseXPath(xpath, opPos, indent+1);
  
      opPos = diagnoseXPath(xpath, opPos, indent+1);
  
      indent(indent);
      System.out.println("}");
      return opPos;
    }
  
    static int diagnoseXPathUnaryOperation(String op, XPath xpath, int opPos, 
int indent)
    {
      System.out.println(op+" {");
      opPos+=2;
      opPos = diagnoseXPath(xpath, opPos, indent+1);
      indent(indent);
      System.out.println("}");
      return opPos;
    }
  
    private static int diagnoseXPathMultiOperation(String op, int multiOp, 
XPath xpath, int opPos, int indent)
    {
      System.out.println(op+" {");
      opPos+=2;
      while(xpath.m_opMap[opPos] == multiOp)
      {
        indent(indent+1);
        System.out.println("{");
        opPos = diagnoseXPath(xpath, opPos, indent+2);
        indent(indent+1);
        System.out.println("}");
      }
      indent(indent);
      System.out.println("}");
      return opPos;
    }
  
    private static int diagnoseToken(XPath xpath, int opPos)
    {
      System.out.print("{");
      System.out.print(xpath.m_tokenQueue[xpath.m_opMap[opPos]]);
      System.out.print("}");
      return opPos+1;
    }
  
    private static int diagnoseXPathSimpleOperation(String op, XPath xpath, int 
opPos, int indent)
    {
      opPos+=2;
      System.out.print(op);
      opPos = diagnoseToken(xpath, opPos);
      System.out.println("");
      return opPos;
    }
  
    private static int diagnoseXPathLocationStep(String op, XPath xpath, int 
opPos, int indent)
    {
      // int opLen = xpath.m_opMap[opPos+xpath.MAPINDEX_LENGTH];
      int stepLen = xpath.m_opMap[opPos+xpath.MAPINDEX_LENGTH+1];
      opPos+=3;
      System.out.print(op);
      if(stepLen > 3)
      {
        opPos = diagnoseXPath(xpath, opPos, 1);
      }
      System.out.println("");
      return opPos;
    }
  
    static int diagnoseXPath(XPath xpath, int opPos, int indent)
    {
      indent(indent);
      switch(xpath.m_opMap[opPos])
      {
      case OpCodes.OP_XPATH:
        opPos = diagnoseXPathUnaryOperation("OP_XPATH", xpath, opPos, indent);
        break;
      case OpCodes.EMPTY:
        System.out.println("{EMPTY}");
        opPos++;
        break;
      case OpCodes.OP_OR:
        opPos = diagnoseXPathBinaryOperation("OP_OR", xpath, opPos, indent);
        break;
      case OpCodes.OP_AND:
        opPos = diagnoseXPathBinaryOperation("OP_AND", xpath, opPos, indent);
        break;
      case OpCodes.OP_NOTEQUALS:
        opPos = diagnoseXPathBinaryOperation("OP_NOTEQUALS", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_EQUALS:
        opPos = diagnoseXPathBinaryOperation("OP_EQUALS", xpath, opPos, indent);
        break;
      case OpCodes.OP_LTE:
        opPos = diagnoseXPathBinaryOperation("OP_LTE", xpath, opPos, indent);
        break;
      case OpCodes.OP_LT:
        opPos = diagnoseXPathBinaryOperation("OP_LT", xpath, opPos, indent);
        break;
      case OpCodes.OP_GTE:
        opPos = diagnoseXPathBinaryOperation("OP_GTE", xpath, opPos, indent);
        break;
      case OpCodes.OP_GT:
        opPos = diagnoseXPathBinaryOperation("OP_GT", xpath, opPos, indent);
        break;
      case OpCodes.OP_PLUS:
        opPos = diagnoseXPathBinaryOperation("OP_PLUS", xpath, opPos, indent);
        break;
      case OpCodes.OP_MINUS:
        opPos = diagnoseXPathBinaryOperation("OP_MINUS", xpath, opPos, indent);
        break;
      case OpCodes.OP_MULT:
        opPos = diagnoseXPathBinaryOperation("OP_MULT", xpath, opPos, indent);
        break;
      case OpCodes.OP_DIV:
        opPos = diagnoseXPathBinaryOperation("OP_DIV", xpath, opPos, indent);
        break;
      case OpCodes.OP_MOD:
        opPos = diagnoseXPathBinaryOperation("OP_MOD", xpath, opPos, indent);
        break;
      case OpCodes.OP_QUO:
        opPos = diagnoseXPathBinaryOperation("OP_QUO", xpath, opPos, indent);
        break;
      case OpCodes.OP_NEG:
        opPos = diagnoseXPathUnaryOperation("OP_NEG", xpath, opPos, indent);
        break;
      case OpCodes.OP_STRING:
        opPos = diagnoseXPathUnaryOperation("OP_STRING", xpath, opPos, indent);
        break;
      case OpCodes.OP_BOOL:
        opPos = diagnoseXPathUnaryOperation("OP_BOOL", xpath, opPos, indent);
        break;
      case OpCodes.OP_NUMBER:
        opPos = diagnoseXPathUnaryOperation("OP_NUMBER", xpath, opPos, indent);
        break;
      case OpCodes.OP_UNION:
        opPos = diagnoseXPathMultiOperation("OP_UNION", 
OpCodes.OP_LOCATIONPATH, xpath, opPos, indent);
        break;
      case OpCodes.OP_LITERAL:
        opPos = diagnoseXPathSimpleOperation("OP_LITERAL", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_VARIABLE:
        opPos = diagnoseXPathSimpleOperation("OP_VARIABLE", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_GROUP:
        opPos = diagnoseXPathUnaryOperation("OP_GROUP", xpath, opPos, indent);
        break;
      case OpCodes.OP_NUMBERLIT:
        opPos = diagnoseXPathSimpleOperation("OP_NUMBERLIT", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_ARGUMENT:
        opPos = diagnoseXPathUnaryOperation("OP_ARGUMENT", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_EXTFUNCTION:
        {
          System.out.println("OP_EXTFUNCTION {");
          int endExtFunc = opPos+xpath.m_opMap[opPos+1]-1;
          opPos+=2;
          indent(indent+1);
          opPos = diagnoseToken(xpath, opPos);
          System.out.print(":");
          opPos = diagnoseToken(xpath, opPos);
          System.out.println("");
          while(opPos < endExtFunc)
          {
            indent(indent+1);
            System.out.println("{");
            opPos = diagnoseXPath(xpath, opPos, indent+2);
            indent(indent+1);
            System.out.println("}");
          }
          indent(indent);
          System.out.println("}");
          if(xpath.m_opMap[opPos] != OpCodes.ENDOP)
          {
            
System.out.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH,
 null)); //"ERROR! Could not find ENDOP after OP_LOCATIONPATH");
          }
          opPos++;
        }
        break;
      case OpCodes.OP_FUNCTION:
        {
          System.out.println("OP_FUNCTION {");
          int endFunc = opPos+xpath.m_opMap[opPos+1]-1;
          opPos+=2;
          indent(indent+1);
          int funcID = xpath.m_opMap[opPos];
          switch(funcID)
          {
          case FunctionTable.FUNC_LAST: System.out.print("FUNC_LAST"); break;
          case FunctionTable.FUNC_POSITION: System.out.print("FUNC_POSITION"); 
break;
          case FunctionTable.FUNC_COUNT: System.out.print("FUNC_COUNT"); break;
          case FunctionTable.FUNC_ID: System.out.print("FUNC_ID"); break;
          case FunctionTable.FUNC_KEY: System.out.print("FUNC_KEY"); break;
          // case FunctionTable.FUNC_DOC: System.out.print("FUNC_DOC"); break;
          case FunctionTable.FUNC_LOCAL_PART: 
System.out.print("FUNC_LOCAL_PART"); break;
          case FunctionTable.FUNC_NAMESPACE: 
System.out.print("FUNC_NAMESPACE"); break;
          case FunctionTable.FUNC_QNAME: System.out.print("FUNC_QNAME"); break;
          case FunctionTable.FUNC_GENERATE_ID: 
System.out.print("FUNC_GENERATE_ID"); break;
          case FunctionTable.FUNC_NOT: System.out.print("FUNC_NOT"); break;
          case FunctionTable.FUNC_TRUE: System.out.print("FUNC_TRUE"); break;
          case FunctionTable.FUNC_FALSE: System.out.print("FUNC_FALSE"); break;
          case FunctionTable.FUNC_BOOLEAN: System.out.print("FUNC_BOOLEAN"); 
break;
          case FunctionTable.FUNC_LANG: System.out.print("FUNC_LANG"); break;
          case FunctionTable.FUNC_NUMBER: System.out.print("FUNC_NUMBER"); 
break;
          case FunctionTable.FUNC_FLOOR: System.out.print("FUNC_FLOOR"); break;
          case FunctionTable.FUNC_CEILING: System.out.print("FUNC_CEILING"); 
break;
          case FunctionTable.FUNC_ROUND: System.out.print("FUNC_ROUND"); break;
          case FunctionTable.FUNC_SUM: System.out.print("FUNC_SUM"); break;
          case FunctionTable.FUNC_STRING: System.out.print("FUNC_STRING"); 
break;
          case FunctionTable.FUNC_STARTS_WITH: 
System.out.print("FUNC_STARTS_WITH"); break;
          case FunctionTable.FUNC_CONTAINS: System.out.print("FUNC_CONTAINS"); 
break;
          case FunctionTable.FUNC_SUBSTRING_BEFORE: 
System.out.print("FUNC_SUBSTRING_BEFORE"); break;
          case FunctionTable.FUNC_SUBSTRING_AFTER: 
System.out.print("FUNC_SUBSTRING_AFTER"); break;
          case FunctionTable.FUNC_NORMALIZE_SPACE: 
System.out.print("FUNC_NORMALIZE_SPACE"); break;
          case FunctionTable.FUNC_TRANSLATE: 
System.out.print("FUNC_TRANSLATE"); break;
          case FunctionTable.FUNC_CONCAT: System.out.print("FUNC_CONCAT"); 
break;
          //case FunctionTable.FUNC_FORMAT_NUMBER: 
System.out.print("FUNC_FORMAT_NUMBER"); break;
          case FunctionTable.FUNC_SYSTEM_PROPERTY: 
System.out.print("FUNC_SYSTEM_PROPERTY"); break;
          case FunctionTable.FUNC_EXT_FUNCTION_AVAILABLE: 
System.out.print("FUNC_EXT_FUNCTION_AVAILABLE"); break;
          case FunctionTable.FUNC_EXT_ELEM_AVAILABLE: 
System.out.print("FUNC_EXT_ELEM_AVAILABLE"); break;
          case FunctionTable.FUNC_SUBSTRING: 
System.out.print("FUNC_SUBSTRING"); break;
          case FunctionTable.FUNC_STRING_LENGTH: 
System.out.print("FUNC_STRING_LENGTH"); break;
          case FunctionTable.FUNC_DOCLOCATION: 
System.out.print("FUNC_DOCLOCATION"); break;
          }
          opPos++;
          System.out.println("");
          while(opPos < endFunc)
          {
            indent(indent+1);
            System.out.println("{");
            opPos = diagnoseXPath(xpath, opPos, indent+2);
            indent(indent+1);
            System.out.println("}");
          }
          indent(indent);
          System.out.println("}");
          if(xpath.m_opMap[opPos] != OpCodes.ENDOP)
          {
            
System.out.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH,
 null)); //"ERROR! Could not find ENDOP after OP_LOCATIONPATH");
          }
          opPos++;
        }
        break;
      case OpCodes.OP_LOCATIONPATH:
      case OpCodes.OP_LOCATIONPATH_EX:
        System.out.println("OP_LOCATIONPATH"+" {");
        int endPath = opPos+xpath.m_opMap[opPos+1]-1;
        opPos+=2;
        while(opPos < endPath)
        {
          opPos = diagnoseXPath(xpath, opPos, indent+1);
        }
        indent(indent);
        System.out.println("}");
        if(xpath.m_opMap[opPos] != OpCodes.ENDOP)
        {
          
System.out.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH,
 null)); //"ERROR! Could not find ENDOP after OP_LOCATIONPATH");
        }
        opPos++;
        break;
      case OpCodes.OP_PREDICATE:
        opPos = diagnoseXPathUnaryOperation("OP_PREDICATE", xpath, opPos, 
indent);
        if(xpath.m_opMap[opPos] != OpCodes.ENDOP)
        {
          System.out.println("ERROR! Could not find ENDOP after 
OP_LOCATIONPATH");
        }
        opPos++;
        break;
      case OpCodes.FROM_ANCESTORS:
        opPos = diagnoseXPathLocationStep("FROM_ANCESTORS", xpath, opPos, 1);
        break;
      case OpCodes.FROM_ANCESTORS_OR_SELF:
        opPos = diagnoseXPathLocationStep("FROM_ANCESTORS_OR_SELF", xpath, 
opPos, 1);
        break;
      case OpCodes.FROM_ATTRIBUTES:
        opPos = diagnoseXPathLocationStep("FROM_ATTRIBUTES", xpath, opPos, 1);
        break;
      case OpCodes.FROM_CHILDREN:
        opPos = diagnoseXPathLocationStep("FROM_CHILDREN", xpath, opPos, 1);
        break;
      case OpCodes.FROM_DESCENDANTS:
        opPos = diagnoseXPathLocationStep("FROM_DESCENDANTS", xpath, opPos, 1);
        break;
      case OpCodes.FROM_DESCENDANTS_OR_SELF:
        opPos = diagnoseXPathLocationStep("FROM_DESCENDANTS_OR_SELF", xpath, 
opPos, 1);
        break;
      case OpCodes.FROM_FOLLOWING:
        opPos = diagnoseXPathLocationStep("FROM_FOLLOWING", xpath, opPos, 
indent);
        break;
      case OpCodes.FROM_FOLLOWING_SIBLINGS:
        opPos = diagnoseXPathLocationStep("FROM_FOLLOWING_SIBLINGS", xpath, 
opPos, indent);
        break;
      case OpCodes.FROM_PARENT:
        opPos = diagnoseXPathLocationStep("FROM_PARENT", xpath, opPos, indent);
        break;
      case OpCodes.FROM_PRECEDING:
        opPos = diagnoseXPathLocationStep("FROM_PRECEDING", xpath, opPos, 
indent);
        break;
      case OpCodes.FROM_PRECEDING_SIBLINGS:
        opPos = diagnoseXPathLocationStep("FROM_PRECEDING_SIBLINGS", xpath, 
opPos, indent);
        break;
      case OpCodes.FROM_SELF:
        opPos = diagnoseXPathLocationStep("FROM_SELF", xpath, opPos, indent);
        break;
      case OpCodes.FROM_NAMESPACE:
        opPos = diagnoseXPathLocationStep("FROM_NAMESPACE", xpath, opPos, 
indent);
        break;
      // case OpCodes.FROM_ATTRIBUTE:
      //   opPos = diagnoseXPathLocationStep("FROM_ATTRIBUTE", xpath, opPos, 
indent);
      //  break;
      // case OpCodes.FROM_DOC:
      //  opPos = diagnoseXPathLocationStep("FROM_DOC", xpath, opPos, indent);
      //  break;
      // case OpCodes.FROM_DOCREF:
      //  opPos = diagnoseXPathLocationStep("FROM_DOCREF", xpath, opPos, 
indent);
      //  break;
      // case OpCodes.FROM_ID:
      //  opPos = diagnoseXPathLocationStep("FROM_ID", xpath, opPos, indent);
      //  break;
      // case OpCodes.FROM_IDREF:
      //  opPos = diagnoseXPathLocationStep("FROM_IDREF", xpath, opPos, indent);
      //  break;
      case OpCodes.FROM_ROOT:
        opPos = diagnoseXPathLocationStep("FROM_ROOT", xpath, opPos, indent);
        break;
      case OpCodes.NODETYPE_COMMENT:
        System.out.println("{NODETYPE_COMMENT}");
        opPos++;
        break;
      case OpCodes.NODETYPE_TEXT:
        System.out.println("{NODETYPE_TEXT}");
        opPos++;
        break;
      case OpCodes.NODETYPE_PI:
        int piLen = xpath.m_opMap[opPos-1];
        System.out.println("{NODETYPE_PI ");
        opPos++;
        if(piLen > 3)
        {
          opPos = diagnoseToken(xpath, opPos);
        }
        break;
      case OpCodes.NODETYPE_NODE:
        System.out.println("{NODETYPE_NODE}");
        opPos++;
        break;
      case OpCodes.NODETYPE_ROOT:
        System.out.println("{NODETYPE_ROOT}");
        opPos++;
        break;
      case OpCodes.NODETYPE_ANYELEMENT:
        System.out.println("{NODETYPE_ANYELEMENT}");
        opPos++;
        break;
      case OpCodes.NODENAME:
        System.out.print("{NODENAME ");
        opPos++;
        if(xpath.m_opMap[opPos] < 0)
        {
          System.out.print("{EMPTY}");
          opPos++;
        }
        else
        {
          opPos = diagnoseToken(xpath, opPos);
        }
        System.out.print(":");
        opPos = diagnoseToken(xpath, opPos);
        break;
      default:
          
System.out.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_UNKNOWN_OPCODE,
 new Object[] {Integer.toString(xpath.m_opMap[opPos])})); //"ERROR! Unknown op 
code: "+xpath.m_opMap[opPos]);
      }
      return opPos;
    }
  
    static void indent(int amount)
    {
      int n = amount * 3;
      for(int i = 0;  i < n; i ++)
      {
        System.out.print(" ");
      }
    }
  
    private static String m_opLabel     = "[";
    private static String m_lenLabel    = "[";
    private static String m_arglenLabel = "[";
    private static String m_noLabel     = "[";
    private static String m_nTestLabel  = "[";
    private static String m_open = "[";
    private static String m_close = "]";
  
    /**
     * Dump an XPath string to System.out.
     */
    public static void diagnoseXPathString2( String str )
      throws org.xml.sax.SAXException
    {
      XPathParser processor = new XPathParser();
      XPath xpath = new XPath();
      processor.initXPath(xpath, str, null);
      diagnoseXPath2(xpath, 0, 0);
    }
  
    /**
     * Dump an XPath string to System.out.
     */
    public static void diagnoseXPathString3( String str )
      throws org.xml.sax.SAXException
    {
      XPathParser processor = new XPathParser();
      XPath xpath = new XPath();
      processor.initXPath(xpath, str, null);
      int len = xpath.m_opMap[xpath.MAPINDEX_LENGTH];
      for(int i = 0; i < len; i++)
      {
        System.out.println("["+xpath.m_opMap[i]+"]");
      }
    }
  
    private static void diagnoseNodeTest2(int opPos, String op)
    {
      System.out.print(m_nTestLabel+op+m_close);
    }
  
    private static void diagnoseOpNoLable2(int opPos, String op)
    {
      System.out.println(m_noLabel+op+m_close);
    }
  
    private static void diagnoseOpOnly2(int opPos, String op)
    {
      System.out.println(m_opLabel+op+m_close);
    }
  
    private static void diagnoseOp2(String op, XPath xpath, int opPos)
    {
      System.out.print(m_opLabel+op+m_close);
      int opLen = xpath.m_opMap[opPos+xpath.MAPINDEX_LENGTH];
      System.out.println(m_open+opLen+m_close);
    }
  
    private static void diagnoseOp2SameLine(String op, XPath xpath, int opPos)
    {
      System.out.print(m_opLabel+op+m_close);
      int opLen = xpath.m_opMap[opPos+xpath.MAPINDEX_LENGTH];
      System.out.print(m_open+opLen+m_close);
    }
  
    private static int diagnoseXPathBinaryOperation2(String op, XPath xpath, 
int opPos, int indent)
    {
      diagnoseOp2(op, xpath, opPos);
      opPos+=2;
  
      opPos = diagnoseXPath2(xpath, opPos, indent+1);
  
      opPos = diagnoseXPath2(xpath, opPos, indent+1);
  
      return opPos;
    }
  
    private static int diagnoseXPathUnaryOperation2(String op, XPath xpath, int 
opPos, int indent)
    {
      diagnoseOp2(op, xpath, opPos);
      opPos+=2;
      opPos = diagnoseXPath2(xpath, opPos, indent+1);
      return opPos;
    }
  
    private static int diagnoseXPathMultiOperation2(String op, int multiOp, 
XPath xpath, int opPos, int indent)
    {
      diagnoseOp2(op, xpath, opPos);
      opPos+=2;
      while(xpath.m_opMap[opPos] == multiOp)
      {
        opPos = diagnoseXPath2(xpath, opPos, indent+2);
      }
      return opPos;
    }
  
    private static int diagnoseToken2(XPath xpath, int opPos)
    {
      int tokenPos = xpath.m_opMap[opPos];
      String token = (tokenPos >= 0) ? xpath.m_tokenQueue[tokenPos].toString() :
                                       (tokenPos == OpCodes.ELEMWILDCARD) ?
                                       "*" : (tokenPos == OpCodes.EMPTY) ?
                                             "EMPTY" : "UNKNOWN";
      System.out.println(m_noLabel+token+m_close);
      return opPos+1;
    }
  
    private static int diagnoseToken2SameLine(XPath xpath, int opPos)
    {
      
System.out.print(m_noLabel+xpath.m_tokenQueue[xpath.m_opMap[opPos]]+m_close);
      return opPos+1;
    }
  
    private static int diagnoseXPathSimpleOperation2(String op, XPath xpath, 
int opPos, int indent)
    {
      diagnoseOp2SameLine(op, xpath, opPos);
      opPos+=2;
      opPos = diagnoseToken2(xpath, opPos);
      return opPos;
    }
  
    private static int diagnoseXPathLocationStep2(String op, XPath xpath, int 
opPos, int indent)
    {
      int opLen = xpath.m_opMap[opPos+xpath.MAPINDEX_LENGTH];
      int stepLen = xpath.m_opMap[opPos+xpath.MAPINDEX_LENGTH+1];
      System.out.print(m_opLabel+op+m_close);
      System.out.print(m_open+opLen+m_close);
      System.out.print(m_open+stepLen+m_close);
      opPos+=3;
      if(stepLen > 3)
      {
        opPos = diagnoseXPath2(xpath, opPos, 0);
      }
      return opPos;
    }
  
    private static int diagnoseXPath2(XPath xpath, int opPos, int indent)
    {
      indent(indent);
      switch(xpath.m_opMap[opPos])
      {
      case OpCodes.OP_XPATH:
        opPos = diagnoseXPathUnaryOperation2("OP_XPATH", xpath, opPos, indent);
        break;
      case OpCodes.EMPTY:
        diagnoseOpOnly2(opPos, "EMPTY");
        opPos++;
        break;
      case OpCodes.OP_OR:
        opPos = diagnoseXPathBinaryOperation2("OP_OR", xpath, opPos, indent);
        break;
      case OpCodes.OP_AND:
        opPos = diagnoseXPathBinaryOperation2("OP_AND", xpath, opPos, indent);
        break;
      case OpCodes.OP_NOTEQUALS:
        opPos = diagnoseXPathBinaryOperation2("OP_NOTEQUALS", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_EQUALS:
        opPos = diagnoseXPathBinaryOperation2("OP_EQUALS", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_LTE:
        opPos = diagnoseXPathBinaryOperation2("OP_LTE", xpath, opPos, indent);
        break;
      case OpCodes.OP_LT:
        opPos = diagnoseXPathBinaryOperation2("OP_LT", xpath, opPos, indent);
        break;
      case OpCodes.OP_GTE:
        opPos = diagnoseXPathBinaryOperation2("OP_GTE", xpath, opPos, indent);
        break;
      case OpCodes.OP_GT:
        opPos = diagnoseXPathBinaryOperation2("OP_GT", xpath, opPos, indent);
        break;
      case OpCodes.OP_PLUS:
        opPos = diagnoseXPathBinaryOperation2("OP_PLUS", xpath, opPos, indent);
        break;
      case OpCodes.OP_MINUS:
        opPos = diagnoseXPathBinaryOperation2("OP_MINUS", xpath, opPos, indent);
        break;
      case OpCodes.OP_MULT:
        opPos = diagnoseXPathBinaryOperation2("OP_MULT", xpath, opPos, indent);
        break;
      case OpCodes.OP_DIV:
        opPos = diagnoseXPathBinaryOperation2("OP_DIV", xpath, opPos, indent);
        break;
      case OpCodes.OP_MOD:
        opPos = diagnoseXPathBinaryOperation2("OP_MOD", xpath, opPos, indent);
        break;
      case OpCodes.OP_QUO:
        opPos = diagnoseXPathBinaryOperation2("OP_QUO", xpath, opPos, indent);
        break;
      case OpCodes.OP_NEG:
        opPos = diagnoseXPathUnaryOperation2("OP_NEG", xpath, opPos, indent);
        break;
      case OpCodes.OP_STRING:
        opPos = diagnoseXPathUnaryOperation2("OP_STRING", xpath, opPos, indent);
        break;
      case OpCodes.OP_BOOL:
        opPos = diagnoseXPathUnaryOperation2("OP_BOOL", xpath, opPos, indent);
        break;
      case OpCodes.OP_NUMBER:
        opPos = diagnoseXPathUnaryOperation2("OP_NUMBER", xpath, opPos, indent);
        break;
      case OpCodes.OP_UNION:
        opPos = diagnoseXPathMultiOperation2("OP_UNION", 
OpCodes.OP_LOCATIONPATH, xpath, opPos, indent);
        break;
      case OpCodes.OP_LITERAL:
        opPos = diagnoseXPathSimpleOperation2("OP_LITERAL", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_VARIABLE:
        opPos = diagnoseXPathSimpleOperation2("OP_VARIABLE", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_GROUP:
        opPos = diagnoseXPathUnaryOperation2("OP_GROUP", xpath, opPos, indent);
        break;
      case OpCodes.OP_NUMBERLIT:
        opPos = diagnoseXPathSimpleOperation2("OP_NUMBERLIT", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_ARGUMENT:
        opPos = diagnoseXPathUnaryOperation2("OP_ARGUMENT", xpath, opPos, 
indent);
        break;
      case OpCodes.OP_EXTFUNCTION:
        {
          diagnoseOp2SameLine("OP_EXTFUNCTION", xpath, opPos);
          int endExtFunc = opPos+xpath.m_opMap[opPos+1]-1;
          opPos+=2;
          opPos = diagnoseToken2SameLine(xpath, opPos);
          opPos = diagnoseToken2(xpath, opPos);
          while(opPos < endExtFunc)
          {
            opPos = diagnoseXPath2(xpath, opPos, indent+2);
          }
          if(xpath.m_opMap[opPos] != OpCodes.ENDOP)
          {
            System.out.println("ERROR! Could not find ENDOP after 
OP_LOCATIONPATH");
          }
          indent(indent+1);
          diagnoseOpOnly2(opPos, "ENDOP");
          opPos++;
        }
        break;
      case OpCodes.OP_FUNCTION:
        {
          diagnoseOp2SameLine("OP_FUNCTION", xpath, opPos);
          int endFunc = opPos+xpath.m_opMap[opPos+1]-1;
          opPos+=2;
          int funcID = xpath.m_opMap[opPos];
          switch(funcID)
          {
          case FunctionTable.FUNC_LAST: diagnoseOpNoLable2(opPos, "FUNC_LAST"); 
break;
          case FunctionTable.FUNC_POSITION: diagnoseOpNoLable2(opPos, 
"FUNC_POSITION"); break;
          case FunctionTable.FUNC_COUNT: diagnoseOpNoLable2(opPos, 
"FUNC_COUNT"); break;
          case FunctionTable.FUNC_ID: diagnoseOpNoLable2(opPos, "FUNC_ID"); 
break;
          case FunctionTable.FUNC_KEY: diagnoseOpNoLable2(opPos, "FUNC_KEY"); 
break;
          // case FunctionTable.FUNC_DOC: diagnoseOpNoLable2(opPos, 
"FUNC_DOC"); break;
          case FunctionTable.FUNC_LOCAL_PART: diagnoseOpNoLable2(opPos, 
"FUNC_LOCAL_PART"); break;
          case FunctionTable.FUNC_NAMESPACE: diagnoseOpNoLable2(opPos, 
"FUNC_NAMESPACE"); break;
          case FunctionTable.FUNC_QNAME: diagnoseOpNoLable2(opPos, 
"FUNC_QNAME"); break;
          case FunctionTable.FUNC_GENERATE_ID: diagnoseOpNoLable2(opPos, 
"FUNC_GENERATE_ID"); break;
          case FunctionTable.FUNC_NOT: diagnoseOpNoLable2(opPos, "FUNC_NOT"); 
break;
          case FunctionTable.FUNC_TRUE: diagnoseOpNoLable2(opPos, "FUNC_TRUE"); 
break;
          case FunctionTable.FUNC_FALSE: diagnoseOpNoLable2(opPos, 
"FUNC_FALSE"); break;
          case FunctionTable.FUNC_BOOLEAN: diagnoseOpNoLable2(opPos, 
"FUNC_BOOLEAN"); break;
          case FunctionTable.FUNC_LANG: diagnoseOpNoLable2(opPos, "FUNC_LANG"); 
break;
          case FunctionTable.FUNC_NUMBER: diagnoseOpNoLable2(opPos, 
"FUNC_NUMBER"); break;
          case FunctionTable.FUNC_FLOOR: diagnoseOpNoLable2(opPos, 
"FUNC_FLOOR"); break;
          case FunctionTable.FUNC_CEILING: diagnoseOpNoLable2(opPos, 
"FUNC_CEILING"); break;
          case FunctionTable.FUNC_ROUND: diagnoseOpNoLable2(opPos, 
"FUNC_ROUND"); break;
          case FunctionTable.FUNC_SUM: diagnoseOpNoLable2(opPos, "FUNC_SUM"); 
break;
          case FunctionTable.FUNC_STRING: diagnoseOpNoLable2(opPos, 
"FUNC_STRING"); break;
          case FunctionTable.FUNC_STARTS_WITH: diagnoseOpNoLable2(opPos, 
"FUNC_STARTS_WITH"); break;
          case FunctionTable.FUNC_CONTAINS: diagnoseOpNoLable2(opPos, 
"FUNC_CONTAINS"); break;
          case FunctionTable.FUNC_SUBSTRING_BEFORE: diagnoseOpNoLable2(opPos, 
"FUNC_SUBSTRING_BEFORE"); break;
          case FunctionTable.FUNC_SUBSTRING_AFTER: diagnoseOpNoLable2(opPos, 
"FUNC_SUBSTRING_AFTER"); break;
          case FunctionTable.FUNC_NORMALIZE_SPACE: diagnoseOpNoLable2(opPos, 
"FUNC_NORMALIZE_SPACE"); break;
          case FunctionTable.FUNC_TRANSLATE: diagnoseOpNoLable2(opPos, 
"FUNC_TRANSLATE"); break;
          case FunctionTable.FUNC_CONCAT: diagnoseOpNoLable2(opPos, 
"FUNC_CONCAT"); break;
          //case FunctionTable.FUNC_FORMAT_NUMBER: diagnoseOpNoLable2(opPos, 
"FUNC_FORMAT_NUMBER"); break;
          case FunctionTable.FUNC_SYSTEM_PROPERTY: diagnoseOpNoLable2(opPos, 
"FUNC_SYSTEM_PROPERTY"); break;
          case FunctionTable.FUNC_EXT_FUNCTION_AVAILABLE: 
diagnoseOpNoLable2(opPos, "FUNC_EXT_FUNCTION_AVAILABLE"); break;
          case FunctionTable.FUNC_EXT_ELEM_AVAILABLE: diagnoseOpNoLable2(opPos, 
"FUNC_EXT_ELEM_AVAILABLE"); break;
          case FunctionTable.FUNC_SUBSTRING: diagnoseOpNoLable2(opPos, 
"FUNC_SUBSTRING"); break;
          case FunctionTable.FUNC_STRING_LENGTH: diagnoseOpNoLable2(opPos, 
"FUNC_STRING_LENGTH"); break;
          case FunctionTable.FUNC_DOCLOCATION: diagnoseOpNoLable2(opPos, 
"FUNC_DOCLOCATION"); break;
          }
          opPos++;
          while(opPos < endFunc)
          {
            // indent(indent+1);
            opPos = diagnoseXPath2(xpath, opPos, indent+2);
          }
          indent(indent);
          if(xpath.m_opMap[opPos] != OpCodes.ENDOP)
          {
            
System.out.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH,
 null)); //"ERROR! Could not find ENDOP after OP_LOCATIONPATH");
          }
          indent(indent+1);
          diagnoseOpOnly2(opPos, "ENDOP");
          opPos++;
        }
        break;
      case OpCodes.OP_LOCATIONPATH_EX:
      case OpCodes.OP_LOCATIONPATH:
        diagnoseOp2("OP_LOCATIONPATH", xpath, opPos);
        int endPath = opPos+xpath.m_opMap[opPos+1]-1;
        opPos+=2;
        while(opPos < endPath)
        {
          opPos = diagnoseXPath2(xpath, opPos, indent+1);
        }
        if(xpath.m_opMap[opPos] != OpCodes.ENDOP)
        {
          
System.out.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH,
 null)); //"ERROR! Could not find ENDOP after OP_LOCATIONPATH");
        }
        indent(indent+1);
        diagnoseOpOnly2(opPos, "ENDOP");
        opPos++;
        break;
      case OpCodes.OP_PREDICATE:
        indent(1);
        opPos = diagnoseXPathUnaryOperation2("OP_PREDICATE", xpath, opPos, 
indent+1);
        if(xpath.m_opMap[opPos] != OpCodes.ENDOP)
        {
          System.out.println("ERROR! Could not find ENDOP after 
OP_LOCATIONPATH");
        }
        indent(indent+2);
        diagnoseOpOnly2(opPos, "ENDOP");
        opPos++;
        break;
      case OpCodes.FROM_ANCESTORS:
        opPos = diagnoseXPathLocationStep2("FROM_ANCESTORS", xpath, opPos, 1);
        break;
      case OpCodes.FROM_ANCESTORS_OR_SELF:
        opPos = diagnoseXPathLocationStep2("FROM_ANCESTORS_OR_SELF", xpath, 
opPos, 1);
        break;
      case OpCodes.FROM_ATTRIBUTES:
        opPos = diagnoseXPathLocationStep2("FROM_ATTRIBUTES", xpath, opPos, 1);
        break;
      case OpCodes.FROM_CHILDREN:
        opPos = diagnoseXPathLocationStep2("FROM_CHILDREN", xpath, opPos, 1);
        break;
      case OpCodes.FROM_DESCENDANTS:
        opPos = diagnoseXPathLocationStep2("FROM_DESCENDANTS", xpath, opPos, 1);
        break;
      case OpCodes.FROM_DESCENDANTS_OR_SELF:
        opPos = diagnoseXPathLocationStep2("FROM_DESCENDANTS_OR_SELF", xpath, 
opPos, 1);
        break;
      case OpCodes.FROM_FOLLOWING:
        opPos = diagnoseXPathLocationStep2("FROM_FOLLOWING", xpath, opPos, 
indent);
        break;
      case OpCodes.FROM_FOLLOWING_SIBLINGS:
        opPos = diagnoseXPathLocationStep2("FROM_FOLLOWING_SIBLINGS", xpath, 
opPos, indent);
        break;
      case OpCodes.FROM_PARENT:
        opPos = diagnoseXPathLocationStep2("FROM_PARENT", xpath, opPos, indent);
        break;
      case OpCodes.FROM_PRECEDING:
        opPos = diagnoseXPathLocationStep2("FROM_PRECEDING", xpath, opPos, 
indent);
        break;
      case OpCodes.FROM_PRECEDING_SIBLINGS:
        opPos = diagnoseXPathLocationStep2("FROM_PRECEDING_SIBLINGS", xpath, 
opPos, indent);
        break;
      case OpCodes.FROM_SELF:
        opPos = diagnoseXPathLocationStep2("FROM_SELF", xpath, opPos, indent);
        break;
      case OpCodes.FROM_NAMESPACE:
        opPos = diagnoseXPathLocationStep2("FROM_NAMESPACE", xpath, opPos, 
indent);
        break;
      // case OpCodes.FROM_ATTRIBUTE:
      //   opPos = diagnoseXPathLocationStep("FROM_ATTRIBUTE", xpath, opPos, 
indent);
      //  break;
      // case OpCodes.FROM_DOC:
      //  opPos = diagnoseXPathLocationStep("FROM_DOC", xpath, opPos, indent);
      //  break;
      // case OpCodes.FROM_DOCREF:
      //  opPos = diagnoseXPathLocationStep("FROM_DOCREF", xpath, opPos, 
indent);
      //  break;
      // case OpCodes.FROM_ID:
      //  opPos = diagnoseXPathLocationStep("FROM_ID", xpath, opPos, indent);
      //  break;
      // case OpCodes.FROM_IDREF:
      //  opPos = diagnoseXPathLocationStep("FROM_IDREF", xpath, opPos, indent);
      //  break;
      case OpCodes.FROM_ROOT:
        opPos = diagnoseXPathLocationStep2("FROM_ROOT", xpath, opPos, indent);
        // opPos++;
        break;
      case OpCodes.NODETYPE_COMMENT:
        diagnoseNodeTest2(opPos, "NODETYPE_COMMENT");
        System.out.println();
        opPos++;
        break;
      case OpCodes.NODETYPE_TEXT:
        diagnoseNodeTest2(opPos, "NODETYPE_TEXT");
        System.out.println();
        opPos++;
        break;
      case OpCodes.NODETYPE_PI:
        int piLen = xpath.m_opMap[opPos-1];
        diagnoseNodeTest2(opPos, "NODETYPE_PI");
        opPos++;
        if(piLen > 3)
        {
          opPos = diagnoseToken(xpath, opPos);
        }
        break;
      case OpCodes.NODETYPE_NODE:
        diagnoseNodeTest2(opPos, "NODETYPE_NODE");
        System.out.println();
        opPos++;
        break;
      case OpCodes.NODETYPE_ROOT:
        diagnoseNodeTest2(opPos, "NODETYPE_ROOT");
        System.out.println();
        opPos++;
        break;
      case OpCodes.NODETYPE_ANYELEMENT:
        diagnoseNodeTest2(opPos, "NODETYPE_ANYELEMENT");
        System.out.println();
        opPos++;
        break;
      case OpCodes.NODENAME:
        diagnoseNodeTest2(opPos, "NODENAME");
        opPos++;
        if(xpath.m_opMap[opPos] < 0)
        {
          System.out.print(m_noLabel+"EMPTY"+m_close);
          opPos++;
        }
        else
        {
          opPos = diagnoseToken2(xpath, opPos);
        }
        opPos = diagnoseToken2(xpath, opPos);
        break;
      default:
        
System.out.println(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_UNKNOWN_OPCODE,
 new Object[] {Integer.toString(xpath.m_opMap[opPos])})); //"ERROR! Unknown op 
code: "+xpath.m_opMap[opPos]);
      }
      return opPos;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/XPathException.java
  
  Index: XPathException.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  import org.w3c.dom.Node;
  import org.xml.sax.SAXException;
  
  /**
   * <meta name="usage" content="general"/>
   * This class implements an exception object that all 
   * XPath classes will throw in case of an error.  This class
   * extends SAXException, and may hold other exceptions. In the 
   * case of nested exceptions, printStackTrace will dump 
   * all the traces of the nested exceptions, not just the trace 
   * of this object.
   */
  public class XPathException extends SAXException
  {
    Object m_styleNode = null;
    
    /**
     * Get the stylesheet node from where this error originated.
     * @return The stylesheet node from where this error originated, or null.
     */
    public Object getStylesheetNode()
    {
      return m_styleNode;
    }
    
    protected Exception m_exception;
    
    /**
     * Create an XPathException object that holds 
     * an error message.
     * @param message The error message.
     */
    public XPathException(String message) 
    {
      super(message);
    }
    
    /**
     * Create an XPathException object that holds 
     * an error message and the stylesheet node that
     * the error originated from.
     * @param message The error message.
     * @param styleNode The stylesheet node that the error originated from.
     */
    public XPathException(String message, Object styleNode) 
    {
      super(message);
      m_styleNode = styleNode;
    }
  
    /**
     * Create an XPathException object that holds 
     * an error message, the stylesheet node that
     * the error originated from, and another exception 
     * that caused this exception.
     * @param message The error message.
     * @param styleNode The stylesheet node that the error originated from.
     * @param e The exception that caused this exception.
     */
    public XPathException (String message, Node styleNode, Exception e)
    {
      super(message);
      m_styleNode = styleNode;
      this.m_exception = e;
    }
  
    /**
     * Create an XPathException object that holds 
     * an error message, and another exception 
     * that caused this exception.
     * @param message The error message.
     * @param e The exception that caused this exception.
     */
    public XPathException (String message, Exception e)
    {
      super(message);
      this.m_exception = e;
    }
    
    /**
     * Print the the trace of methods from where the error 
     * originated.  This will trace all nested exception 
     * objects, as well as this object.
     * @param s The stream where the dump will be sent to.
     */
    public void printStackTrace(java.io.PrintStream s) 
    {
      if(s == null)
        s = System.err;
      try
      {
        super.printStackTrace(s);
      }
      catch(Exception e){}
      Exception exception = m_exception;
      for(int i = 0; (i < 10) && (null != exception); i++)
      {
        s.println("---------");
        exception.printStackTrace(s);
        if(exception instanceof SAXException)
        {
          SAXException se = (SAXException)exception;
          Exception prev = exception;
          exception = se.getException();
          if(prev == exception)
            break;
        }
        else
        {
          exception = null;
        }
      }
    }
    
    /**
     * Find the most contained message.
     * @returns The error message of the originating exception.
     */
    public String getMessage() 
    {
      String lastMessage = super.getMessage();
      Exception exception = m_exception;
      while(null != exception)
      {
        String nextMessage = exception.getMessage();
        if(null != nextMessage)
          lastMessage = nextMessage;
        if(exception instanceof SAXException)
        {
          SAXException se = (SAXException)exception;
          Exception prev = exception;
          exception = se.getException();
          if(prev == exception)
            break;
        }
        else
        {
          exception = null;
        }
      }
      return (null != lastMessage) ? lastMessage : "";
    }
  
    /**
     * Print the the trace of methods from where the error 
     * originated.  This will trace all nested exception 
     * objects, as well as this object.
     * @param s The writer where the dump will be sent to.
     */
    public void printStackTrace(java.io.PrintWriter s) 
    {
      if(s == null)
        s = new java.io.PrintWriter(System.err);
      try
      {
        super.printStackTrace(s);
      }
      catch(Exception e){}
      Exception exception = m_exception;
      
      for(int i = 0; (i < 10) && (null != exception); i++)
      {
        s.println("---------");
        try
        {
          exception.printStackTrace(s);
        }
        catch(Exception e)
        {
          s.println("Could not print stack trace...");
        }
        if(exception instanceof SAXException)
        {
          SAXException se = (SAXException)exception;
          Exception prev = exception;
          exception = se.getException();
          if(prev == exception)
          {
            exception = null;
            break;
          }
        }
        else
        {
          exception = null;
        }
      }
    }
  
    /**
      * Return the embedded exception, if any.
      * Overrides org.xml.sax.SAXException.getException().
      *
      * @return The embedded exception, or null if there is none.
      */
    public Exception getException ()
    {
      return m_exception;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/XPathFactory.java
  
  Index: XPathFactory.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Factory class for creating an XPath.  Implementors of XPath derivatives
   * will need to make a derived class of this.
   */
  public interface XPathFactory
  {
    /**
     * Create an XPath.
     */
    XPath create();
    
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/XPathParser.java
  
  Index: XPathParser.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import java.util.Vector;
  import java.util.Hashtable;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.res.XSLMessages;
  import org.apache.xalan.utils.StringKey;
  import org.xml.sax.ErrorHandler;
  import org.xml.sax.SAXException;
  import org.xml.sax.Locator;
  import trax.ProcessorException;
  
  /**
   * <meta name="usage" content="general"/>
   * Tokenizes and parses XPath expressions. This should really be named 
   * XPathParserImpl, and may be renamed in the future.
   */
  public class XPathParser implements java.io.Serializable
  {
    /**
     * The XPath to be processed.
     */
    private OpMap m_ops;
  
    /**
     * The next token in the pattern.
     */
    String m_token;
  
    /**
     * The first char in m_token, the theory being that this
     * is an optimization because we won't have to do charAt(0) as
     * often.
     */
    char m_tokenChar = 0;
  
    /**
     * The position in the token queue is tracked by m_queueMark.
     */
    int m_queueMark = 0;
  
    /**
     * The parser constructor.
     */
    public XPathParser()
    {
    }
  
    /**
     * The prefix resolver to map prefixes to namespaces in the XPath.
     */
    PrefixResolver m_namespaceContext;
    
    /**
     * Given an string, init an XPath object for selections, 
     * in order that a parse doesn't 
     * have to be done each time the expression is evaluated.
     * @param pathObj The XPath object to be initialized.
     * @param expresson A String representing the XPath.
     * @param namespaceContext An object that is able to resolve prefixes in 
     * the XPath to namespaces.
     */
    public void initXPath(XPath pathObj, String expression, PrefixResolver 
namespaceContext)
      throws org.xml.sax.SAXException
    {
      m_ops = pathObj;
      m_namespaceContext = namespaceContext;
      Lexer lexer = new Lexer(pathObj, namespaceContext, this);
      lexer.tokenize( expression );
      m_ops.m_opMap[0] = OpCodes.OP_XPATH;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] = 2;
      nextToken();
      Expr();
      if(null != m_token)
      {
        String extraTokens = "";
        while(null != m_token)
        {
          extraTokens += "'"+m_token+"'";
          nextToken();
          if(null != m_token)
            extraTokens += ", ";
        }
        error(XPATHErrorResources.ER_EXTRA_ILLEGAL_TOKENS, new Object[] 
{extraTokens}); //"Extra illegal tokens: "+extraTokens);
      }
      pathObj.shrink();
      doStaticAnalysis(pathObj);
    }
  
    /**
     * Analyze the XPath object to give optimization information.
     */
    void doStaticAnalysis(XPath pathObj)
    {
    }
  
    /**
     * Given an string, init an XPath object for pattern matches, 
     * in order that a parse doesn't 
     * have to be done each time the expression is evaluated.
     * @param pathObj The XPath object to be initialized.
     * @param expresson A String representing the XPath.
     * @param namespaceContext An object that is able to resolve prefixes in 
     * the XPath to namespaces.
     */
    public void initMatchPattern(XPath pathObj, String expression, 
PrefixResolver namespaceContext)
      throws org.xml.sax.SAXException
    {
      m_ops = pathObj;
      m_namespaceContext = namespaceContext;
      Lexer lexer = new Lexer(pathObj, namespaceContext, this);
      lexer.tokenize( expression );
      m_ops.m_opMap[0] = OpCodes.OP_MATCHPATTERN;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] = 2;
      nextToken();
      Pattern();
      if(null != m_token)
      {
        String extraTokens = "";
        while(null != m_token)
        {
          extraTokens += "'"+m_token+"'";
          nextToken();
          if(null != m_token)
            extraTokens += ", ";
        }
        error(XPATHErrorResources.ER_EXTRA_ILLEGAL_TOKENS, new Object[] 
{extraTokens}); //"Extra illegal tokens: "+extraTokens);
      }
      // Terminate for safety.
      m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = OpCodes.ENDOP;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
      m_ops.shrink();
    }
    
    private ErrorHandler m_errorHandler;
  
    /**
     * Allow an application to register an error event handler.
     */
    public void setErrorHandler (ErrorHandler handler)
    {
      m_errorHandler = handler;
    }
  
    /**
     * Return the current error handler.
     */
    public ErrorHandler getErrorHandler ()
    {
      return m_errorHandler;
    }
  
    /**
     * Check whether m_token==s. If m_token is null, returns false (or true if 
s is also null);
     * do not throw an exception.
     */
    final boolean tokenIs( String s )
    {
      return ( m_token!=null ) ? (m_token.equals(s)) : ( s==null );
    }
  
    /**
     * Check whether m_token==c. If m_token is null, returns false (or true if 
c is also null);
     * do not throw an exception.
     */
    final boolean tokenIs( char c )
    {
      return ( m_token!=null ) ? (m_tokenChar == c) : false;
    }
  
    /**
     * Look ahead of the current token in order to
     * make a branching decision.
     * @param s the string to compare it to.
     * @param n number of tokens to look ahead.  Must be
     * greater than 1.
     */
    final boolean lookahead( char c, int n )
    {
      int pos = (m_queueMark+n);
      boolean b;
      if((pos <= m_ops.m_tokenQueueSize) && (pos > 0) && 
(m_ops.m_tokenQueueSize != 0))
      {
        String tok = ((String)m_ops.m_tokenQueue[pos-1]);
        b = (tok.length() == 1) ? (tok.charAt(0) == c) : false;
      }
      else
      {
        b = false;
      }
      return b;
    }
  
    /**
     * Look behind the first character of the current token in order to
     * make a branching decision.
     * @param c the character to compare it to.
     * @param n number of tokens to look behind.  Must be
     * greater than 1.  Note that the look behind terminates
     * at either the beginning of the string or on a '|'
     * character.  Because of this, this method should only
     * be used for pattern matching.
     */
    private final boolean lookbehind( char c, int n )
    {
      boolean isToken;
      int lookBehindPos = m_queueMark-(n+1);
      if( lookBehindPos >= 0 )
      {
        String lookbehind = (String)m_ops.m_tokenQueue[lookBehindPos];
        if(lookbehind.length() == 1)
        {
          char c0 = ( lookbehind == null ) ? '|' : lookbehind.charAt(0);
          isToken = ( c0 == '|' ) ? false : (c0 == c);
        }
        else
        {
          isToken = false;
        }
      }
      else
      {
        isToken = false;
      }
      return isToken;
    }
  
    /**
     * look behind the current token in order to
     * see if there is a useable token.
     * @param n number of tokens to look behind.  Must be
     * greater than 1.  Note that the look behind terminates
     * at either the beginning of the string or on a '|'
     * character.  Because of this, this method should only
     * be used for pattern matching.
     * @return true if look behind has a token, false otherwise.
     */
    private final boolean lookbehindHasToken( int n )
    {
      boolean hasToken;
      if( (m_queueMark-n) > 0 )
      {
        String lookbehind = (String)m_ops.m_tokenQueue[m_queueMark - (n-1)];
        char c0 = ( lookbehind == null ) ? '|' : lookbehind.charAt(0);
        hasToken = ( c0 == '|' ) ? false : true;
      }
      else
      {
        hasToken = false;
      }
      return hasToken;
    }
  
    /**
     * Look ahead of the current token in order to
     * make a branching decision.
     * @param s the string to compare it to.
     * @param n number of tokens to lookahead.  Must be
     * greater than 1.
     */
    private final boolean lookahead( String s, int n )
    {
      boolean isToken;
      if( (m_queueMark+n) <= m_ops.m_tokenQueueSize )
      {
        String lookahead = (String)m_ops.m_tokenQueue[m_queueMark + (n-1)];
        isToken = ( lookahead!=null ) ? lookahead.equals(s) : ( s==null );
      }
      else
      {
        isToken = (null == s);
      }
      return isToken;
    }
  
    /**
     * Retrieve the next token from the command and
     * store it in m_token string.
     */
    private final void nextToken()
    {
      if( m_queueMark < m_ops.m_tokenQueueSize )
      {
        m_token = (String)m_ops.m_tokenQueue[m_queueMark++];
        m_tokenChar = m_token.charAt(0);
      }
      else
      {
        m_token = null;
        m_tokenChar = 0;
      }
    }
  
    /**
     * Retrieve a token relative to the current token.
     * @param i Position relative to current token.
     */
    private final String getTokenRelative(int i)
    {
      String tok;
      int relative = m_queueMark+i;
      if( (relative > 0) && (relative < m_ops.m_tokenQueueSize) )
      {
        tok = (String)m_ops.m_tokenQueue[relative];
      }
      else
      {
        tok = null;
      }
      return tok;
    }
  
    /**
     * Retrieve the previous token from the command and
     * store it in m_token string.
     */
    private final void prevToken()
    {
      if( m_queueMark > 0 )
      {
        m_queueMark--;
        m_token = (String)m_ops.m_tokenQueue[m_queueMark];
        m_tokenChar = m_token.charAt(0);
      }
      else
      {
        m_token = null;
        m_tokenChar = 0;
      }
    }
  
    /**
     * Consume an expected token, throwing an exception if it
     * isn't there.
     */
    private final void consumeExpected(String expected)
      throws org.xml.sax.SAXException
    {
      if(tokenIs(expected))
      {
        nextToken();
      }
      else
      {
                error(XPATHErrorResources.ER_EXPECTED_BUT_FOUND, new Object[] 
{expected, m_token}); //"Expected "+expected+", but found: "+m_token);
      }
    }
  
    /**
     * Consume an expected token, throwing an exception if it
     * isn't there.
     */
    private final void consumeExpected(char expected)
      throws org.xml.sax.SAXException
    {
      if(tokenIs(expected))
      {
        nextToken();
      }
      else
      {
        error(XPATHErrorResources.ER_EXPECTED_BUT_FOUND, new Object[] 
{String.valueOf(expected), m_token}); //"Expected "+expected+", but found: 
"+m_token);
      }
    }
  
    /**
     * Warn the user of a problem.
     */
    void warn(int msg, Object[] args)
      throws SAXException
    {
      String fmsg = XSLMessages.createXPATHWarning(msg, args); 
      
      ErrorHandler ehandler = this.getErrorHandler();
  
      if(null != ehandler)
      {
        // TO DO: Need to get stylesheet Locator from here.
        ehandler.warning(new ProcessorException(fmsg, (Locator)null));
      }  
      else
      {
        System.out.println(fmsg);
      }
    }
  
    /**
     * Notify the user of an assertion error, and probably throw an
     * exception.
     */
    private void assert(boolean b, String msg)
    {
      if(!b)
      {
        String fMsg = 
XSLMessages.createXPATHMessage(XPATHErrorResources.ER_INCORRECT_PROGRAMMER_ASSERTION,
 new Object[] {msg}); 
        throw new RuntimeException(fMsg);
      }
    }
  
    /**
     * Notify the user of an error, and probably throw an
     * exception.
     */
    void error(int msg, Object[] args)
      throws SAXException
    {
      String fmsg = XSLMessages.createXPATHMessage(msg, args); 
      
      ErrorHandler ehandler = this.getErrorHandler();
  
      if(null != ehandler)
      {
        // TO DO: Need to get stylesheet Locator from here.
        ehandler.fatalError(new ProcessorException(fmsg, (Locator)null));
      }
      else
      {
        System.out.println(fmsg);
      }
    }
  
    /**
     * Dump the remaining token queue.
     * Thanks to Craig for this.
     */
    protected String dumpRemainingTokenQueue()
    {
      int q = m_queueMark;
      String returnMsg;
      if(q < m_ops.m_tokenQueueSize)
      {
        String msg = "\n Remaining tokens: (";
        while (q < m_ops.m_tokenQueueSize )
        {
          String t = (String)m_ops.m_tokenQueue[q++];
          msg += (" '" + t + "'");
        }
        returnMsg = msg + ")";
      }
      else
      {
        returnMsg = "";
      }
      return returnMsg;
    }
  
    /**
     * Given a string, return the corresponding function token.
     */
    final int getFunctionToken(String key)
    {
      int tok;
      try
      {
        tok = ((Integer)(Keywords.m_functions.get(key))).intValue();
      }
      catch(NullPointerException npe)
      {
        tok = -1;
      }
      catch(ClassCastException cce)
      {
        tok = -1;
      }
      return tok;
    }
  
    /**
     * Insert room for operation.  This will NOT set
     * the length value of the operation, but will update
     * the length value for the total expression.
     */
    void insertOp(int pos, int length, int op)
    {
      int totalLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      for(int i = totalLen - 1; i >= pos; i--)
      {
        m_ops.m_opMap[i+length] = m_ops.m_opMap[i];
      }
      m_ops.m_opMap[pos] = op;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] = totalLen + length;
    }
  
    /**
     * Insert room for operation.  This WILL set
     * the length value of the operation, and will update
     * the length value for the total expression.
     */
    void appendOp(int length, int op)
    {
      int totalLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      m_ops.m_opMap[totalLen] = op;
      m_ops.m_opMap[totalLen+XPath.MAPINDEX_LENGTH] = length;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] = totalLen + length;
    }
  
    // ============= EXPRESSIONS FUNCTIONS =================
    
    /**
     *
     *
     * Expr  ::=  OrExpr
     *
     */
    protected void Expr()
      throws org.xml.sax.SAXException
    {
      OrExpr();
    }
  
    /**
     *
     *
     * OrExpr  ::=  AndExpr
     * | OrExpr 'or' AndExpr
     *
     */
    protected void OrExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      AndExpr();
      if((null != m_token) && tokenIs("or"))
      {
        nextToken();
        insertOp(opPos, 2, OpCodes.OP_OR);
        OrExpr();
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH]
          = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      }
    }
  
    /**
     *
     *
     * AndExpr  ::=  EqualityExpr
     * | AndExpr 'and' EqualityExpr
     *
     */
    protected void AndExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      EqualityExpr(-1);
      if((null != m_token) && tokenIs("and"))
      {
        nextToken();
        insertOp(opPos, 2, OpCodes.OP_AND);
        AndExpr();
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      }
    }
  
    /**
     *
     * @returns an Object which is either a String, a Number, a Boolean, or a 
vector
     * of nodes.
     *
     * EqualityExpr  ::=  RelationalExpr
     * | EqualityExpr '=' RelationalExpr
     *
     */
    protected int EqualityExpr(int addPos)
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      if(-1 == addPos)
        addPos = opPos;
      RelationalExpr(-1);
      if(null != m_token)
      {
        if(tokenIs('!') && lookahead('=', 1))
        {
          nextToken();
          nextToken();
          insertOp(addPos, 2, OpCodes.OP_NOTEQUALS);
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = EqualityExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
        else if(tokenIs('='))
        {
          nextToken();
          insertOp(addPos, 2, OpCodes.OP_EQUALS);
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = EqualityExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
      }
      return addPos;
    }
  
    /**
     * .
     * @returns an Object which is either a String, a Number, a Boolean, or a 
vector
     * of nodes.
     *
     * RelationalExpr  ::=  AdditiveExpr
     * | RelationalExpr '<' AdditiveExpr
     * | RelationalExpr '>' AdditiveExpr
     * | RelationalExpr '<=' AdditiveExpr
     * | RelationalExpr '>=' AdditiveExpr
     *
     */
    protected int RelationalExpr(int addPos)
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      if(-1 == addPos)
        addPos = opPos;
      AdditiveExpr(-1);
      if(null != m_token)
      {
        if(tokenIs('<'))
        {
          nextToken();
          if(tokenIs('='))
          {
            nextToken();
            insertOp(addPos, 2, OpCodes.OP_LTE);
          }
          else
          {
            insertOp(addPos, 2, OpCodes.OP_LT);
          }
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = RelationalExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
        else if(tokenIs('>'))
        {
          nextToken();
          if(tokenIs('='))
          {
            nextToken();
            insertOp(addPos, 2, OpCodes.OP_GTE);
          }
          else
          {
            insertOp(addPos, 2, OpCodes.OP_GT);
          }
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = RelationalExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
      }
      return addPos;
    }
  
    /**
     * XXXX.
     * @returns an Object which is either a String, a Number, a Boolean, or a 
vector
     * of nodes.
     * This has to handle construction of the operations so that they are 
evaluated
     * in pre-fix order.  So, for 9+7-6, instead of |+|9|-|7|6|, this needs to 
be
     * evaluated as |-|+|9|7|6|.
     * @param addPos The position where the op should be inserted.
     *
     * AdditiveExpr  ::=  MultiplicativeExpr
     * | AdditiveExpr '+' MultiplicativeExpr
     * | AdditiveExpr '-' MultiplicativeExpr
     *
     */
    protected int AdditiveExpr(int addPos)
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      if(-1 == addPos)
        addPos = opPos;
      MultiplicativeExpr(-1);
      if(null != m_token)
      {
        if(tokenIs('+'))
        {
          nextToken();
          insertOp(addPos, 2, OpCodes.OP_PLUS);
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = AdditiveExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
        else if(tokenIs('-'))
        {
          nextToken();
          insertOp(addPos, 2, OpCodes.OP_MINUS);
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = AdditiveExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
      }
      return addPos;
    }
  
    /**
     * XXXX.
     * @returns an Object which is either a String, a Number, a Boolean, or a 
vector
     * of nodes.
     * This has to handle construction of the operations so that they are 
evaluated
     * in pre-fix order.  So, for 9+7-6, instead of |+|9|-|7|6|, this needs to 
be
     * evaluated as |-|+|9|7|6|.
     * @param addPos The position where the op should be inserted.
     *
     * MultiplicativeExpr  ::=  UnaryExpr
     * | MultiplicativeExpr MultiplyOperator UnaryExpr
     * | MultiplicativeExpr 'div' UnaryExpr
     * | MultiplicativeExpr 'mod' UnaryExpr
     * | MultiplicativeExpr 'quo' UnaryExpr
     *
     */
    protected int MultiplicativeExpr(int addPos)
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      if(-1 == addPos)
        addPos = opPos;
      UnaryExpr();
      if(null != m_token)
      {
        if(tokenIs('*'))
        {
          nextToken();
          insertOp(addPos, 2, OpCodes.OP_MULT);
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = MultiplicativeExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;        
        }
        else if(tokenIs("div"))
        {
          nextToken();
          insertOp(addPos, 2, OpCodes.OP_DIV);
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = MultiplicativeExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
        else if(tokenIs("mod"))
        {
          nextToken();
          insertOp(addPos, 2, OpCodes.OP_MOD);
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = MultiplicativeExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
        else if(tokenIs("quo"))
        {
          nextToken();
          insertOp(addPos, 2, OpCodes.OP_QUO);
          int opPlusLeftHandLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - addPos;
          addPos = MultiplicativeExpr(addPos);
          m_ops.m_opMap[addPos + XPath.MAPINDEX_LENGTH]
            = m_ops.m_opMap[addPos+opPlusLeftHandLen+1] + opPlusLeftHandLen;
          addPos+=2;
        }
      }
      return addPos;
    }
  
    /**
     * XXXX.
     * @returns an Object which is either a String, a Number, a Boolean, or a 
vector
     * of nodes.
     *
     * UnaryExpr  ::=  UnionExpr
     * | '-' UnaryExpr
     *
     */
    protected void UnaryExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      boolean isNeg = false;
      if(m_tokenChar == '-')
      {
        nextToken();
        appendOp(2, OpCodes.OP_NEG);
        isNeg = true;
      }
      UnionExpr();
      if(isNeg)
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    /**
     *
     * StringExpr  ::=  Expr
     *
     */
    protected void StringExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      appendOp(2, OpCodes.OP_STRING);
      Expr();
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    /**
     *
     *
     * StringExpr  ::=  Expr
     *
     */
    protected void BooleanExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      appendOp(2, OpCodes.OP_BOOL);
      Expr();
      int opLen = m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      if(opLen == 2)
      {
        error(XPATHErrorResources.ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL, null); 
//"boolean(...) argument is no longer optional with 19990709 XPath draft.");
      }
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = opLen;
    }
  
    /**
     *
     *
     * NumberExpr  ::=  Expr
     *
     */
    protected void NumberExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      appendOp(2, OpCodes.OP_NUMBER);
      Expr();
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    /**
     * The context of the right hand side expressions is the context of the
     * left hand side expression. The results of the right hand side expressions
     * are node sets. The result of the left hand side UnionExpr is the union
     * of the results of the right hand side expressions.
     *
     *
     * UnionExpr    ::=    PathExpr
     * | UnionExpr '|' PathExpr
     *
     */
    protected void UnionExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      boolean continueOrLoop = true;
      boolean foundUnion = false;
      do
      {
        PathExpr();
  
        if(tokenIs('|'))
        {
          if(false == foundUnion)
          {
            foundUnion = true;
            insertOp(opPos, 2, OpCodes.OP_UNION);
          }
          nextToken();
        }
        else
        {
          break;
        }
  
        // this.m_testForDocOrder = true;
      }
        while(continueOrLoop);
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    /**
     * Analyze a union pattern and tell if the axes are
     * all descendants.
     * (Move to XPath?)
     */
    private static boolean isLocationPathSimpleFollowing(OpMap xpath, int opPos)
    {
      if(true)
      {
        // int posOfLastOp = xpath.getNextOpPos(opPos)-1;
  
        opPos = xpath.getFirstChildPos(opPos);
        // step
        int stepType = xpath.m_opMap[opPos];
  
        // make sure all step types are going forwards
        switch(stepType)
        {
        case OpCodes.FROM_SELF:
        case OpCodes.FROM_ATTRIBUTES:
        case OpCodes.FROM_CHILDREN:
        case OpCodes.FROM_DESCENDANTS:
        case OpCodes.FROM_DESCENDANTS_OR_SELF:
        case OpCodes.FROM_FOLLOWING:
        case OpCodes.FROM_FOLLOWING_SIBLINGS:
          if(xpath.m_opMap[xpath.getNextOpPos(opPos)] == OpCodes.ENDOP)
          {
            // Add the length of the step itself, plus the length of the op,
            // and two length arguments, to the op position.
            opPos = 
(xpath.getArgLengthOfStep(opPos)+xpath.getFirstChildPosOfStep(opPos));
            int nextStepType = xpath.m_opMap[opPos];
  
            if(OpCodes.OP_PREDICATE == nextStepType)
            {
              int firstPredPos = opPos+2;
              int predicateType = xpath.m_opMap[firstPredPos];
              if((OpCodes.OP_NUMBERLIT == predicateType) || (OpCodes.OP_NUMBER 
== predicateType)
                 || (FunctionTable.FUNC_NUMBER == predicateType))
              {
                return false;
              }
              opPos = xpath.getNextOpPos(opPos);
              nextStepType = xpath.m_opMap[opPos];
              // Multiple predicates?
              if(OpCodes.OP_PREDICATE == nextStepType)
                return false;
            }
            return true;
          }
          break;
        }
        return false;
      }
      else
      {
        return false;
      }
    }
  
  
    /**
     * PathExpr  ::=  LocationPath
     * | FilterExpr
     * | FilterExpr '/' RelativeLocationPath
     * | FilterExpr '//' RelativeLocationPath
     *
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    protected void PathExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      boolean foundLocationPath;
  
      FilterExpr();
  
      if(tokenIs('/'))
      { 
        nextToken();
        int locationPathOpPos = opPos;
        insertOp(opPos, 2, OpCodes.OP_LOCATIONPATH);
        RelativeLocationPath();
  
        // Terminate for safety.
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = OpCodes.ENDOP;
        m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
        if(isLocationPathSimpleFollowing(m_ops, locationPathOpPos))
        {
          m_ops.m_opMap[locationPathOpPos] = OpCodes.OP_LOCATIONPATH_EX;
        }
      }
    }
  
    /**
     *
     *
     * FilterExpr  ::=  PrimaryExpr
     * | FilterExpr Predicate
     *
     * @exception XSLProcessorException thrown if the active ProblemListener 
and XPathContext decide
     * the error condition is severe enough to halt processing.
     */
    protected void FilterExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      // boolean isFunc = lookahead('(', 1);
      PrimaryExpr();
  
      if(tokenIs('['))
      {
        int locationPathOpPos = opPos;
        insertOp(opPos, 2, OpCodes.OP_LOCATIONPATH);
  
        while(tokenIs('['))
        {
          Predicate();
        }
  
        if(tokenIs('/'))
        {
          nextToken();
          RelativeLocationPath();
        }
  
        // Terminate for safety.
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = OpCodes.ENDOP;
        m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
        if(isLocationPathSimpleFollowing(m_ops, locationPathOpPos))
        {
          m_ops.m_opMap[locationPathOpPos] = OpCodes.OP_LOCATIONPATH_EX;
        }
      }
  
      /*
       * if(tokenIs('['))
       * {
       *   Predicate();
       *   m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
       * }
       */
    }
  
    /**
     *
     * PrimaryExpr  ::=  VariableReference
     * | '(' Expr ')'
     * | Literal
     * | Number
     * | FunctionCall
     *
     */
    protected void PrimaryExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      if((m_tokenChar == '\'') || (m_tokenChar == '"'))
      {
        appendOp(2, OpCodes.OP_LITERAL);
        Literal();
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      }
      else if(m_tokenChar == '$')
      {
        nextToken(); // consume '$'
        appendOp(2, OpCodes.OP_VARIABLE);
  
        NCName();
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      }
      else if(m_tokenChar == '(')
      {
        nextToken();
        appendOp(2, OpCodes.OP_GROUP);
        Expr();
        consumeExpected(')');
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      }
      else if((null != m_token) &&
              ((('.' == m_tokenChar) && (m_token.length() > 1) &&
                Character.isDigit( m_token.charAt(1) ))
               || Character.isDigit( m_tokenChar )))
      {
        appendOp(2, OpCodes.OP_NUMBERLIT);
        Number();
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      }
      else if(lookahead('(', 1) || (lookahead(':', 1) && lookahead('(', 3)))
      {
        FunctionCall();
      }
      else
      {
        LocationPath();
      }
    }
  
    /**
     *
     * Argument    ::=    Expr
     *
     */
    protected void Argument()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      appendOp(2, OpCodes.OP_ARGUMENT);
      Expr();
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    /**
     *
     * FunctionCall    ::=    FunctionName '(' ( Argument ( ',' Argument)*)? ')'
     *
     */
    protected void FunctionCall()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      if(lookahead(':',1))
      {
        appendOp(4, OpCodes.OP_EXTFUNCTION);
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH + 1] = m_queueMark-1;
        nextToken();
        consumeExpected(':');
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH + 2] = m_queueMark-1;
        nextToken();
      }
      else
      {
        int funcTok = getFunctionToken(m_token);
        if(-1 == funcTok)
        {
                  error(XPATHErrorResources.ER_COULDNOT_FIND_FUNCTION, new 
Object[] {m_token}); //"Could not find function: "+m_token+"()");
        }
        switch(funcTok)
        {
        case OpCodes.NODETYPE_PI:
        case OpCodes.NODETYPE_COMMENT:
        case OpCodes.NODETYPE_TEXT:
        case OpCodes.NODETYPE_NODE:
          LocationPath();
          return;
        default:
          appendOp(3, OpCodes.OP_FUNCTION);
          m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH + 1] = funcTok;
        }
        nextToken();
      }
      consumeExpected('(');
      while(!tokenIs(')'))
      {
        if(tokenIs(','))
        {
          error(XPATHErrorResources.ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG, null); 
//"Found ',' but no preceding argument!");
        }
        Argument();
        if(!tokenIs(')'))
        {
          consumeExpected(',');
          if(tokenIs(')'))
          {
            error(XPATHErrorResources.ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG, 
null); //"Found ',' but no following argument!");
          }
        }
      }
      consumeExpected(')');
  
      // Terminate for safety.
      m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = OpCodes.ENDOP;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    // ============= GRAMMAR FUNCTIONS =================
  
    /**
     *
     * LocationPath ::= RelativeLocationPath
     * | AbsoluteLocationPath
     *
     */
    protected void LocationPath()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      int locationPathOpPos = opPos;
      appendOp(2, OpCodes.OP_LOCATIONPATH);
  
      if(tokenIs('/'))
      {
        appendOp(4, OpCodes.FROM_ROOT);
        // Tell how long the step is without the predicate
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 2] = 4;
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 1] = 
OpCodes.NODETYPE_ROOT;
        nextToken();
      }
      if(m_token != null)
      {
        RelativeLocationPath();
      }
  
      // Terminate for safety.
      m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = OpCodes.ENDOP;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      if(isLocationPathSimpleFollowing(m_ops, locationPathOpPos))
      {
        m_ops.m_opMap[locationPathOpPos] = OpCodes.OP_LOCATIONPATH_EX;
      }
    }
  
    /**
     *
     * RelativeLocationPath ::= Step
     * | RelativeLocationPath '/' Step
     * | AbbreviatedRelativeLocationPath
     *
     */
    protected void RelativeLocationPath()
      throws org.xml.sax.SAXException
    {
      Step();
      while(tokenIs('/'))
      {
        nextToken();
        Step();
      }
    }
  
  
    /**
     *
     * Step    ::=    Basis Predicate*
     * | AbbreviatedStep
     */
    protected void Step()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
  
      if(tokenIs("."))
      {
        nextToken();
        if(tokenIs('['))
        {
          error(XPATHErrorResources.ER_PREDICATE_ILLEGAL_SYNTAX, null); 
//"'..[predicate]' or '.[predicate]' is illegal syntax.  Use 
'self::node()[predicate]' instead.");
        }
        appendOp(4, OpCodes.FROM_SELF);
        // Tell how long the step is without the predicate
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 2] = 4;
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 1] = 
OpCodes.NODETYPE_NODE;
      }
      else if(tokenIs(".."))
      {
        nextToken();
        appendOp(4, OpCodes.FROM_PARENT);
        // Tell how long the step is without the predicate
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 2] = 4;
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 1] = 
OpCodes.NODETYPE_NODE;
      }
      else
      {
        Basis();
  
        while(tokenIs('['))
        {
          Predicate();
        }
  
        // Tell how long the entire step is.
        m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
      }
    }
  
    /**
     *
     * Basis    ::=    AxisName '::' NodeTest
     * | AbbreviatedBasis
     */
    protected void Basis()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      int axesType;
  
      // The next blocks guarantee that a FROM_XXX will be added.
      if(lookahead("::", 1))
      {
        axesType = AxisName();
        nextToken();
        nextToken();
      }
      else if(tokenIs('@'))
      {
        axesType = OpCodes.FROM_ATTRIBUTES;
        appendOp(2, axesType);
        nextToken();
      }
      else if(tokenIs('/'))
      {
        axesType = OpCodes.FROM_DESCENDANTS_OR_SELF;
        appendOp(2, axesType);
  
        // Have to fix up for patterns such as '//@foo' or '//attribute::foo',
        // which translate to 'descendant-or-self::node()/attribute::foo'.
        // notice I leave the '/' on the queue, so the next will be processed
        // by a regular step pattern.
        // if(lookahead('@', 1) || lookahead("::", 2))
        {
          // Make room for telling how long the step is without the predicate
          m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
          m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = 
OpCodes.NODETYPE_NODE;
          m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
          // Tell how long the step is without the predicate
          m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH + 1] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
  
          return; // make a quick exit...
        }
        // else
        // {
        //  nextToken();
        // }
      }
      else
      {
        axesType = OpCodes.FROM_CHILDREN;
        appendOp(2, axesType);
      }
  
      // Make room for telling how long the step is without the predicate
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
      NodeTest(axesType);
  
      // Tell how long the step is without the predicate
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH + 1] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    /**
     *
     * Basis    ::=    AxisName '::' NodeTest
     * | AbbreviatedBasis
     */
    protected int AxisName()
      throws org.xml.sax.SAXException
    {
      Object val = Keywords.m_axisnames.get(m_token);
      if(null == val)
      {
        error(XPATHErrorResources.ER_ILLEGAL_AXIS_NAME, new Object[] 
{m_token}); //"illegal axis name: "+m_token);
      }
      int axesType = ((Integer)val).intValue();
      appendOp(2, axesType);
      return axesType;
    }
  
  
    /**
     *
     * NodeTest    ::=    WildcardName
     * | NodeType '(' ')'
     * | 'processing-instruction' '(' Literal ')'
     */
    protected void NodeTest(int axesType)
      throws org.xml.sax.SAXException
    {
      if(lookahead('(', 1))
      {
        Object nodeTestOp = Keywords.m_nodetypes.get(m_token);
        if(null == nodeTestOp)
        {
          error(XPATHErrorResources.ER_UNKNOWN_NODETYPE, new Object[] 
{m_token}); //"Unknown nodetype: "+m_token);
        }
        else
        {
          nextToken();
          int nt = ((Integer)nodeTestOp).intValue();
          m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = nt;
          m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
          consumeExpected('(');
          if(OpCodes.NODETYPE_PI == nt)
          {
            if(!tokenIs(')'))
            {
              Literal();
            }
          }
          consumeExpected(')');
        }
      }
      else
      {
        // Assume name of attribute or element.
          m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = 
OpCodes.NODENAME;
          m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
          if(lookahead(':', 1))
          {
            if(tokenIs('*'))
            {
              m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]]
                = OpCodes.ELEMWILDCARD;
            }
            else
            {
              m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = 
m_queueMark-1;
            }
            nextToken();
            consumeExpected(':');
          }
          else
          {
            m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = OpCodes.EMPTY;
          }
          m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
          if(tokenIs('*'))
          {
            m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = 
OpCodes.ELEMWILDCARD;
          }
          else
          {
            if(OpCodes.FROM_NAMESPACE == axesType)
            {
              String prefix = (String)this.m_ops.m_tokenQueue[m_queueMark-1];
              String namespace = 
((PrefixResolver)m_namespaceContext).getNamespaceForPrefix(prefix);
              this.m_ops.m_tokenQueue[m_queueMark-1] = namespace;
            }
            m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = m_queueMark-1;
          }
  
          m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
          nextToken();
      }
    }
  
    /**
     *
     * Predicate ::= '[' PredicateExpr ']'
     *
     */
    protected void Predicate()
      throws org.xml.sax.SAXException
    {
      if(tokenIs('['))
      {
        nextToken();
        PredicateExpr();
        consumeExpected(']');
      }
    }
  
    /**
     *
     * PredicateExpr ::= Expr
     *
     */
    protected void PredicateExpr()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      appendOp(2, OpCodes.OP_PREDICATE);
      Expr();
  
      // Terminate for safety.
      m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = OpCodes.ENDOP;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    /**
     * QName ::=  (Prefix ':')? LocalPart
     * Prefix ::=  NCName
     * LocalPart ::=  NCName
     */
    protected void QName()
      throws org.xml.sax.SAXException
    {
      m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = m_queueMark-1;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
      nextToken();
      consumeExpected(':');
      m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = m_queueMark-1;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
      nextToken();
    }
  
    /**
     * NCName ::=  (Letter | '_') (NCNameChar)*
     * NCNameChar ::=  Letter | Digit | '.' | '-' | '_' | CombiningChar | 
Extender
     */
    protected void NCName()
    {
      m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = m_queueMark-1;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
      nextToken();
    }
  
    /**
     * The value of the Literal is the sequence of characters inside
     * the " or ' characters>.
     *
     * Literal  ::=  '"' [^"]* '"'
     * | "'" [^']* "'"
     *
     */
    protected void Literal()
      throws org.xml.sax.SAXException
    {
      int last = m_token.length()-1;
      char c0 = m_tokenChar;
      char cX = m_token.charAt(last);
      if(((c0 == '\"') && (cX == '\"')) ||
         ((c0 == '\'') && (cX == '\'')))
      {
        // Mutate the token to remove the quotes and have the XString object
        // already made.
        int tokenQueuePos = m_queueMark-1;
        m_ops.m_tokenQueue[tokenQueuePos] = null;
        Object obj = new XString(m_token.substring(1, last));
        m_ops.m_tokenQueue[tokenQueuePos] = obj;
        // lit = m_token.substring(1, last);
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = tokenQueuePos;
        m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
        nextToken();
      }
      else
      {
        error(XPATHErrorResources.ER_PATTERN_LITERAL_NEEDS_BE_QUOTED, new 
Object[] {m_token}); //"Pattern literal ("+m_token+") needs to be quoted!");
      }
    }
  
    /**
     *
     * Number ::= [0-9]+('.'[0-9]+)? | '.'[0-9]+
     *
     */
    protected void Number()
      throws org.xml.sax.SAXException
    {
      if(null != m_token)
      {
        // Mutate the token to remove the quotes and have the XNumber object
        // already made.
        double num;
        try
        {
          num = Double.valueOf(m_token).doubleValue();
        }
        catch(NumberFormatException nfe)
        {
          num = 0.0; // to shut up compiler.
          error(XPATHErrorResources.ER_COULDNOT_BE_FORMATTED_TO_NUMBER, new 
Object[] {m_token}); //m_token+" could not be formatted to a number!");
        }
        m_ops.m_tokenQueue[m_queueMark-1]
          = new XNumber(num);
  
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = m_queueMark - 1;
        m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
        nextToken();
      }
    }
  
    // ============= PATTERN FUNCTIONS =================
  
    /**
     *
     * Pattern  ::=  LocationPathPattern
     * | Pattern '|' LocationPathPattern
     *
     */
    protected void Pattern()
      throws org.xml.sax.SAXException
    {
      while(true)
      {
        LocationPathPattern();
  
        if(tokenIs('|'))
        {
          nextToken();
        }
        else
        {
          break;
        }
      }
    }
  
    /**
     *
     *
     * LocationPathPattern  ::=  '/' RelativePathPattern?
     * | IdKeyPattern (('/' | '//') RelativePathPattern)?
     * | '//'? RelativePathPattern
     *
     */
    protected void LocationPathPattern()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      appendOp(2, OpCodes.OP_LOCATIONPATHPATTERN);
  
      if(lookahead('(', 1) 
         && (tokenIs(Keywords.FUNC_ID_STRING) || 
tokenIs(Keywords.FUNC_KEY_STRING)))
      {
        IdKeyPattern();
        if(tokenIs('/') && lookahead('/', 1))
        {
          appendOp(4, OpCodes.MATCH_ANY_ANCESTOR);
          // Tell how long the step is without the predicate
          m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 2] = 4;
          m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 1] = 
OpCodes.NODETYPE_ROOT;
          nextToken();
        }
      }
      else if(tokenIs('/'))
      {
        if(lookahead('/', 1))
        {
          appendOp(4, OpCodes.MATCH_ANY_ANCESTOR);
        }
        else
        {
          appendOp(4, OpCodes.FROM_ROOT);
        }
        // Tell how long the step is without the predicate
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 2] = 4;
        m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - 1] = 
OpCodes.NODETYPE_ROOT;
        nextToken();
      }
  
      if(!tokenIs('|') && (null != m_token))
      {
        RelativePathPattern();
      }
  
      // Terminate for safety.
      m_ops.m_opMap[m_ops.m_opMap[XPath.MAPINDEX_LENGTH]] = OpCodes.ENDOP;
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
    /**
     *
     * IdKeyPattern  ::=  'id' '(' Literal ')'
     * | 'key' '(' Literal ',' Literal ')'
     * (Also handle doc())
     *
     */
    protected void IdKeyPattern()
      throws org.xml.sax.SAXException
    {
      FunctionCall();
    }
  
    /**
     *
     * RelativePathPattern  ::=  StepPattern
     * | RelativePathPattern '/' StepPattern
     * | RelativePathPattern '//' StepPattern
     *
     */
    protected void RelativePathPattern()
      throws org.xml.sax.SAXException
    {
      StepPattern();
      while(tokenIs('/'))
      {
        nextToken();
        StepPattern();
      }
    }
  
    /**
     *
     * StepPattern  ::=  AbbreviatedNodeTestStep
     *
     */
    protected void StepPattern()
      throws org.xml.sax.SAXException
    {
      AbbreviatedNodeTestStep(  );
    }
  
    /**
     *
     * AbbreviatedNodeTestStep    ::=    '@'? NodeTest Predicate*
     *
     */
    protected void AbbreviatedNodeTestStep()
      throws org.xml.sax.SAXException
    {
      int opPos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
      int axesType;
  
      // The next blocks guarantee that a MATCH_XXX will be added.
      int matchTypePos = -1;
      if(tokenIs('@'))
      {
        axesType = OpCodes.MATCH_ATTRIBUTE;
        appendOp(2, axesType);
        nextToken();
      }
      else if(this.lookahead("::", 1))
      {
        if(tokenIs("attribute"))
        {
          axesType = OpCodes.MATCH_ATTRIBUTE;
          appendOp(2, axesType);
        }
        else if(tokenIs("child"))
        {
          axesType = OpCodes.MATCH_IMMEDIATE_ANCESTOR;
          appendOp(2, axesType);
        }
        else
        {
          axesType = -1;
          this.error(XPATHErrorResources.ER_AXES_NOT_ALLOWED, new Object[] 
{this.m_token});
        }
        nextToken();
        nextToken();
      }
      else if(tokenIs('/'))
      {
        axesType = OpCodes.MATCH_ANY_ANCESTOR;
        appendOp(2, axesType);
        nextToken();
      }
      else
      {
        if(tokenIs('/'))
        {
          nextToken();
        }
        matchTypePos = m_ops.m_opMap[XPath.MAPINDEX_LENGTH];
        axesType = OpCodes.MATCH_IMMEDIATE_ANCESTOR;
        appendOp(2, axesType);
      }
  
      // Make room for telling how long the step is without the predicate
      m_ops.m_opMap[XPath.MAPINDEX_LENGTH] += 1;
  
      NodeTest(axesType);
  
      // Tell how long the step is without the predicate
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH + 1] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
  
      while(tokenIs('['))
      {
        Predicate();
      }
      if((matchTypePos > -1) && tokenIs('/') && lookahead('/', 1))
      {
        m_ops.m_opMap[matchTypePos] = OpCodes.MATCH_ANY_ANCESTOR;
        nextToken();
      }
  
      // Tell how long the entire step is.
      m_ops.m_opMap[opPos + XPath.MAPINDEX_LENGTH] = 
m_ops.m_opMap[XPath.MAPINDEX_LENGTH] - opPos;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/XPathProcessorException.java
  
  Index: XPathProcessorException.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  /**
   * <meta name="usage" content="general"/>
   * Derived from XPathException in order that XPath processor 
   * exceptions may be specifically caught.
   */
  public class XPathProcessorException extends XPathException
  {
    /**
     * Create an XPathProcessorException object that holds 
     * an error message.
     * @param message The error message.
     */
    public XPathProcessorException(String message) 
    {
      super(message);
    }
  
    /**
     * Create an XPathProcessorException object that holds 
     * an error message, and another exception 
     * that caused this exception.
     * @param message The error message.
     * @param e The exception that caused this exception.
     */
    public XPathProcessorException (String message, Exception e)
    {
      super(message, e);
    }
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XRTreeFrag.java
  
  Index: XRTreeFrag.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.*;
  import org.apache.xalan.xpath.DOMHelper;
  
  /**
   * <meta name="usage" content="general"/>
   * This class represents an XPath result tree fragment object, and is capable 
of 
   * converting the RTF to other types, such as a string.
   */
  public class XRTreeFrag extends XObject
  {  
    /**
     * Create an XObject.
     */
    public XRTreeFrag(DocumentFragment frag)
    {
      super(frag);
    }
    
    /**
     * Tell what kind of class this is.
     */
    public int getType()
    {
      return CLASS_RTREEFRAG;
    }
  
    /**
     * Given a request type, return the equivalent string. 
     * For diagnostic purposes.
     */
    private String getTypeString()
    {
      return "#RTREEFRAG";
    }
    
    /**
     * Cast result object to a number.
     */
    public double num()
    {
      java.text.NumberFormat m_formatter = 
java.text.NumberFormat.getNumberInstance();
      double result;
      String s = DOMHelper.getNodeData((DocumentFragment)m_obj);
      if(null != s)
      {
        try
        {
          // result = Double.valueOf(s).doubleValue();
          Number n = m_formatter.parse(s.trim());
          result = n.doubleValue();
        }
        // catch(NumberFormatException nfe)
        catch(java.text.ParseException nfe)
        {
          result = Double.NaN;
        }
      }
      else
      {
        result = Double.NaN;
      }
  
      return result;
    }
  
    /**
     * Cast result object to a boolean.
     */
    public boolean bool()
    {
      boolean result = false;
      NodeList nl = ((DocumentFragment)m_obj).getChildNodes();
      int nChildren = nl.getLength();
      for(int i = 0; i < nChildren; i++)
      {
        Node n = nl.item(i);
        if((Node.TEXT_NODE == n.getNodeType()) &&
            (((Text)n).getData().trim().length() == 0))
        {
          continue;
        }
        
        result = true;
        break;
      }
  
      return result;
    }
  
    /**
     * Cast result object to a string.
     */
    public String str()
    {
      String str = DOMHelper.getNodeData((DocumentFragment)m_obj);
      return (null == str) ? "" : str;
    }
    
    /**
     * Cast result object to a result tree fragment.
     */
    public DocumentFragment rtree()
    {
      return (DocumentFragment)m_obj;
    }
    
    /**
     * Cast result object to a nodelist. (special function).
     */
    public NodeList convertToNodeset()
    {
      return ((DocumentFragment)m_obj).getChildNodes();
    }  
    
    /**
     * Tell if two objects are functionally equal.
     */
    public boolean equals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      if(XObject.CLASS_NODESET == obj2.getType())
      {
        // In order to handle the 'all' semantics of 
        // nodeset comparisons, we always call the 
        // nodeset function.
        return obj2.equals(this);
      }
      else if(XObject.CLASS_BOOLEAN == obj2.getType())
      {
        return bool() == obj2.bool();
      }
      else if(XObject.CLASS_NUMBER == obj2.getType())
      {
        return num() == obj2.num();
      }
      else if(XObject.CLASS_NODESET == obj2.getType())
      {
        return str().equals(obj2.str());
      }
      else if(XObject.CLASS_STRING == obj2.getType())
      {
        return str().equals(obj2.str());
      }
      else if(XObject.CLASS_RTREEFRAG == obj2.getType())
      {
        // Probably not so good.  Think about this.
        return str().equals(obj2.str());
      }
      else
      {
        return super.equals(obj2);
      }
    }
  
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xpath/XString.java
  
  Index: XString.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath;
  
  import org.w3c.dom.*;
  
  /**
   * <meta name="usage" content="general"/>
   * This class represents an XPath string object, and is capable of 
   * converting the string to other types, such as a number.
   */
  public class XString extends XObject
  {
    /**
     * Construct a XNodeSet object.
     */
    public XString(String val)
    {
      super(val);
    }
  
    /**
     * Tell that this is a CLASS_STRING.
     */
    public int getType()
    {
      return CLASS_STRING;
    }
    
    /**
     * Given a request type, return the equivalent string. 
     * For diagnostic purposes.
     */
    private String getTypeString()
    {
      return "#STRING";
    }
    
    /**
     * Cast a string to a number.
     */
    public static double castToNum(String s)
    {
      double result;
      if(null == s) 
        result = 0.0;
      else
      {
        try 
        {
          /**
          * TODO: Adjust this for locale. Need to take into 
          * account the lang parameter on the xsl:sort 
          */
          // It seems we can not use this as it just parses the 
          // start of the string until it finds a non-number char, 
          // which is not what we want according to the XSLT spec.  
          // Also, I *think* this is a local-specific
          // parse, which is also not what we want according to the 
          // XSLT spec (see below).
          // NumberFormat formatter = NumberFormat.getNumberInstance();
          // result = formatter.parse(s.trim()).doubleValue();
          
          // The dumb XSLT spec says: "The number function should 
          // not be used for conversion of numeric data occurring 
          // in an element in an XML document unless the element 
          // is of a type that represents numeric data in a 
          // language-neutral format (which would typically be 
          // transformed into a language-specific format for 
          // presentation to a user). In addition, the number 
          // function cannot be used unless the language-neutral 
          // format used by the element is consistent with the 
          // XPath syntax for a Number."
          // So I guess we need to check, if the default local 
          // is french, does Double.valueOf use the local specific 
          // parse?  Or does it use the ieee parse?
          result = Double.valueOf(s.trim()).doubleValue();
        }
        // catch (ParseException e) 
        catch (NumberFormatException nfe)
        {
          result = Double.NaN;
        }
      }
      return result;
    }
    
    /**
     * Cast result object to a number.
     */
    public double num()
    {
      return castToNum((String)m_obj);
    }
  
    /**
     * Cast result object to a boolean.
     */
    public boolean bool()
    {
      return str().length() > 0;
    }
  
    /**
     * Cast result object to a string.
     */
    public String str()
    {
      return (null != m_obj) ? ((String)m_obj) : "";
    }
    
    /**
     * Cast result object to a result tree fragment.
     */
    public DocumentFragment rtree(XPathContext support)
    {
      DocumentFragment df = 
support.getDOMHelper().getDOMFactory().createDocumentFragment();
      Text textNode = 
support.getDOMHelper().getDOMFactory().createTextNode(str());
      df.appendChild(textNode);
      return df;
    }
    
    /**
     * Tell if two objects are functionally equal.
     */
    public boolean equals(XObject obj2)
      throws org.xml.sax.SAXException
    {
      // In order to handle the 'all' semantics of 
      // nodeset comparisons, we always call the 
      // nodeset function.
      if(obj2.getType() == XObject.CLASS_NODESET)
        return obj2.equals(this);
  
      return str().equals(obj2.str());
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/AncestorOrSelfWalker.java
  
  Index: AncestorOrSelfWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import java.util.Stack;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.DOMHelper;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'ancestor-or-self' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class AncestorOrSelfWalker extends AncestorWalker
  {
    /**
     * Construct an AncestorOrSelfWalker using a LocPathWalker.
     */
    public AncestorOrSelfWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
  
    /**
     * Push the ancestor nodes.
     */
    protected void pushAncestors(Node n)
    {
      m_ancestors = new Stack();
      m_ancestors.push(n);
      DOMHelper dh = m_lpi.getDOMHelper();
      while(null != (n = dh.getParentOfNode(n)))
        m_ancestors.push(n);
      m_nextLevelAmount = m_ancestors.isEmpty() ? 0 : 1;
    }
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return m_lpi.getDOMHelper().getLevel(m_root);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/AncestorWalker.java
  
  Index: AncestorWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import java.util.Stack;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.DOMHelper;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'ancestor' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class AncestorWalker extends ReverseAxesWalker
  {
    /**
     * Construct an AncestorWalker using a LocPathWalker.
     */
    public AncestorWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
      
    /**
     * Push the ancestor nodes.
     */
    protected void pushAncestors(Node n)
    {
      m_ancestors = new Stack();
      DOMHelper dh = m_lpi.getDOMHelper();
      while(null != (n = dh.getParentOfNode(n)))
        m_ancestors.push(n);
      m_nextLevelAmount = m_ancestors.isEmpty() ? 0 : 1;
    }
    
    /**
     *  The root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      pushAncestors(root);
      super.setRoot(root);
    }
  
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      Node next = m_ancestors.isEmpty() ? null : (Node)m_ancestors.pop();
      m_nextLevelAmount = m_ancestors.isEmpty() ? 0 : 1;
      return setCurrentIfNotNull(next);
    }
    
    protected Stack m_ancestors;
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      DOMHelper dh = m_lpi.getDOMHelper();
      Node p = dh.getParentOfNode(m_root);
      
      return (null == p) ? 1 : dh.getLevel(p);
    }
  
  
  }
    
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/AttributeWalker.java
  
  Index: AttributeWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  import org.w3c.dom.NamedNodeMap;
  
  /**
   * Walker for the 'attribute' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class AttributeWalker extends AxesWalker
  {
    /**
     * Construct an AttributeWalker using a LocPathWalker.
     */
    public AttributeWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
    
    /**
     *  The root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      m_attrListPos = -1;
      m_attributeList = null;
      m_nAttrs = -2;
      m_nextLevelAmount = 1;
      super.setRoot(root);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      if(m_currentNode.getNodeType() == Node.ELEMENT_NODE)
      {
        m_attrListPos = -1;
        m_attributeList = m_currentNode.getAttributes();
        if(null != m_attributeList)
          m_nAttrs = m_attributeList.getLength();
        else
          m_nAttrs = -2;
      }
      m_nextLevelAmount = 0;
      return nextSibling();
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      // Attributes don't really have siblings, but we'll fake it.
      if(null != m_attributeList)
      {
        m_attrListPos++;
        if(m_attrListPos < m_nAttrs)
        {
          return setCurrentIfNotNull(m_attributeList.item(m_attrListPos));
        }
        else
          m_attributeList = null;
      }
      return null; 
    }
    
    NamedNodeMap m_attributeList;
    int m_attrListPos;
    int m_nAttrs;
      
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return m_lpi.getDOMHelper().getLevel(m_root);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/AxesWalker.java
  
  Index: AxesWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import java.util.Stack;
  
  // Xalan imports
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.OpCodes;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.DOMHelper;
  
  import org.apache.xalan.utils.PrefixResolver;
  
  // DOM2 imports
  import org.w3c.dom.Node;
  import org.w3c.dom.NamedNodeMap;
  
  import org.w3c.dom.traversal.TreeWalker;
  import org.w3c.dom.traversal.NodeFilter;
  import org.w3c.dom.DOMException;
  
  /**
   * Serves as common interface for axes Walkers, and stores common 
   * state variables.
   */
  public abstract class AxesWalker 
    implements Cloneable, TreeWalker, NodeFilter
  {
    protected LocPathIterator m_lpi;
    public LocPathIterator getLocPathIterator() { return m_lpi; }
    public void setLocPathIterator(LocPathIterator li) { m_lpi = li; }
    
    /**
     * Construct an AxesWalker using a LocPathIterator.
     */
    public AxesWalker(LocPathIterator locPathIterator)
    {
      m_lpi = locPathIterator;
    }
    
    /**
     * Init an AxesWalker.  This must be called before the path 
     * is executed.  I do this instead of a constructor, so I 
     * can use the default constructor, so I don't have to do 
     * constructors on the derived classes.
     * @param opPos The op position of the axes step in the XPath.
     * @param stepType The axes type.
     */
    public void init(int opPos, int stepType)
    {
      m_opPos = opPos;
      XPath xpath = m_lpi.getXPath();
      m_nodeTestOpPos = xpath.getFirstChildPosOfStep(m_opPos);
      m_stepType = stepType;
      m_argLen = xpath.getArgLengthOfStep(opPos);
      initPredicateInfo();
      
      int testType = xpath.getOp(m_nodeTestOpPos);
      switch(testType)
      {
      case OpCodes.NODETYPE_COMMENT:
        m_whatToShow = NodeFilter.SHOW_COMMENT;
        break;
      case OpCodes.NODETYPE_TEXT:
        m_whatToShow = NodeFilter.SHOW_TEXT;
        break;
      case OpCodes.NODETYPE_PI:
        m_whatToShow = NodeFilter.SHOW_PROCESSING_INSTRUCTION;
        break;
      case OpCodes.NODETYPE_NODE:
        m_whatToShow = NodeFilter.SHOW_ALL;
        break;
      case OpCodes.NODETYPE_ROOT:
        m_whatToShow = NodeFilter.SHOW_DOCUMENT;
        break;
      case OpCodes.NODENAME:
        m_whatToShow = NodeFilter.SHOW_ELEMENT | 
                       NodeFilter.SHOW_ATTRIBUTE |
                       NodeFilter.SHOW_PROCESSING_INSTRUCTION;
        break;
      default:
        m_whatToShow = NodeFilter.SHOW_ALL;
      }
  
    }
    
    /**
     * Get a cloned AxesWalker.
     */
    public Object clone()
      throws CloneNotSupportedException
    {
      AxesWalker clone = (AxesWalker)super.clone();
  
      if((null != this.m_proximityPositions) && (this.m_proximityPositions == 
clone.m_proximityPositions))
      {
        clone.m_proximityPositions = new int[this.m_proximityPositions.length];
        System.arraycopy(this.m_proximityPositions, 0, 
clone.m_proximityPositions, 0, this.m_proximityPositions.length);
      }
      return clone;
    }
    
    /**
     * Create the proper Walker from the axes type.
     */
    public static AxesWalker createDefaultWalker(int stepType, LocPathIterator 
lpi)
    {
      AxesWalker ai;
      switch(stepType)
      {
      case OpCodes.OP_VARIABLE:
      case OpCodes.OP_EXTFUNCTION:
      case OpCodes.OP_FUNCTION:
      case OpCodes.OP_GROUP:
        ai = new FilterExprWalker(lpi);
        break;
      case OpCodes.FROM_ROOT: ai = new RootWalker(lpi); break;
      case OpCodes.FROM_ANCESTORS: ai = new AncestorWalker(lpi); break;
      case OpCodes.FROM_ANCESTORS_OR_SELF: ai = new AncestorOrSelfWalker(lpi); 
break;
      case OpCodes.FROM_ATTRIBUTES: ai = new AttributeWalker(lpi); break;
      case OpCodes.FROM_NAMESPACE: ai = new NamespaceWalker(lpi); break;
      case OpCodes.FROM_CHILDREN: ai = new ChildWalker(lpi);  break;
      case OpCodes.FROM_DESCENDANTS: ai = new DescendantWalker(lpi); break;
      case OpCodes.FROM_DESCENDANTS_OR_SELF: ai = new 
DescendantOrSelfWalker(lpi); break;
      case OpCodes.FROM_FOLLOWING: ai = new FollowingWalker(lpi); break;
      case OpCodes.FROM_FOLLOWING_SIBLINGS: ai = new 
FollowingSiblingWalker(lpi); break;
      case OpCodes.FROM_PRECEDING: ai = new PrecedingWalker(lpi); break;
      case OpCodes.FROM_PRECEDING_SIBLINGS: ai = new 
PrecedingSiblingWalker(lpi); break;
      case OpCodes.FROM_PARENT: ai = new ParentWalker(lpi); break;
      case OpCodes.FROM_SELF: ai = new SelfWalker(lpi); break;
  
      case OpCodes.MATCH_ATTRIBUTE: ai = new AttributeWalker(lpi); break;
      case OpCodes.MATCH_ANY_ANCESTOR: ai = new ChildWalker(lpi); break;
      case OpCodes.MATCH_IMMEDIATE_ANCESTOR: ai = new ChildWalker(lpi); break;
      default: 
                                             throw new 
RuntimeException("Programmer's assertion: unknown opcode: "+stepType);
      }
      return ai;
    }
    
    /**
     * Reset the Walker.
     */
    public void reset()
    {
      setCurrentNode(m_root);
    }
    
    /**
     * The op position of the XPath step. 
     * Does not change after the constructor.
     */
    public int getOpPos() { return m_opPos; }
    public void setOpPos(int opPos) { m_opPos = opPos; }
    private int m_opPos;
  
    /**
     * The op position of the XPath step. 
     * Does not change after the constructor.
     */
    private int m_nodeTestOpPos;
    protected int getNodeTestOpPos() { return m_nodeTestOpPos; }
  
    /**
     * The step type of the XPath step. Does not change after the constructor.
     */
    private int m_stepType;
    protected int getStepType() { return m_stepType; }
    
    /**
     * The arg length of the XPath step. Does not change after the constructor.
     */
    private int m_argLen;
    protected int getArgLen() { return m_argLen; }
            
    /**
     * An array of counts that correspond to the number 
     * of predicates the step contains.
     */
    protected int[] m_proximityPositions;
    
    /**
     * Get the current sub-context position.
     */
    public int getProximityPosition()
    {
      // System.out.println("getProximityPosition - m_predicateIndex: 
"+m_predicateIndex);
      return (m_predicateIndex >= 0) ?
             m_proximityPositions[m_predicateIndex] : 0;
    }
    
    /**
     * Get the current sub-context position.
     */
    protected int getProximityPosition(int predicateIndex)
    {
      return m_proximityPositions[predicateIndex];
    }
    
    /**
     * Reset the proximity positions counts.
     */
    public void resetProximityPositions()
      throws org.xml.sax.SAXException
    {
      if(m_predicateCount > 0)
      {
        m_proximityPositions = new int[m_predicateCount];
        int opPos = m_posOfPredicate;
        XPath xpath = m_lpi.getXPath();
        for(int i = 0; i < m_predicateCount; i++)
        {
          initProximityPosition(i, opPos);
          opPos = xpath.getNextOpPos(opPos);
        }
      }
    }
    
    /**
     * Init the proximity position to zero for a forward axes.
     */
    public void initProximityPosition(int i, int posOfPredicateOpCode)
      throws org.xml.sax.SAXException
    {
      m_proximityPositions[i] = 0;
    }
  
    /**
     * Count forward one proximity position.
     */
    protected void countProximityPosition(int i)
    {
      if(i < m_proximityPositions.length)
        m_proximityPositions[i]++;
    }
    
    /**
     * Tells if this is a reverse axes.
     */
    public boolean isReverseAxes()
    {
      return false;
    }
    
    /**
     * Which predicate we are executing.
     */
    int m_predicateIndex = -1;
    
    /**
     * Get which predicate is executing.  Returns 
     * -1 if no predicate is executing.
     */
    public int getPredicateIndex()
    {
      return m_predicateIndex;
    }
    
    /**
     * Count the number of predicates in the step.
     */
    int countPredicates(XPath xpath, int opPos)
    {
      int count = 0;
      while(OpCodes.OP_PREDICATE == xpath.getOp(opPos))
      {
        count++;
        opPos = xpath.getNextOpPos(opPos);
      }
      return count;
    }
    
    /**
     * Process the predicates.
     */
    boolean predicate(Node context, XPath xpath, XPathContext xctxt, 
                      int opPos)
      throws org.xml.sax.SAXException
    {    
      m_predicateIndex = 0;
      int nPredicates = m_predicateCount;
      for(int i = 0; i < nPredicates; i++)
      {
        PrefixResolver savedResolver = xctxt.getNamespaceContext();
        int savedStackframeIndex = 
xctxt.getVarStack().getCurrentStackFrameIndex();
        xctxt.pushTreeWalkerContext(this);
        XObject pred;
        try
        {
          
xctxt.getVarStack().setCurrentStackFrameIndex(m_lpi.getStackFrameIndex());
          xctxt.setNamespaceContext(m_lpi.getPrefixResolver());
          pred = xpath.predicate(xctxt, context, opPos);
        }
        finally
        {
          xctxt.setNamespaceContext(savedResolver);
          xctxt.popTreeWalkerContext();
          xctxt.getVarStack().setCurrentStackFrameIndex(savedStackframeIndex);
        }
        if(XObject.CLASS_NUMBER == pred.getType())
        {
          if(this.getProximityPosition(m_predicateIndex) != (int)pred.num())
          {
            return false;
          }
        }
        else if(!pred.bool())
          return false;
        
        countProximityPosition(++m_predicateIndex);
        opPos = xpath.getNextOpPos(opPos);
      }
      m_predicateIndex = -1;
      return true;
    }
    
    /**
     * The op position where the predicates start.
     */
    protected int m_posOfPredicate;
    
    /**
     * Number of predicates (in effect).
     */
    int m_predicateCount;
    
    /**
     * Get the number of predicates that this walker has.
     */
    public int getPredicateCount()
    {
      return m_predicateCount;
    }
    
    /**
     * Set the number of predicates that this walker has.
     */
    public void setPredicateCount(int count)
    {
      m_predicateCount = count;
    }
    
    /**
     * Init predicate info.
     */
    private void initPredicateInfo()
    {
      XPath xpath = m_lpi.getXPath();
      m_posOfPredicate = xpath.getFirstPredicateOpPos(m_opPos);
      m_predicateCount = countPredicates(xpath, m_posOfPredicate);
    }
        
    /**
     * Tell if the given node is a parent of the 
     * step context, or the step context node itself.
     */
    boolean isAncestorOfRootContext(Node n)
    {
      Node parent = m_root;
      while(null != (parent = parent.getParentNode()))
      {
        if(parent.equals( n ))
          return true;
      }
      return false;
    }
    
    //=============== TreeWalker Implementation ===============
    
    /**
     *  The root node of the TreeWalker, as specified when it was created.
     */
    Node m_root;
      
    /**
     * The root node of the TreeWalker, as specified in setRoot(Node root).
     * Note that this may actually be below the current node.
     */
    public Node getRoot()
    {
      return m_root;
    }
    
    boolean m_isFresh;
  
    /**
     * Set the root node of the TreeWalker.
     * (Not part of the DOM2 TreeWalker interface).
     */
    public void setRoot(Node root)
    {
      m_isFresh = true;
      m_root = root;
      m_currentNode = root;
      m_prevReturned = null;
      if(null == root)
        System.out.print("\n !!!! Warning! Setting the root to null!!!");
      try
      {
        resetProximityPositions();
      }
      catch(org.xml.sax.SAXException se)
      {
        // TODO: Fix this...
        throw new RuntimeException(se.getMessage());
      }
    }
    
    /**
     *  The node at which the TreeWalker is currently positioned.
     */
    Node m_currentNode;
  
    /**
     * The node at which the TreeWalker is currently positioned.
     * <br> The value must not be null. Alterations to the DOM tree may cause 
     * the current node to no longer be accepted by the TreeWalker's 
     * associated filter. currentNode may also be explicitly set to any node, 
     * whether or not it is within the subtree specified by the root node or 
     * would be accepted by the filter and whatToShow flags. Further 
     * traversal occurs relative to currentNode even if it is not part of the 
     * current view by applying the filters in the requested direction (not 
     * changing currentNode where no traversal is possible). 
     * @exception DOMException
     *    NOT_SUPPORTED_ERR: Raised if the specified <code>currentNode</code> 
     *   is<code>null</code> .
     */
    public Node getCurrentNode()
    { 
      return m_currentNode; 
    }
    
    /**
     * Set the current node.
     */
    public void setCurrentNode(Node currentNode)
      throws DOMException
    { 
      m_currentNode = currentNode; 
    }
    
    /**
     * Set the current node if it's not null.
     * @return The node passed in.
     */
    protected Node setCurrentIfNotNull(Node currentNode)
      throws DOMException
    { 
      if(null != currentNode)
        m_currentNode = currentNode; 
      return currentNode;
    }
    
    /**
     * This attribute determines which node types are presented via the 
     * TreeWalker.
     * Does not change after the constructor.
     */
    private int m_whatToShow;
  
    /**
     *  This attribute determines which node types are presented via the 
     * TreeWalker. These constants are defined in the <code>NodeFilter</code> 
     * interface.
     */
    public int getWhatToShow()
    {
      return m_whatToShow;
    }
  
    /**
     *  The filter used to screen nodes.
     */
    public NodeFilter getFilter()
    {
      return this;
    }
  
    /**
     *  The value of this flag determines whether the children of entity 
     * reference nodes are visible to the TreeWalker. If false, they will be 
     * skipped over.
     * <br> To produce a view of the document that has entity references 
     * expanded and does not expose the entity reference node itself, use the 
     * whatToShow flags to hide the entity reference node and set 
     * expandEntityReferences to true when creating the TreeWalker. To 
     * produce a view of the document that has entity reference nodes but no 
     * entity expansion, use the whatToShow flags to show the entity 
     * reference node and set expandEntityReferences to false.
     */
    public boolean getExpandEntityReferences()
    {
      return true;
    }
        
    /**
     *  Moves to and returns the closest visible ancestor node of the current 
     * node. If the search for parentNode attempts to step upward from the 
     * TreeWalker's root node, or if it fails to find a visible ancestor 
     * node, this method retains the current position and returns null.
     * @return  The new parent node, or null if the current node has no parent 
     *   in the TreeWalker's logical view.
     */
    public Node parentNode()
    {
      return null;
    }
  
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      return null;
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      return null;
    }
  
    /**
     *  Moves the <code>TreeWalker</code> to the last visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   children  in the TreeWalker's logical view.
     */
    public Node lastChild()
    {
      // We may need to support this...
      throw new RuntimeException("lastChild not supported!");
    }
  
    /**
     *  Moves the <code>TreeWalker</code> to the previous sibling of the 
     * current node, and returns the new node. If the current node has no 
     * visible previous sibling, returns <code>null</code> , and retains the 
     * current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   previous sibling in the TreeWalker's logical view.
     */
    public Node previousSibling()
    {
      throw new RuntimeException("previousSibling not supported!");
    }
  
    /**
     *  Moves the <code>TreeWalker</code> to the previous visible node in 
     * document order relative to the current node, and returns the new node. 
     * If the current node has no previous node,  or if the search for 
     * previousNode attempts to step upward from the TreeWalker's root node, 
     * returns <code>null</code> , and retains the current node. 
     * @return  The new node, or <code>null</code> if the current node has no 
     *   previous node in the TreeWalker's logical view.
     */
    public Node previousNode()
    {
      throw new RuntimeException("previousNode not supported!");
    }
    
    static boolean DEBUG_WAITING = false;
    static boolean DEBUG_TRAVERSAL = false;
    static boolean DEBUG_LOCATED = false;
    
    private AxesWalker m_nextWalker;
    
    public void setNextWalker(AxesWalker walker)
    {
      m_nextWalker = walker;
    }
  
    public AxesWalker getNextWalker()
    {
      return m_nextWalker;
    }
  
    AxesWalker m_prevWalker;
    
    public void setPrevWalker(AxesWalker walker)
    {
      m_prevWalker = walker;
    }
  
    public AxesWalker getPrevWalker()
    {
      return m_prevWalker;
    }
    
    /**
     * Diagnostics.
     */
    public String toString()
    {
      Class cl = this.getClass();
      String clName = cl.getName();
      java.util.StringTokenizer tokenizer 
        = new java.util.StringTokenizer(clName, ".");
      while(tokenizer.hasMoreTokens())
        clName = tokenizer.nextToken();
      String rootName = (null == m_root) 
                        ? "null" 
                          : m_root.getNodeName() 
                            + 
"{"+((org.apache.xalan.stree.Child)m_root).getUid()+"}";
      String currentNodeName = (null == m_root) 
                               ? "null" 
                                 : m_currentNode.getNodeName()
                                  + 
"{"+((org.apache.xalan.stree.Child)m_currentNode).getUid()+"}";
  
      return clName+this.m_opPos+"["+rootName+"]["+currentNodeName+"]";
    }
    
    /**
     * Diagnostics.
     */
    protected String nodeToString(Node n)
    {
      return (null != n) 
             ? n.getNodeName()+"{"+ ((org.apache.xalan.stree.Child)n).getUid() 
+ "}"
               : "null";
    }
      
    /**
     * Diagnostics.
     */
    private Node returnNextNode(Node n)
    {
      if(DEBUG_LOCATED && (null != n))
      {
        printDebug("RETURN --->"+nodeToString(n));
      }
      else
      {
        printDebug("RETURN --->null");
      }
      return n;
    }
    
    /**
     * Diagnostics.
     */
    private void printDebug(String s)
    {
      if(DEBUG_TRAVERSAL)
      {
        System.out.print("\n");
        if(null != m_currentNode)
        {
          org.apache.xalan.stree.Child n = 
((org.apache.xalan.stree.Child)m_currentNode);
          int depth = n.getLevel();
          for(int i = 0; i < depth; i++)
            System.out.print(" ");
        }
        System.out.print(s);
      }
    }
    
    /**
     * Do a diagnostics dump of the entire document.
     */
    private void dumpAll(Node node, int indent)
    {
      for(int i = 0; i < indent; i++)
        System.out.print(" ");
  
      System.out.print(nodeToString(node));
      if(Node.TEXT_NODE == node.getNodeType())
      {
        String value = node.getNodeValue();
        if(null != value)
        {
          System.out.print("+= -->"+value.trim());
        }
      }
      System.out.println("");
      NamedNodeMap map = node.getAttributes();
      if(null != map)
      {
        int n = map.getLength();
        for(int i = 0; i < n; i++)
        {
          for(int k = 0; k < indent; k++)
            System.out.print(" ");
          System.out.print("attr -->");
          System.out.print(nodeToString(map.item(i)));
          String value = map.item(i).getNodeValue();
          if(null != value)
          {
            System.out.print("+= -->"+value.trim());
          }
          System.out.println("");
        }
      }
      Node child = node.getFirstChild();
      while(null != child)
      {
        dumpAll(child, indent+1);
        child = child.getNextSibling();
      }
    }
  
    /**
     * Diagnostics.
     */
    private void printDebugAdd(String s)
    {
      if(DEBUG_TRAVERSAL)
      {
        System.out.print("; "+s);
      }
    }
  
    /**
     * Diagnostics.
     */
    private void printEntryDebug()
    {
      if(true && DEBUG_TRAVERSAL)
      {
        System.out.print("\n============================\n");
        if(null != m_currentNode)
        {
          org.apache.xalan.stree.Child n = 
((org.apache.xalan.stree.Child)m_currentNode);
          int depth = n.getLevel();
          for(int i = 0; i < depth; i++)
            System.out.print("+");
        }
        System.out.print(" "+this.toString()+", 
"+nodeToString(this.m_currentNode));
        printWaiters();
      }
    }
    
    /**
     * Diagnostics.
     */
    private void printWaiters()
    {
      if(DEBUG_WAITING)
      {
        int nWaiting = m_lpi.m_waiting.size();
        for(int i = 0; i < nWaiting; i++)
        { 
          AxesWalker ws = (AxesWalker)m_lpi.m_waiting.elementAt(i);
          printDebug("["+ws.toString()
                     +" WAITING... ]");
        }
        printDebug("Waiting count: "+nWaiting);
      }
    }
    
    // short-lived flag.
    private boolean m_waitingForNext = false;
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return 0;
    }
    
    protected int m_nextLevelAmount;
    
    /**
     * Tell what's the next level this axes can descend to.
     */
    protected int getNextLevelAmount()
    {
      return m_nextLevelAmount;
    }
    
    /**
     * Tell if it's OK to traverse to the next node, following document 
     * order, or if the walker should wait for a condition to occur.
     * @prevStepWalker The previous walker in the location path.
     * @testWalker The walker being tested, but the state may not be intact, 
     * so only static information can be obtained from it.
     */
    protected boolean checkOKToTraverse(AxesWalker prevStepWalker, 
                                        AxesWalker testWalker, 
                                        Node currentTestNode,
                                        int nextLevelAmount)
    {
      DOMHelper dh = m_lpi.getDOMHelper();
      
      int level = dh.getLevel(currentTestNode);
      
      // Is this always the context node of the test walker?
      Node prevNode = prevStepWalker.m_currentNode;
  
      // Can the previous walker go past the one being tested?
      if(DEBUG_WAITING)
        printDebug("[prevStepWalker.getLevelMax():"+prevStepWalker.getLevelMax()
                   +" > level:"+level+"?]");
      boolean ok;
      if(!prevStepWalker.m_isDone && prevStepWalker.getLevelMax() > level) 
      {
        // Is (prevStepWalker.m_currentNode > the currentTestNode)?
        // (Sorry about the reverse logic).
        boolean isNodeAfter 
          = !dh.isNodeAfter(prevNode, currentTestNode);
        if(DEBUG_WAITING)
          printDebug("[isNodeAfter:"+isNodeAfter+"?]");
        if(isNodeAfter)
        {
          int prevStepLevel = dh.getLevel(prevNode);
          // If the previous step walker is below us in the tree, 
          // then we have to wait until it pops back up to our level, 
          // (if it ever does).
          if(DEBUG_WAITING)
            printDebug("[prevStepLevel:"+prevStepLevel
                       +" <= 
(level:"+level+"+nextLevelAmount:"+nextLevelAmount+"):"+(level+nextLevelAmount)+"?]");
          if(prevStepLevel > (level+nextLevelAmount))
          {
            // if next step is down, then ok = true, else
            // if next step is horizontal, then we have to wait.
            ok = false;
          }
          else
            ok = true;
        }
        else
          ok = false;
      }
      else
        ok = true;
      if(DEBUG_WAITING)
        printDebug("checkOKToTraverse = "+ok);
      
      return ok;
    }
      
    private boolean m_didSwitch = false;
    
    /**
     * Check if any walkers need to fire before the given walker.  If they 
     * do, then the given walker will be put on the waiting list, and the 
     * waiting walker will be returned.
     * @param walker The walker that is about to call nextNode(), or null.
     * @return walker argument or new walker.
     */
    AxesWalker checkWaiting(AxesWalker walker)
    {
      // printDebug("checkWaiting: "+walker.toString()+", 
"+nodeToString(walker.m_currentNode));
      if((null != walker) && (null == walker.m_currentNode))
        return walker;
      
      int nWaiting = m_lpi.m_waiting.size();
      for(int i = 0; i < nWaiting; i++)
      { 
        AxesWalker ws = (AxesWalker)m_lpi.m_waiting.elementAt(i);
        AxesWalker prevStepWalker = ws.m_prevWalker;
        if(null != prevStepWalker)
        {
          if(DEBUG_WAITING)
            printDebug("Calling 
checkOKToTraverse("+prevStepWalker.toString()+", "+
                       ws.toString()+", .);");
  
          if(checkOKToTraverse(prevStepWalker, ws, 
                                        ws.m_currentNode, ws.m_nextLevelAmount))
          {
            if(null != walker)
            {
              AxesWalker deferedWalker = walker;
              
              if(DEBUG_WAITING)
                printDebug("[Moving "+deferedWalker.toString()
                           +", "+nodeToString(deferedWalker.m_currentNode)+" to 
WAITING list]");
              if(!isWaiting(deferedWalker))
                m_lpi.addToWaitList(deferedWalker);
            }
  
            walker = ws;
            m_lpi.removeFromWaitList(walker);
            if(DEBUG_WAITING)
              printDebug("[And using WAITING on "+ws.toString());
            
            walker.printEntryDebug();
            m_didSwitch = true;
            break;
          }
        }
      }
              
      return walker;
    }
    
    /**
     * We have to do something to get things moving along, 
     * so get the earliest (in doc order) waiter.
     */
    private AxesWalker getEarliestWaiting()
    {
      DOMHelper dh = m_lpi.getDOMHelper();
      AxesWalker first = null;
      int nWaiting = m_lpi.m_waiting.size();
      for(int i = 0; i < nWaiting; i++)
      {
        AxesWalker ws = (AxesWalker)m_lpi.m_waiting.elementAt(i);
        if(first == null)
          first = ws;
        else
        {
          if(!dh.isNodeAfter(ws.m_currentNode, first.m_currentNode))
            first = ws;
        }
      }
      if(null != first)
      {
        m_lpi.removeFromWaitList(first);
        if(DEBUG_WAITING)
          printDebug("[(getEarliestWaiting)Using WAITING on "+first.toString());
        
        first.printEntryDebug();
      }
      return first;
    }
    
    /**
     * Tell if the given walker is already on the waiting list.
     */
    boolean isWaiting(AxesWalker walker)
    {
      int nWaiting = m_lpi.m_waiting.size();
      for(int i = 0; i < nWaiting; i++)
      { 
        AxesWalker ws = (AxesWalker)m_lpi.m_waiting.elementAt(i);
        if(ws == walker)
          return true;
      }
      return false;
    }
    
    /**
     * Check if a given walker needs to wait for the previous walker to 
     * catch up.
     */
    AxesWalker checkNeedsToWait(AxesWalker walker)
    {
      AxesWalker prevWalker = walker.m_prevWalker;
      if(null != prevWalker)
      {
        printDebug("Calling checkOKToTraverse("+prevWalker.toString()+", "+
                   walker.toString()+", .);");
        if(!checkOKToTraverse(prevWalker, walker, 
                             walker.m_currentNode, walker.m_nextLevelAmount))
        {
          printDebug("[Adding "+walker.toString()+" to WAITING list");
          if(isWaiting(walker))
          {
            try
            {
              printDebug("checkNeedsToWait.clone: "+walker.toString());
              m_lpi.addToWaitList((AxesWalker)walker.clone());
            }
            catch(CloneNotSupportedException cnse)
            {
            }
          }
          else
            m_lpi.addToWaitList(walker);
          walker = walker.m_prevWalker;
          walker.printEntryDebug();
        }
      }
      return walker;
    }
    
    boolean m_isDone = false;
    
    /**
     * Get the next node in document order on the axes.
     */
    protected Node getNextNode()
    {
      if(m_isFresh)
        m_isFresh = false;
      Node next = this.firstChild();
  
      while(null == next)
      {     
        next = this.nextSibling();
        
        if(null == next)
        {
          Node p = this.parentNode();
          if(null == p)
            break;
        }
      }
      if(null == next)
        this.m_isDone = true;
      return next;
    }
    
    Node m_prevReturned;
    
    static boolean m_didDumpAll = false;
  
    /**
     *  Moves the <code>TreeWalker</code> to the next visible node in document 
     * order relative to the current node, and returns the new node. If the 
     * current node has no next node,  or if the search for nextNode attempts 
     * to step upward from the TreeWalker's root node, returns 
     * <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next node  in the TreeWalker's logical view.
     */
    public Node nextNode()
    {
      if(DEBUG_TRAVERSAL && !m_didDumpAll)
      {
        m_didDumpAll = true;
        Node doc = (Node.DOCUMENT_NODE == m_root.getNodeType()) ? m_root : 
m_root.getOwnerDocument();
        dumpAll(doc, 0);
      }
      
      Node nextNode = null;
      AxesWalker walker = m_lpi.getLastUsedWalker();
      // DOMHelper dh = m_lpi.getDOMHelper();
      walker.printEntryDebug();
      m_didSwitch = false;
      boolean processWaiters = true;
  
      do
      {
        while(true)
        {
          // Check to see if there's any walkers that need to execute first.
          if(processWaiters)
          {
            AxesWalker waiting = checkWaiting(walker);
            if(m_didSwitch)
            {
              m_didSwitch = false;
              walker = waiting;
            }
            else if(null != walker)
            {
              waiting = checkNeedsToWait(walker);
              if(waiting != walker)
              {
                walker = waiting;
                continue;
              }
            }
          }
          else
            processWaiters = true;
          
          if(null == walker)
            break;
          
          nextNode = walker.getNextNode();
          
          if(DEBUG_TRAVERSAL)
          {
            
walker.printDebug(walker.toString()+"--NEXT->"+nodeToString(nextNode)+")");
          }
          
          if(null == nextNode)
          {
            AxesWalker prev = walker;
            walker = walker.m_prevWalker;
            if(null != walker)
              walker.printEntryDebug();
            else
            {
              walker = getEarliestWaiting();
              if(null != walker)
              {
                processWaiters = false;
                continue;
              }
            }
          }
          else
          {
            if(walker.acceptNode(nextNode) != NodeFilter.FILTER_ACCEPT)
            {
              printDebugAdd("[FILTER_SKIP]");
              continue;
            }
            else
            {
              printDebugAdd("[FILTER_ACCEPT]");
            }
            
            if(null == walker.m_nextWalker)
            {
              // walker.pushState();
              printDebug("May be returning: "+nodeToString(nextNode));
              if(null != m_prevReturned)
                printDebugAdd(", m_prevReturned: 
"+nodeToString(m_prevReturned));
              
              m_lpi.setLastUsedWalker(walker);
              // return walker.returnNextNode(nextNode);
              break;
            }
            else
            {
              AxesWalker prev = walker;
              walker = walker.m_nextWalker;
              /*
              if((walker.getRoot() != null) &&
                 prev.getLevelMax() >= walker.getLevelMax()) // bogus, but 
might be ok
              */
              if(isWaiting(walker))
              {
                try
                {
                  walker = (AxesWalker)walker.clone();
                  // walker.pushState();
                  walker.setRoot(nextNode);
                  printDebug("clone: "+walker.toString());
                }
                catch(CloneNotSupportedException cnse)
                {
                }
              }
              else
              {
                walker.setRoot(nextNode);
              }
              walker.m_prevWalker = prev;
              walker.printEntryDebug();
  
              continue;
            }
          } // if(null != nextNode)
          
        } // while(null != walker)
        
      }
        while((null != nextNode) && (null != m_prevReturned)
              && m_lpi.getDOMHelper().isNodeAfter(nextNode, m_prevReturned));
      
      m_prevReturned = nextNode;
      return returnNextNode(nextNode);
    }
    
    //============= End TreeWalker Implementation =============
    
    public int getLastPos()
    {
      int pos = getProximityPosition();
      AxesWalker walker;
      try
      {
        walker = (AxesWalker)clone();
      }
      catch(CloneNotSupportedException cnse)
      {
        return -1;
      }
      walker.setPredicateCount(walker.getPredicateCount() - 1);
      walker.setNextWalker(null);
      walker.setPrevWalker(null);
      LocPathIterator lpi = walker.getLocPathIterator();
      AxesWalker savedWalker = lpi.getLastUsedWalker();
      try
      {
        lpi.setLastUsedWalker(walker);
        Node next;
        while (null != (next = walker.nextNode()))
          pos++;
        // TODO: Should probably save this in the iterator.
      }
      finally
      {
        lpi.setLastUsedWalker(savedWalker);
      }
      return pos;
    }
  
    //=============== NodeFilter Implementation ===============
    
    /**
     *  Test whether a specified node is visible in the logical view of a 
     * TreeWalker or NodeIterator. This function will be called by the 
     * implementation of TreeWalker and NodeIterator; it is not intended to 
     * be called directly from user code.
     * @param n  The node to check to see if it passes the filter or not.
     * @return  a constant to determine whether the node is accepted, 
     *   rejected, or skipped, as defined  above .
     */
    public short acceptNode(Node n)
    {
      try
      {
        if( 0 == (getWhatToShow() & (0x00000001 << (n.getNodeType()-1))))
          return NodeFilter.FILTER_SKIP;
        
        if(XPath.MATCH_SCORE_NONE 
           != m_lpi.getLocator().nodeTest(m_lpi.getXPath(), 
m_lpi.getXPathContext(), 
                                          n, m_nodeTestOpPos, 
                                          getArgLen(), getStepType()))
        {                    
          if(m_predicateCount > 0)
          {
            countProximityPosition(0);
            
            if(!predicate(n, m_lpi.getXPath(), m_lpi.getXPathContext(), 
                          m_posOfPredicate))
              return NodeFilter.FILTER_SKIP;
          }
          
          return NodeFilter.FILTER_ACCEPT;
        }
      }
      catch(org.xml.sax.SAXException se)
      {
        // TODO: Fix this.
        throw new RuntimeException(se.getMessage());
      }
      return NodeFilter.FILTER_SKIP;
    }
  
    
    //============= End NodeFilter Implementation =============
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/ChildWalker.java
  
  Index: ChildWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'child' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class ChildWalker extends AxesWalker
  {    
    /**
     * Construct an ChildWalker using a LocPathIterator.
     */
    public ChildWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
    
    /**
     *  The root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      m_nextLevelAmount = root.hasChildNodes() ? 1 : 0;
      super.setRoot(root);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      m_nextLevelAmount = 0;
      if(m_root == m_currentNode)
      {
        return setCurrentIfNotNull(this.m_root.getFirstChild());
      }
      else 
        return null;
    }
      
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      if(m_root != m_currentNode)
        return setCurrentIfNotNull(m_currentNode.getNextSibling());
      else 
        return null;
    }
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return m_lpi.getDOMHelper().getLevel(m_root);
    }
  
  
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/DescendantOrSelfWalker.java
  
  Index: DescendantOrSelfWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'descendant-or-self' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class DescendantOrSelfWalker extends DescendantWalker
  {
    /**
     * Construct a DescendantOrSelfWalker using a LocPathIterator.
     */
    public DescendantOrSelfWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
  
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      m_processedSelf = false;
      super.setRoot(root);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      // Follow my made-up rule about returning the self node as a child.
      // (only in this case, it isn't the self).
      if(!m_processedSelf)
      {
        m_processedSelf = true;
        return setCurrentIfNotNull(m_root);
      }
      return super.firstChild();
    }
        
    boolean m_processedSelf;  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/DescendantWalker.java
  
  Index: DescendantWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'descendant' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class DescendantWalker extends AxesWalker
  {
    /**
     * Construct an DescendantWalker using a LocPathIterator.
     */
    public DescendantWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
    
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      m_nextLevelAmount = root.hasChildNodes() ? 1 : 0;
      super.setRoot(root);
    }
  
    /**
     *  Moves to and returns the closest visible ancestor node of the current 
     * node. If the search for parentNode attempts to step upward from the 
     * TreeWalker's root node, or if it fails to find a visible ancestor 
     * node, this method retains the current position and returns null.
     * @return  The new parent node, or null if the current node has no parent 
     *   in the TreeWalker's logical view.
     */
    public Node parentNode()
    {
      Node n;
      if(m_root.equals(m_currentNode))
      {
        n = null;
      }
      else
      {
        Node p = m_currentNode.getParentNode();
        n = m_root.equals( p ) ? null : p;
      }
      m_nextLevelAmount = 0;
      return setCurrentIfNotNull(n);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      Node next = m_currentNode.getFirstChild();
      m_nextLevelAmount = (null == next) ? 0 : (next.hasChildNodes() ? 1 : 0);
      return setCurrentIfNotNull(next);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      Node next 
        = m_root.equals(m_currentNode) ? null : m_currentNode.getNextSibling();
      m_nextLevelAmount = (null == next) ? 0 : (next.hasChildNodes() ? 1 : 0);
      return setCurrentIfNotNull(next);
    }
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return Short.MAX_VALUE;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/FilterExprWalker.java
  
  Index: FilterExprWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.DOMHelper;
  import org.apache.xalan.utils.PrefixResolver;
  import java.util.Vector;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.traversal.NodeFilter;
  
  /**
   * Walker for the OP_VARIABLE, or OP_EXTFUNCTION, or OP_FUNCTION, or OP_GROUP,
   * op codes.
   * @see <a href="http://www.w3.org/TR/xpath#NT-FilterExpr";>XPath FilterExpr 
descriptions</a>
   */
  public class FilterExprWalker extends AxesWalker
  {
    /**
     * Construct a FilterExprWalker using a LocPathIterator.
     */
    public FilterExprWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
      
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      XPathContext xctxt = m_lpi.getXPathContext();
      PrefixResolver savedResolver = xctxt.getNamespaceContext();
      int savedStackframeIndex = 
xctxt.getVarStack().getCurrentStackFrameIndex();
      try
      {
        
xctxt.getVarStack().setCurrentStackFrameIndex(m_lpi.getStackFrameIndex());
        xctxt.setNamespaceContext(m_lpi.getPrefixResolver());
        XObject obj = m_lpi.getXPath().execute(m_lpi.getXPathContext(), 
                                               root, getOpPos());
        if(null != obj)
          m_nodeSet = obj.nodeset();
        else
          m_nodeSet = null;
        
        m_peek = null;
      }
      catch(org.xml.sax.SAXException se)
      {
        // TODO: Fix...
        throw new RuntimeException(se.getMessage());
      }
      finally
      {
        xctxt.getVarStack().setCurrentStackFrameIndex(savedStackframeIndex);
        xctxt.setNamespaceContext(savedResolver);
      }
      
      super.setRoot(root);
    }
    
    /**
     * Get a cloned FilterExprWalker.
     */
    public Object clone()
      throws CloneNotSupportedException
    {
      FilterExprWalker clone = (FilterExprWalker)super.clone();
      clone.m_nodeSet = (NodeIterator)((LocPathIterator)m_nodeSet).clone();
      return clone;
    }
    
    /**
     * This method needs to override AxesWalker.acceptNode because 
FilterExprWalkers 
     * don't need to, and shouldn't, do a node test.
     * @param n  The node to check to see if it passes the filter or not.
     * @return  a constant to determine whether the node is accepted, 
     *   rejected, or skipped, as defined  above .
     */
    public short acceptNode(Node n)
    {
      try
      {
        if(m_predicateCount > 0)
        {
          countProximityPosition(0);
          
          if(!predicate(n, m_lpi.getXPath(), m_lpi.getXPathContext(), 
                        m_posOfPredicate))
            return NodeFilter.FILTER_SKIP;
        }
        
        return NodeFilter.FILTER_ACCEPT;
      }
      catch(org.xml.sax.SAXException se)
      {
        // TODO: Fix this.
        throw new RuntimeException(se.getMessage());
      }
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the next visible node in document 
     * order relative to the current node, and returns the new node. If the 
     * current node has no next node,  or if the search for nextNode attempts 
     * to step upward from the TreeWalker's root node, returns 
     * <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next node  in the TreeWalker's logical view.
     */
    public Node getNextNode()
    {
      Node next;
      if(null != m_peek)
      {
        next = m_peek;
        m_peek = null;
      }
      else
      {
        next = (null != m_nodeSet) ? m_nodeSet.nextNode() : null;
      }
      
      // Bogus, I think, but probably OK for right now since a filterExpr 
      // can only occur at the head of a location path.
      if(null == next)
      {
        m_nextLevelAmount = 0;
      }
      else
      {
        m_nextLevelAmount = (next.hasChildNodes() ? 1 : 0);
        /* ...WAIT TO SEE IF WE REALLY NEED THIS...
        m_peek = m_nodeSet.nextNode();
        if(null == m_peek)
          m_nextLevelAmount = 0;
        else
        {
          DOMHelper dh = m_lpi.getDOMHelper();
          m_nextLevelAmount = dh.getLevel(m_peek) - dh.getLevel(next);
        }
        */
      }
      
      return setCurrentIfNotNull(next);
    }
    
    NodeIterator m_nodeSet;
    Node m_peek = null;
      
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      // TODO: Oh, this is going to be a hell of a lot of fun...
      // return Short.MAX_VALUE;
      return 1; // bogus, will probably screw things up.
      // return m_lpi.getDOMHelper().getLevel(this.m_currentNode)+1;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/FollowingSiblingWalker.java
  
  Index: FollowingSiblingWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'following-sibling' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class FollowingSiblingWalker extends AxesWalker
  {
    /**
     * Construct a FollowingSiblingWalker using a LocPathIterator.
     */
    public FollowingSiblingWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
      m_nextLevelAmount = 0;
    }
        
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      Node n = m_currentNode.getNextSibling();
      return setCurrentIfNotNull(n);
    }
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return m_lpi.getDOMHelper().getLevel(m_root);
    }
  
  }
  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/FollowingWalker.java
  
  Index: FollowingWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import java.util.Stack;
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.DOMHelper;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'following' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class FollowingWalker extends AxesWalker
  {
    /**
     * Construct a FollowingWalker using a LocPathIterator.
     */
    public FollowingWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
    
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      super.setRoot(root);
      m_currentAncestor = root;
      
      // Following is always moving up the tree, 
      // so I think this should be OK.
      m_nextLevelAmount = 0;
    }
    
    protected Stack m_ancestors = new Stack();
    
    
    /**
     *  Moves to and returns the closest visible ancestor node of the current 
     * node. If the search for parentNode attempts to step upward from the 
     * TreeWalker's root node, or if it fails to find a visible ancestor 
     * node, this method retains the current position and returns null.
     * @return  The new parent node, or null if the current node has no parent 
     *   in the TreeWalker's logical view.
     */
    public Node parentNode()
    {
      Node n;
      Node nextAncestor = (null != m_currentAncestor) 
                          ? m_currentAncestor.getParentNode() : null;
      Node nextParent = m_currentNode.getParentNode();
      if(nextParent == nextAncestor)
      {
        n = null;
        Node ancestor = m_currentAncestor;
        
        while((null != ancestor) && 
              (null != (ancestor = (Node)ancestor.getParentNode())))
        {
          n = ancestor.getNextSibling();
          if((null != n) || (null == ancestor))
            break;
        }
        m_currentAncestor = ancestor;
      }
      else
      {
        n = nextParent;
      }
      
      return setCurrentIfNotNull(n);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      Node n = (m_currentAncestor == m_currentNode) 
               ? m_currentNode.getNextSibling() 
                 : m_currentNode.getFirstChild();
  
      m_nextLevelAmount = (null == n) ? 0 : (n.hasChildNodes() ? 1 : 0);
      return setCurrentIfNotNull(n);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      Node n = m_currentNode.getNextSibling();
      m_nextLevelAmount = (null == n) ? 0 : (n.hasChildNodes() ? 1 : 0);
      return setCurrentIfNotNull(n);
    }
    
    Node m_currentAncestor;
      
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return Short.MAX_VALUE;
    }
  
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/NamespaceWalker.java
  
  Index: NamespaceWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import java.util.Stack;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  import org.w3c.dom.NamedNodeMap;
  
  /**
   * Walker for the 'namespace' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class NamespaceWalker extends AxesWalker
  {
    /**
     * Construct an NamespaceWalker using a LocPathIterator.
     */
    public NamespaceWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
    
    /**
     * Get a cloned AxesWalker.
     */
    public Object clone()
      throws CloneNotSupportedException
    {
      NamespaceWalker clone = (NamespaceWalker)super.clone();
  
      if(null != this.m_namespaces)
      {
        clone.m_namespaces = (Stack)this.m_namespaces.clone();
      }
      return clone;
    }
  
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      m_nextLevelAmount = 1;
      m_namespaces = new Stack();
      Node nsContext = root;
      
      while(null != nsContext)
      {      
        NamedNodeMap attributeList = nsContext.getAttributes();
        if(null != attributeList)
        {
          int nAttrs = attributeList.getLength();
          // System.out.println("setRoot - nAttrs: "+nAttrs);
          for(int i = (nAttrs-1); i >= 0; i--)
          {
            Node attr = attributeList.item(i);
            if(m_lpi.getDOMHelper().isNamespaceNode(attr))
            {
              // System.out.println("setRoot - pushing namespace: 
"+attr.getNodeName());
              m_namespaces.push(attr);
            }
          }
        }
        
        nsContext = nsContext.getParentNode();
      }
      
      super.setRoot(root);
      // System.out.println("============");
    }
          
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      m_nextLevelAmount = 0;
      return nextSibling();
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      Node next = m_namespaces.isEmpty() ? null : (Node)m_namespaces.pop();
      // System.out.println("nextSibling: "+this.nodeToString(next));
      return this.setCurrentIfNotNull(next);
    }
    
    Stack m_namespaces;
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return m_lpi.getDOMHelper().getLevel(m_root);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/ParentWalker.java
  
  Index: ParentWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'parent' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class ParentWalker extends AxesWalker
  {
    /**
     * Construct a ParentWalker using a LocPathIterator.
     */
    public ParentWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
  
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      m_gotParent = false;
      m_nextLevelAmount = 0;
      super.setRoot(root);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      // Follow rule about returning the first occuring in document order 
      // as the first child.  Strange but true.
      if(!m_gotParent)
      {
        m_gotParent = true;
        Node n = m_root.getParentNode();
        return setCurrentIfNotNull(n);
      }
      return null;
    }
      
    boolean m_gotParent;
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return m_lpi.getDOMHelper().getLevel(m_root)-1;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/PrecedingSiblingWalker.java
  
  Index: PrecedingSiblingWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'preceding-sibling' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class PrecedingSiblingWalker extends ReverseAxesWalker
  {
    /**
     * Construct a PrecedingSiblingWalker using a LocPathIterator.
     */
    public PrecedingSiblingWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
      m_nextLevelAmount = 0;
    }
  
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      Node next;
      if(m_currentNode == m_root)
      {
        Node parent = m_lpi.getDOMHelper().getParentOfNode(m_currentNode);
        if(null == parent)
          return null;
        next = parent.getFirstChild();
      }
      else
      {
        next = m_currentNode.getNextSibling();
      }
      if(next.equals(m_root))
        next = null;
      return setCurrentIfNotNull(next);
    }
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return m_lpi.getDOMHelper().getLevel(m_root);
    }
  
    
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/PrecedingWalker.java
  
  Index: PrecedingWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.DOMHelper;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'preceding' axes.
   * <p>The walk is done from the root node, in depth-first order, 
   * testing to see if a given vertice is an ancestor of the step 
   * context, in which case that vertice, and all following vertices, 
   * are skipped.</p>
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class PrecedingWalker extends ReverseAxesWalker
  {
    /**
     * Construct a PrecedingWalker using a LocPathIterator.
     */
    public PrecedingWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
        
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      super.setRoot(root);
      m_doc = m_lpi.getDOMHelper().getRootNode(root);
      m_currentNode = m_doc;
      m_nextLevelAmount = root.hasChildNodes() ? 1 : 0;
      try
      {
        super.resetProximityPositions();
      }
      catch(org.xml.sax.SAXException se)
      {
        // TODO: Fix this...
        throw new RuntimeException(se.getMessage());
      }
    }
    
    /**
     * Reset the proximity positions counts.
     */
    public void resetProximityPositions()
      throws org.xml.sax.SAXException
    {
    }
  
    
    /**
     *  Moves to and returns the closest visible ancestor node of the current 
     * node. If the search for parentNode attempts to step upward from the 
     * TreeWalker's root node, or if it fails to find a visible ancestor 
     * node, this method retains the current position and returns null.
     * @return  The new parent node, or null if the current node has no parent 
     *   in the TreeWalker's logical view.
     */
    public Node parentNode()
    {
      Node next = m_currentNode.getParentNode();
      
      // If we're at the root of the tree, we're done.
      if((null == next) || m_doc.equals( next ))
        return null;
      
      // If the parent vertice is an ancestor of the step 
      // context, then all siblings are to the left of the 
      // ancestor path, so we're done.
      if(isAncestorOfRootContext( next ))
        return null;
      
      m_nextLevelAmount = 0;
      return setCurrentIfNotNull(next);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      // Walk down the left edge of the current sub-tree.
      // Get the next child on the 'preceding' axes. This will 
      // skip any children nodes that are ancestors of the step context,
      // but will return children of those nodes.
      if(m_root.equals(m_currentNode))
        return null;
  
      Node nextNode = m_currentNode;
      while(null != nextNode)
      {
        Node n = nextNode.getFirstChild();
        
        if(null != n)
        {
          nextNode = n;
        }
        else
        {
          // If the next sibling is an ancestor, then continue 
          // on to get it's first child, otherwise nextSibling() 
          // will get it.
          nextNode = nextNode.getNextSibling();
          if(null != nextNode)
          {
            if(m_root.equals(nextNode) || !isAncestorOfRootContext(nextNode))
              return null;
            else
              continue;
          }
        }
        
        if(null != nextNode)
        {
          if(m_root.equals(nextNode))
            return null;
          else if(!isAncestorOfRootContext(nextNode))
            break;
        }
      }
      m_nextLevelAmount = (null == nextNode) ? 0 : (nextNode.hasChildNodes() ? 
1 : 0);
      return setCurrentIfNotNull(nextNode);
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the next sibling of the current 
     * node, and returns the new node. If the current node has no visible 
     * next sibling, returns <code>null</code> , and retains the current node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   next sibling in the TreeWalker's logical view.
     */
    public Node nextSibling()
    {
      if(m_root.equals(m_currentNode))
        return null;
      
      Node next = m_currentNode.getNextSibling();
        
      if((null == next) || m_root.equals(next) || isAncestorOfRootContext(next))
        return null;
      
      m_nextLevelAmount = (null == next) ? 0 : (next.hasChildNodes() ? 1 : 0);
      return setCurrentIfNotNull(next);
    }
      
    Node m_doc;
      
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return Short.MAX_VALUE;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/ReverseAxesWalker.java
  
  Index: ReverseAxesWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import java.util.Vector;
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.OpCodes;
  import org.apache.xalan.xpath.XObject;
  import org.xml.sax.SAXException;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeFilter;
  
  /**
   * Walker for a reverse axes.
   * @see <a href="http://www.w3.org/TR/xpath#predicates";>XPath 2.4 
Predicates</a>
   */
  public class ReverseAxesWalker extends AxesWalker
  {
    /**
     * Construct an AxesWalker using a LocPathIterator.
     */
    public ReverseAxesWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
    }
    
    /**
     * Tells if this is a reverse axes.
     */
    public boolean isReverseAxes()
    {
      return true;
    }
    
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      super.setRoot(root);
    }
    
    /**
     * Get the current sub-context position.  In order to do the 
     * reverse axes count, for the moment this re-searches the axes 
     * up to the predicate.  An optimization on this is to cache 
     * the nodes searched, but, for the moment, this case is probably 
     * rare enough that the added complexity isn't worth it.
     */
    protected int getProximityPosition(int predicateIndex)
    {
      if(m_proximityPositions[predicateIndex] <= 0)
      {
        AxesWalker savedWalker = m_lpi.getLastUsedWalker();
        try
        {
          ReverseAxesWalker clone = (ReverseAxesWalker)this.clone();
          clone.setRoot(this.getRoot());
          clone.m_predicateCount = predicateIndex;
          clone.setPrevWalker(null);
          clone.setNextWalker(null);
          m_lpi.setLastUsedWalker(clone);
  
          // Count 'em all
          int count = 1;
          Node next;
          while(null != (next = clone.nextNode()))
            count++;
          m_proximityPositions[predicateIndex] += count;
        }
        catch(CloneNotSupportedException cnse)
        {
          // can't happen
        }
        finally
        {
          m_lpi.setLastUsedWalker(savedWalker);
        }
      }
  
      return m_proximityPositions[predicateIndex];
    }
    
    /**
     * Count backwards one proximity position.
     */
    protected void countProximityPosition(int i)
    {
      if(i < m_proximityPositions.length)
        m_proximityPositions[i]--;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/RootWalker.java
  
  Index: RootWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the FROM_ROOT axes.
   * @see <a href="http://www.w3.org/TR/xpath#location-paths";>XPath 
location-paths descriptions</a>
   * @see <a href="http://www.w3.org/TR/xpath#NT-AbsoluteLocationPath";>XPath 
AbsoluteLocationPath descriptions</a>
   * @see <a 
href="http://www.w3.org/TR/xpath#NT-AbbreviatedAbsoluteLocationPath";>XPath 
AbbreviatedAbsoluteLocationPath descriptions</a>
   */
  public class RootWalker extends AxesWalker
  {
    /**
     * Construct a RootWalker using a LocPathIterator.
     */
    public RootWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
      m_nextLevelAmount = 0;
    }
    
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      // Follow rule about returning the first occuring in document order 
      // as the first child.  Strange but true.
      if(!m_processedRoot)
      {
        m_processedRoot = true;
        Node n = m_lpi.getDOMHelper().getRootNode(m_currentNode);
        return setCurrentIfNotNull(n);
      }
      return null;
    }
      
    boolean m_processedRoot = false;
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return 1;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/axes/SelfWalker.java
  
  Index: SelfWalker.java
  ===================================================================
  /*
  * The Apache Software License, Version 1.1
  *
  *
  * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
  *
  * 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 and was
  * originally based on software copyright (c) 1999, Lotus
  * Development Corporation., http://www.lotus.com.  For more
  * information on the Apache Software Foundation, please see
  * <http://www.apache.org/>.
  */
  package org.apache.xalan.xpath.axes;
  
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.SimpleNodeLocator;
  import org.apache.xalan.xpath.XPathContext;
  import org.w3c.dom.Node;
  
  /**
   * Walker for the 'self' axes.
   * @see <a href="http://www.w3.org/TR/xpath#axes";>XPath axes descriptions</a>
   */
  public class SelfWalker extends AxesWalker
  {
    /**
     * Construct a SelfWalker using a LocPathIterator.
     */
    public SelfWalker(LocPathIterator locPathIterator)
    {
      super(locPathIterator);
      m_nextLevelAmount = 0;
    }
    
    /**
     *  Set the root node of the TreeWalker.
     */
    public void setRoot(Node root)
    {
      m_processedSelf = false;
      super.setRoot(root);
    }
      
    /**
     *  Moves the <code>TreeWalker</code> to the first visible child of the 
     * current node, and returns the new node. If the current node has no 
     * visible children, returns <code>null</code> , and retains the current 
     * node.
     * @return  The new node, or <code>null</code> if the current node has no 
     *   visible children in the TreeWalker's logical view.
     */
    public Node firstChild()
    {
      // Follow my made-up rule about returning the self node as a child.
      if(!m_processedSelf)
      {
        m_processedSelf = true;
        return setCurrentIfNotNull(m_root);
      }
      return null;
    }
      
    boolean m_processedSelf;
    
    /**
     * Tell what's the maximum level this axes can descend to.
     */
    protected int getLevelMax()
    {
      return m_lpi.getDOMHelper().getLevel(m_root);
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncBoolean.java
  
  Index: FuncBoolean.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Boolean() function.
   */
  public class FuncBoolean extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      return ((XObject)args.elementAt(0)).bool() ? XBoolean.S_TRUE : 
XBoolean.S_FALSE;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncCeiling.java
  
  Index: FuncCeiling.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 The Apache Software Foundation.  All rights 
   * Xalan.
   *
   * 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Ceiling() function.
   */
  public class FuncCeiling extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      double d = ((XObject)args.elementAt(0)).num();
    return new XNumber(java.lang.Math.ceil(d));
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncConcat.java
  
  Index: FuncConcat.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Concat() function.
   */
  public class FuncConcat extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      int nArgs = args.size();
      String s = "";
    for(int i = 0; i < nArgs; i++)
    {
        String s1 = ((XObject)args.elementAt(i)).str();
        s = s.concat(s1);
      }
      return new XString(s);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncContains.java
  
  Index: FuncContains.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Contains() function.
   */
  public class FuncContains extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      String s1 = ((XObject)args.elementAt(0)).str();
    String s2 = ((XObject)args.elementAt(1)).str();
      
    // Add this check for JDK consistency for empty strings.
      if (s1.length() ==0 && s2.length() ==0)
        return XBoolean.S_TRUE;
    int index = s1.indexOf(s2);
      return (index > -1) ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncCount.java
  
  Index: FuncCount.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Count() function.
   */
  public class FuncCount extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {
      if (!(args.size() > 0))
        path.error(xctxt, context, XPATHErrorResources.ER_COUNT_TAKES_1_ARG, 
null);
      NodeIterator nl = ((XObject)args.elementAt(0)).nodeset();
      int i = 0;
      if(null != nl)
      {
        while(null != nl.nextNode())
          i++;
      }
      return new XNumber((double)i);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncCurrent.java
  
  Index: FuncCurrent.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions;
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNodeSet;
  import org.apache.xalan.xpath.axes.AxesWalker;
  import org.apache.xalan.xpath.LocPathIterator;
  import org.apache.xalan.xpath.NodeSet;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the current() function.
   */
  public class FuncCurrent extends Function
  {
    /**
     * Diagnostics.
     */
    protected String nodeToString(Node n)
    {
      return (null != n) 
             ? n.getNodeName()+"{"+ ((org.apache.xalan.stree.Child)n).getUid() 
+ "}"
               : "null";
    }
  
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      // If we're in a predicate, then this will return non-null.
      AxesWalker iter = (AxesWalker)xctxt.getTreeWalkerContext();
      
      Node currentNode;
      if(null != iter)
      {
        LocPathIterator lpi = iter.getLocPathIterator();
        currentNode = lpi.getCurrentContextNode();
      }
      else
      {
        NodeSet cnl = xctxt.getContextNodeList();
        if(null != cnl)
        {
          currentNode = cnl.getCurrentNode();
        }
        else
          currentNode = null;
      }
      
      if(null == currentNode)
      {
        path.error(xctxt, context, 
XPATHErrorResources.ER_CURRENT_NOT_ALLOWED_IN_MATCH, null); //"The current() 
function is not allowed in a match pattern!");
      }
      if(args.size() > 0)
      {
        path.error(xctxt, context, 
XPATHErrorResources.ER_CURRENT_TAKES_NO_ARGS, null); //"The current() function 
does not accept arguments!");
      }
  
      if(null != currentNode)
        return new XNodeSet(currentNode);
      else
        return new XNodeSet();
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncDoc.java
  
  Index: FuncDoc.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Doc() function.
   */
  public class FuncDoc extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      path.error( xctxt, context, XPATHErrorResources.ER_DOCUMENT_REPLACED, 
null); //"document() function implementation has been replaced by 
org.apache.xalan.xslt.FuncDocument!");
      return null;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncDoclocation.java
  
  Index: FuncDoclocation.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.Document;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the proprietary document-location() function, which returns 
   * a node set of documents.
   */
  public class FuncDoclocation extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      Node whereNode;
    if(args.size() > 0)
    {
      XObject firstArg = (XObject)args.firstElement();
      NodeIterator nl = firstArg.nodeset();
        whereNode = nl.nextNode();
      }
    else
    {
        whereNode = context;
    }
    
      String fileLocation = null;
    if(null != whereNode)
    {
      if(Node.DOCUMENT_FRAGMENT_NODE == whereNode.getNodeType())
        {
        whereNode = whereNode.getFirstChild();
        }
      if(null != whereNode)
        {
        Document owner = whereNode.getOwnerDocument();
          fileLocation = xctxt.getSourceTreeManager().findURIFromDoc(owner);
        }
    }
      
    return new XString((null != fileLocation) ? fileLocation : "");
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncExtElementAvailable.java
  
  Index: FuncExtElementAvailable.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.extensions.ExtensionsTable;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the ExtElementAvailable() function.
   */
  public class FuncExtElementAvailable extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
        public XObject execute(XPath path, XPathContext xctxt, Node context, 
int opPos, Vector args)
        {    
                String fullName = ((XObject)args.elementAt(0)).str();
                int indexOfNSSep = fullName.indexOf(':');
                String prefix = (indexOfNSSep >= 0) ? fullName.substring(0, 
indexOfNSSep) : "";
                String namespace = 
xctxt.getNamespaceContext().getNamespaceForPrefix(prefix);
                String methName = (indexOfNSSep < 0) ? fullName : 
fullName.substring(indexOfNSSep+1);
  
      ExtensionsTable etable = xctxt.getExtensionsTable();
                return etable.elementAvailable(namespace, methName) 
             ? XBoolean.S_TRUE : XBoolean.S_FALSE;
        }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncExtFunctionAvailable.java
  
  Index: FuncExtFunctionAvailable.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.extensions.ExtensionsTable;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the ExtFunctionAvailable() function.
   */
  public class FuncExtFunctionAvailable extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
        public XObject execute(XPath path, XPathContext xctxt, Node context, 
int opPos, Vector args)
        {    
                String fullName = ((XObject)args.elementAt(0)).str();
                int indexOfNSSep = fullName.indexOf(':');
                String prefix = (indexOfNSSep >= 0) ? fullName.substring(0, 
indexOfNSSep) : "";
                String namespace = 
xctxt.getNamespaceContext().getNamespaceForPrefix(prefix);
                String methName = (indexOfNSSep < 0) ? fullName : 
fullName.substring(indexOfNSSep+1);
  
      ExtensionsTable etable = xctxt.getExtensionsTable();
                return etable.functionAvailable(namespace, methName) 
             ? XBoolean.S_TRUE : XBoolean.S_FALSE;
        }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncFalse.java
  
  Index: FuncFalse.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the False() function.
   */
  public class FuncFalse extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      return XBoolean.S_FALSE;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncFloor.java
  
  Index: FuncFloor.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Floor() function.
   */
  public class FuncFloor extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      double d = ((XObject)args.elementAt(0)).num();
    return new XNumber(java.lang.Math.floor(d));
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncFormatNumber.java
  
  Index: FuncFormatNumber.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the FormatNumber() function.
   */
  public class FuncFormatNumber extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      double num = ((XObject)args.elementAt(0)).num();
      String formatStr = ((XObject)args.elementAt(1)).str();
      int nArgs = args.size();
      if(nArgs == 3)
      {
        path.warn(xctxt, context, 
XPATHErrorResources.WG_LOCALE_NAME_NOT_HANDLED, null); //"locale name in the 
format-number function not yet handled!");
      }
  
      java.text.DecimalFormat formatter = new 
java.text.DecimalFormat(formatStr);
      return new XString(formatter.format(num));
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncGenerateId.java
  
  Index: FuncGenerateId.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the GenerateId() function.
   */
  public class FuncGenerateId extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      if(args.size() > 0)
      {
      NodeIterator nl = ((XObject)args.elementAt(0)).nodeset();
        context = nl.nextNode();
      }
      try
      {
        org.apache.xalan.dtm.DTMProxy dtmp = 
(org.apache.xalan.dtm.DTMProxy)context;
        
        return new XString((null == context) 
                           ? "" : 
"N"+Integer.toString(dtmp.getDTMNodeNumber()));
      }
      catch(ClassCastException cce)
      {
        return new XString((null == context) 
                           ? "" : "N"+Integer.toString(context.hashCode()));
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncId.java
  
  Index: FuncId.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import java.util.Hashtable;
  import java.util.StringTokenizer;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.Document;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.DOMHelper;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNodeSet;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Id() function.
   */
  public class FuncId extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      Document docContext = (Node.DOCUMENT_NODE == context.getNodeType()) 
                            ? (Document)context : context.getOwnerDocument();
      XObject arg = (XObject)args.elementAt(0);
      XNodeSet nodes = new XNodeSet();
      boolean argIsNodeset = (XObject.CLASS_NODESET != arg.getType());
      if((arg.getType() == arg.CLASS_NULL) || 
         (!argIsNodeset && arg.str().length() == 0))
        return nodes;
      Hashtable usedrefs = new Hashtable();
      NodeIterator ni = argIsNodeset ? arg.nodeset() : null;
      Node pos = null;
      while(!argIsNodeset || (null != (pos = ni.nextNode())))
      {
        String refval = argIsNodeset
                        ? DOMHelper.getNodeData(pos) : arg.str();
        if(null != refval)
        {
          StringTokenizer tokenizer = new StringTokenizer(refval);
          while(tokenizer.hasMoreTokens())
          {
            String ref = tokenizer.nextToken();
            if(null == ref)
              continue;
            if(usedrefs.get(ref) != null)
            {
              continue;
            }
            else
            {
              // m_currentPattern being used as a dummy value.
              usedrefs.put(ref, path.getPatternString());
            }
            if(null == docContext)
            {
              path.error(xctxt, context, 
XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); //"context does not have 
an owner document!");
            }
            Node node = xctxt.getDOMHelper().getElementByID(ref, docContext);
            // nodes.mutableNodeset().addNode(node);   
            if(null != node)
              nodes.mutableNodeset().addNodeInDocOrder(node, xctxt);
          }
        }
        if(!argIsNodeset)
          break;
      }
      return nodes;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncLang.java
  
  Index: FuncLang.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import org.w3c.dom.Element;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Lang() function.
   */
  public class FuncLang extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      String lang = ((XObject)args.elementAt(0)).str();
    Node parent = context;
      boolean isLang = false;
      while(null != parent)
      {
        if(Node.ELEMENT_NODE == parent.getNodeType())
        {
          String langVal = ((Element)parent).getAttribute("xml:lang");
          if((null != langVal) && (langVal.length() > 0))
          {
            if(langVal.toLowerCase().startsWith(lang.toLowerCase()))
            {
              int valLen = lang.length();
              if((langVal.length() == valLen) || (langVal.charAt(valLen) == 
'-'))
              {
                isLang = true;
              }
            }
            break;
          }
        }
        parent = xctxt.getDOMHelper().getParentOfNode(parent);
      }
      return isLang ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncLast.java
  
  Index: FuncLast.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  import org.apache.xalan.xpath.FoundIndex;
  import org.apache.xalan.xpath.NodeSet;
  import org.apache.xalan.xpath.axes.AxesWalker;
  import org.apache.xalan.xpath.LocPathIterator;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Last() function.
   */
  public class FuncLast extends Function
  {
    /**
     * Get the position in the current context node list.
     */
    public int getCountOfContextNodeList(XPath path, XPathContext xctxt, Node 
context)
      throws org.xml.sax.SAXException
    {
      //    assert(null != m_contextNodeList, "m_contextNodeList must be 
non-null");
      
      if(xctxt.getThrowFoundIndex())
        throw new FoundIndex();
      
       // If we're in a predicate, then this will return non-null.
      AxesWalker iter = (AxesWalker)xctxt.getTreeWalkerContext();
      
      if(null != iter)
      {
        return iter.getLastPos();
      }
      
      NodeSet cnl = xctxt.getContextNodeList();
      if(cnl.size() == 0)
      {
        int currentPos = cnl.getCurrentPos();
        if(!cnl.isFresh())
          cnl.reset();
        cnl.setShouldCacheNodes(true);
        cnl.runTo(-1);
        cnl.setCurrentPos(currentPos);
      }
      
      return cnl.size();
    }
    
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      return new XNumber((double)getCountOfContextNodeList(path, xctxt,  
context));
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncLoader.java
  
  Index: FuncLoader.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import java.lang.Class;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Load functions in function table as needed
   */
  public class FuncLoader extends Function
  {
    private int m_funcID;
    private String m_funcName, test;
    
    public FuncLoader(String funcName, int funcID)
    {
      super();
      m_funcID = funcID;
      m_funcName = funcName;
    }
    
    /**
     * Replace the current function (us) in the table with
     * the actual function the call the function's execute method.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {
      try
      {
        Class function;
        // first get package name if necessary
        if ( m_funcName.indexOf(".") < 0 )
        {  
          String thisName = this.getClass().getName();
          int lastdot = thisName.lastIndexOf(".");
          String classname = thisName.substring(0,lastdot+1) + m_funcName;      
          function = Class.forName(classname);
        }
        else
          function = Class.forName(m_funcName);
        
        Function func = (Function)function.newInstance();
        path.installFunction(m_funcName, m_funcID, func);
        return func.execute(path, xctxt, context, opPos, args);
      }
      catch(ClassNotFoundException e)
      {
        e.printStackTrace();
        path.error(xctxt, context, 
XPATHErrorResources.ER_COULDNOT_FIND_FUNCTION, new Object[] {m_funcName});
        return null;
      }
      catch(IllegalAccessException e)
      {
        e.printStackTrace();
        path.error(xctxt, context, 
XPATHErrorResources.ER_COULDNOT_FIND_FUNCTION, new Object[] {m_funcName});
        return null;
      } 
      catch(InstantiationException e)
      {
        e.printStackTrace();
        path.error(xctxt, context, 
XPATHErrorResources.ER_COULDNOT_FIND_FUNCTION, new Object[] {m_funcName});
        return null;
      } 
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncLocalPart.java
  
  Index: FuncLocalPart.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * Execute the LocalPart() function.
   * <meta name="usage" content="advanced"/>
   */
  public class FuncLocalPart extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      int nArgs = args.size();
      if(nArgs > 0)
      {
        if(nArgs > 1)
          path.error(xctxt, context, 
XPATHErrorResources.ER_LOCALNAME_HAS_TOO_MANY_ARGS, null); //"local-name() has 
too many arguments.");
        NodeIterator nl = ((XObject)args.elementAt(0)).nodeset();
        context = nl.nextNode();
      }
      return new XString((context != null)
                         ? xctxt.getDOMHelper().getLocalNameOfNode(context) : 
"");
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncNamespace.java
  
  Index: FuncNamespace.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Namespace() function.
   */
  public class FuncNamespace extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      int nArgs = args.size();
      if(nArgs > 0)
      {
        if(nArgs > 1)
          path.error(xctxt, context, 
XPATHErrorResources.ER_NAMESPACEURI_HAS_TOO_MANY_ARGS, null); 
//"namespace-uri() has too many arguments.");
        NodeIterator nl = ((XObject)args.elementAt(0)).nodeset();
        context = nl.nextNode();
      }
      return new XString((context != null)
                         ? xctxt.getDOMHelper().getNamespaceOfNode(context) : 
"");
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncNormalize.java
  
  Index: FuncNormalize.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  import org.apache.xalan.xpath.XNodeSet;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Normalize() function.
   */
  public class FuncNormalize extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      int nArgs = args.size();
      XObject obj;
      if(nArgs > 0)
      {
        if(nArgs > 1)
          path.error(xctxt, context, 
XPATHErrorResources.ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS, null); //"normalize() 
has too many arguments.");
        obj = ((XObject)args.elementAt(0));
      }
      else
      {
        obj = new XNodeSet(context);
      }
      String s1 = obj.str();
      return new XString(fixWhiteSpace(s1, true, true, false));
    }
    
    /**
     * Returns whether the specified <var>ch</var> conforms to the XML 1.0 
definition
     * of whitespace.  Refer to <A 
href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S";>
     * the definition of <CODE>S</CODE></A> for details.
     * @param   ch      Character to check as XML whitespace.
     * @return          =true if <var>ch</var> is XML whitespace; otherwise 
=false.
     */
    private static boolean isSpace(char ch) 
    {
      return Character.isWhitespace(ch); // Take the easy way out for now.
    }
    
    /**
     * (Code stolen and modified from XML4J)
     * Conditionally trim all leading and trailing whitespace in the specified 
String.  
     * All strings of white space are 
     * replaced by a single space character (#x20), except spaces after 
punctuation which 
     * receive double spaces if doublePunctuationSpaces is true.
     * This function may be useful to a formatter, but to get first class
     * results, the formatter should probably do it's own white space handling 
     * based on the semantics of the formatting object.
     * @param   string      String to be trimmed.
     * @param   trimHead    Trim leading whitespace?
     * @param   trimTail    Trim trailing whitespace?
     * @param   doublePunctuationSpaces    Use double spaces for punctuation?
     * @return              The trimmed string.
     */
    protected String fixWhiteSpace(String string, 
                                boolean trimHead, 
                                boolean trimTail, 
                                boolean doublePunctuationSpaces) 
    {
      char[] buf = string.toCharArray();
      int len = buf.length;
      boolean edit = false;
      int s;
      for (s = 0;  s < len;  s++) 
      {
        if (isSpace(buf[s]))  
        {
          break;
        }
      }
      /* replace S to ' '. and ' '+ -> single ' '. */
      int d = s;
      boolean pres = false;
      for ( ;  s < len;  s ++) 
      {
        char c = buf[s];
        if (isSpace(c)) 
        {
          if (!pres) 
          {
            if (' ' != c)  
            {
              edit = true;
            }
            buf[d++] = ' ';
            if(doublePunctuationSpaces && (s != 0))
            {
              char prevChar = buf[s-1];
              if(!((prevChar == '.') || (prevChar == '!') || (prevChar == '?')))
              {
                pres = true;
              }
            }
            else
            {
              pres = true;
            }
          }
          else
          {
            edit = true;
            pres = true;
          }
        }
        else 
        {
          buf[d++] = c;
          pres = false;
        }
      }
      if (trimTail && 1 <= d && ' ' == buf[d-1]) 
      {
        edit = true;
        d --;
      }
      int start = 0;
      if (trimHead && 0 < d && ' ' == buf[0]) 
      {
        edit = true;
        start ++;
      }
      return edit ? new String(buf, start, d-start) : string;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncNormalizeSpace.java
  
  Index: FuncNormalizeSpace.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  import org.apache.xalan.xpath.XNodeSet;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Normalize-space() function.
   */
  public class FuncNormalizeSpace extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      int nArgs = args.size();
      if(nArgs > 0)
      {
        if(nArgs > 1)
          path.error(xctxt, context, 
XPATHErrorResources.ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS, null); 
//"normalize-space() has too many arguments.");
        
        String s1 = ((XObject)args.elementAt(0)).str();
        return new XString(fixWhiteSpace(s1, true, true, false));
      }
      else
      {
        String s1 = XNodeSet.getStringFromNode(context);
        return new XString(fixWhiteSpace(s1, true, true, false));
      }
    }
    
    /**
     * Returns whether the specified <var>ch</var> conforms to the XML 1.0 
definition
     * of whitespace.  Refer to <A 
href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S";>
     * the definition of <CODE>S</CODE></A> for details.
     * @param   ch      Character to check as XML whitespace.
     * @return          =true if <var>ch</var> is XML whitespace; otherwise 
=false.
     */
    private static boolean isSpace(char ch) 
    {
      return Character.isWhitespace(ch); // Take the easy way out for now.
    }
    
    /**
     * (Code stolen and modified from XML4J)
     * Conditionally trim all leading and trailing whitespace in the specified 
String.  
     * All strings of white space are 
     * replaced by a single space character (#x20), except spaces after 
punctuation which 
     * receive double spaces if doublePunctuationSpaces is true.
     * This function may be useful to a formatter, but to get first class
     * results, the formatter should probably do it's own white space handling 
     * based on the semantics of the formatting object.
     * @param   string      String to be trimmed.
     * @param   trimHead    Trim leading whitespace?
     * @param   trimTail    Trim trailing whitespace?
     * @param   doublePunctuationSpaces    Use double spaces for punctuation?
     * @return              The trimmed string.
     */
    protected String fixWhiteSpace(String string, 
                                boolean trimHead, 
                                boolean trimTail, 
                                boolean doublePunctuationSpaces) 
    {
      char[] buf = string.toCharArray();
      int len = buf.length;
      boolean edit = false;
      int s;
      for (s = 0;  s < len;  s++) 
      {
        if (isSpace(buf[s]))  
        {
          break;
        }
      }
      /* replace S to ' '. and ' '+ -> single ' '. */
      int d = s;
      boolean pres = false;
      for ( ;  s < len;  s ++) 
      {
        char c = buf[s];
        if (isSpace(c)) 
        {
          if (!pres) 
          {
            if (' ' != c)  
            {
              edit = true;
            }
            buf[d++] = ' ';
            if(doublePunctuationSpaces && (s != 0))
            {
              char prevChar = buf[s-1];
              if(!((prevChar == '.') || (prevChar == '!') || (prevChar == '?')))
              {
                pres = true;
              }
            }
            else
            {
              pres = true;
            }
          }
          else
          {
            edit = true;
            pres = true;
          }
        }
        else 
        {
          buf[d++] = c;
          pres = false;
        }
      }
      if (trimTail && 1 <= d && ' ' == buf[d-1]) 
      {
        edit = true;
        d --;
      }
      int start = 0;
      if (trimHead && 0 < d && ' ' == buf[0]) 
      {
        edit = true;
        start ++;
      }
      return edit ? new String(buf, start, d-start) : string;
    }
  
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncNot.java
  
  Index: FuncNot.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Not() function.
   */
  public class FuncNot extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      return ((XObject)args.elementAt(0)).bool() ? XBoolean.S_FALSE : 
XBoolean.S_TRUE;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncNumber.java
  
  Index: FuncNumber.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  import org.apache.xalan.xpath.XNodeSet;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Number() function.
   */
  public class FuncNumber extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      int nArgs = args.size();
      XObject obj;
      if(nArgs > 0)
      {
        if(nArgs > 1)
          path.error(xctxt, context, 
XPATHErrorResources.ER_NUMBER_HAS_TOO_MANY_ARGS, null); //"number() has too 
many arguments.");
        obj = ((XObject)args.elementAt(0));
      }
      else
      {
        obj = new XNodeSet(context);
      }
      return new XNumber(obj.num());
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncPosition.java
  
  Index: FuncPosition.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  import org.apache.xalan.xpath.FoundIndex;
  import org.apache.xalan.xpath.axes.AxesWalker;
  import org.apache.xalan.xpath.NodeSet;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Position() function.
   */
  public class FuncPosition extends Function
  {
    /**
     * Get the position in the current context node list.
     */
    public int getPositionInContextNodeList(Node context, XPathContext xctxt)
    {
      // assert(null != m_contextNodeList, "m_contextNodeList must be 
non-null");
      
      if(xctxt.getThrowFoundIndex())
        throw new FoundIndex();
      
      // If we're in a predicate, then this will return non-null.
      AxesWalker iter = (AxesWalker)xctxt.getTreeWalkerContext();
      
      if(null != iter)
      {
        int prox = iter.getProximityPosition();
        // System.out.println("prox: "+prox);
        return prox;
      }
      
      NodeSet cnl = xctxt.getContextNodeList();
      if(null != cnl)
      {
        // System.out.println("cnl.getCurrentPos(): "+cnl.getCurrentPos());
        return cnl.getCurrentPos();
      }
      
      return -1;
    }
  
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      return new XNumber((double)getPositionInContextNodeList(context, xctxt));
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncQname.java
  
  Index: FuncQname.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import org.w3c.dom.Attr;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  import org.apache.xalan.utils.QName;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Qname() function.
   */
  public class FuncQname extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      int nArgs = args.size();
      if(nArgs > 0)
      {
        if(nArgs > 1)
          path.error(xctxt, context, 
XPATHErrorResources.ER_NAME_HAS_TOO_MANY_ARGS, null); //"name() has too many 
arguments.");
        NodeIterator nl = ((XObject)args.elementAt(0)).nodeset();
        context = nl.nextNode();
      }
      XObject val;
      if(null != context)
      {
        int ntype = context.getNodeType();
        if(ntype == Node.ATTRIBUTE_NODE)
        {
          String qname = ((Attr)context).getName();
          if(xctxt.getDOMHelper().isNamespaceNode(context))
          {
            if(qname.equals("xmlns"))
              val = new XString("");
            else
            {
              qname = QName.getLocalPart(qname);
              val = new XString((null == qname) ? "" : qname);
            }
          }
          else
            val = new XString(qname);
        }
        else if((ntype == Node.ELEMENT_NODE) 
           || (ntype == Node.PROCESSING_INSTRUCTION_NODE))
        {
          String qname = context.getNodeName();
          val = new XString(qname);
        }
        else
        {
          val = new XString("");
        }
      }
      else
      {
        val = new XString("");
      }
      return val;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncRound.java
  
  Index: FuncRound.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Round() function.
   */
  public class FuncRound extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      double d = ((XObject)args.elementAt(0)).num();
  
      return new XNumber(java.lang.Math.floor(d + 0.5));
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncStartsWith.java
  
  Index: FuncStartsWith.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the StartsWith() function.
   */
  public class FuncStartsWith extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      String s1 = ((XObject)args.elementAt(0)).str();
    String s2 = ((XObject)args.elementAt(1)).str();
    boolean startswith = s1.startsWith(s2);
      return startswith ? XBoolean.S_TRUE : XBoolean.S_FALSE;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncString.java
  
  Index: FuncString.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  import org.apache.xalan.xpath.XNodeSet;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the String() function.
   */
  public class FuncString extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      int nArgs = args.size();
      XObject obj;
      if(nArgs > 0)
      {
        if(nArgs > 1)
          path.error(xctxt, context, 
XPATHErrorResources.ER_STRING_HAS_TOO_MANY_ARGS, null); //"string() has too 
many arguments.");
        obj = ((XObject)args.elementAt(0));
      }
      else
      {
        obj = new XNodeSet(context);
      }
  
      return (XObject.CLASS_STRING == obj.getType()) ?
             (XString)obj : new XString(obj.str());
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncStringLength.java
  
  Index: FuncStringLength.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  import org.apache.xalan.xpath.XNodeSet;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the StringLength() function.
   */
  public class FuncStringLength extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      int nArgs = args.size();
      XObject obj;
      if(nArgs > 0)
      {
        if(nArgs > 1)
          path.error(xctxt, context, 
XPATHErrorResources.ER_STRINGLENGTH_HAS_TOO_MANY_ARGS, null); 
//"string-length() has too many arguments.");
        obj = ((XObject)args.elementAt(0));
      }
      else
      {
        obj = new XNodeSet(context);
      }
      String s1 = obj.str();
      return new XNumber(s1.length());
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncSubstring.java
  
  Index: FuncSubstring.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Substring() function.
   */
  public class FuncSubstring extends Function
  {
    /**
     * Execute the substring function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      String s1 = ((XObject)args.elementAt(0)).str();
    double start = ((XObject)args.elementAt(1)).num();
      int lenOfS1 = s1.length();
      String substr;
      if(lenOfS1 <= 0)
      {
        substr = "";
      }
      else
      {
        
        int startIndex;
        if(Double.isNaN(start))
        {
          // Double.MIN_VALUE doesn't work with math below 
          // so just use a big number and hope I never get caught.
          start = -1000000;  
          startIndex = 0;
        }
        else
        {
          start = Math.round(start);
          startIndex = (start > 0) ? (int)start-1 : 0;
        }
        
        if(args.size() > 2)
        {
          double len = ((XObject)args.elementAt(2)).num();
          int end = (int)(Math.round(len)+start)-1;
          
          // Normalize end index.
          if(end < 0)
            end = 0;
          else if(end > lenOfS1)
            end = lenOfS1;
          
          substr = s1.substring(startIndex, end);
        }
        else
        {
          substr = s1.substring(startIndex);
        }
      }
      return new XString(substr);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncSubstringAfter.java
  
  Index: FuncSubstringAfter.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the SubstringAfter() function.
   */
  public class FuncSubstringAfter extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      String s1 = ((XObject)args.elementAt(0)).str();
    String s2 = ((XObject)args.elementAt(1)).str();
    int index = s1.indexOf(s2);
      return new XString((-1 == index) ? "" : s1.substring(index+s2.length()));
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncSubstringBefore.java
  
  Index: FuncSubstringBefore.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the SubstringBefore() function.
   */
  public class FuncSubstringBefore extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      String s1 = ((XObject)args.elementAt(0)).str();
    String s2 = ((XObject)args.elementAt(1)).str();
    int index = s1.indexOf(s2);
      return new XString((-1 == index) ? "" : s1.substring(0,  index));
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncSum.java
  
  Index: FuncSum.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import org.w3c.dom.traversal.NodeIterator;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.DOMHelper;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Sum() function.
   */
  public class FuncSum extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      NodeIterator nodes = ((XObject)args.elementAt(0)).nodeset();
    double sum = 0.0;
      Node pos;
      while(null != (pos = nodes.nextNode()))
      {
        String s = DOMHelper.getNodeData(pos);
        if(null != s) 
          sum += XString.castToNum(s);
      }
      return new XNumber(sum);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncSystemProperty.java
  
  Index: FuncSystemProperty.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import java.util.Properties;
  import java.io.BufferedInputStream;
  import java.io.InputStream;
  import java.lang.ClassLoader;
  import org.apache.xalan.utils.PrefixResolver;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XNumber;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the SystemProperty() function.
   */
  public class FuncSystemProperty extends Function
  {
    Properties xsltInfo = new Properties ();
    static String XSLT_PROPERTIES = "/org/apache/xalan/res/XSLTInfo.properties";
    
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      String fullName = ((XObject)args.elementAt(0)).str();
      int indexOfNSSep = fullName.indexOf(':');
      String result;
      String propName= "";
      loadPropertyFile(XSLT_PROPERTIES, xsltInfo);
      if(indexOfNSSep > 0)
      {
        String prefix = (indexOfNSSep >= 0) ? fullName.substring(0, 
indexOfNSSep) : "";
        String namespace;
        namespace = xctxt.getNamespaceContext().getNamespaceForPrefix(prefix);
        propName = (indexOfNSSep < 0) ? fullName 
                                               : 
fullName.substring(indexOfNSSep+1);
        
        if(namespace.startsWith("http://www.w3.org/XSL/Transform";) ||
           namespace.equals("http://www.w3.org/1999/XSL/Transform";))
        {
          result = xsltInfo.getProperty(propName);
          if (null == result)
          {
                            path.warn(xctxt, context, 
XPATHErrorResources.WG_PROPERTY_NOT_SUPPORTED, new Object[] {fullName}); //"XSL 
Property not supported: "+fullName);
            result = "";
          }
        }
        else
        {
          path.warn(xctxt, context, 
XPATHErrorResources.WG_DONT_DO_ANYTHING_WITH_NS, new Object[] {namespace, 
fullName}); //"Don't currently do anything with namespace "+namespace+" in 
property: "+fullName);
          try
          {
            result = System.getProperty(propName);
            if(null == result)
            {
              // result = System.getenv(propName);
              result = "";
            }
          }
          catch(SecurityException se)
          {
            path.warn(xctxt, context, 
XPATHErrorResources.WG_SECURITY_EXCEPTION, new Object[] {fullName}); 
//"SecurityException when trying to access XSL system property: "+fullName);
            result = "";
          }
        }
      }
      else
      {
        try
        {
          result = System.getProperty(fullName);
          if(null == result)
          {
            // result = System.getenv(fullName);
            result = "";
          }
        }
        catch(SecurityException se)
        {
          path.warn(xctxt, context, XPATHErrorResources.WG_SECURITY_EXCEPTION, 
new Object[] {fullName}); //"SecurityException when trying to access XSL system 
property: "+fullName);
          result = "";
        }
      }
      if (propName.equals("version") && result.length()>0)
      {  
        try
        {
          return new XNumber(new Double(result).doubleValue());
        }
        catch (Exception ex)
        {
          return new XString(result);
        }    
      }      
      else  
        return new XString(result);
    }
    
  /*
   * Retrieve a propery bundle from a specified file
   * @param file The string name of the property file.  The file is loaded from 
the workplace base directory
   * @param target The target property bag the file will be placed into.
   */
    public void loadPropertyFile (String file, Properties target) 
    {
      InputStream is;
      try
      {                    
        is= getClass().getResourceAsStream(file);      
                                                             // get a buffered 
version
        BufferedInputStream bis = new BufferedInputStream (is);
        target.load (bis);                                     // and load up 
the property bag from this
        bis.close ();                                          // close out 
after reading
      }
      catch (Exception ex)
      {
        ex.printStackTrace();
      }  
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncTranslate.java
  
  Index: FuncTranslate.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the Translate() function.
   */
  public class FuncTranslate extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      if(args.size() != 3)
      {
        path.error(xctxt, context, 
XPATHErrorResources.ER_TRANSLATE_TAKES_3_ARGS, null); //"The translate() 
function takes three arguments!");
      }
                String          theFirstString = 
((XObject)args.elementAt(0)).str();
                String          theSecondString = 
((XObject)args.elementAt(1)).str();
                String          theThirdString = 
((XObject)args.elementAt(2)).str();
  
                int                     theFirstStringLength = 
theFirstString.length();
                int                     theThirdStringLength = 
theThirdString.length();
  
                // A vector to contain the new characters.  We'll use it to 
construct
                // the result string.
                StringBuffer sbuffer = new StringBuffer();
  
                for (int i = 0; i < theFirstStringLength; i++)
                {
                        char theCurrentChar = theFirstString.charAt(i);
  
                        int             theIndex = 
theSecondString.indexOf(theCurrentChar);
  
                        if (theIndex < 0)
                        {
                                // Didn't find the character in the second 
string, so it
                                // is not translated.
          sbuffer.append(theCurrentChar);
                        }
                        else if (theIndex < theThirdStringLength)
                        {
                                // OK, there's a corresponding character in the
                                // third string, so do the translation...
          sbuffer.append(theThirdString.charAt(theIndex));
                        }
                        else
                        {
                                // There's no corresponding character in the
                                // third string, since it's shorter than the
                                // second string.  In this case, the character
                                // is removed from the output string, so don't
                                // do anything.
                        }
                }
      return new XString(sbuffer.toString());
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncTrue.java
  
  Index: FuncTrue.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XBoolean;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the True() function.
   */
  public class FuncTrue extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
    {    
      return XBoolean.S_TRUE;
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/FuncUnparsedEntityURI.java
  
  Index: FuncUnparsedEntityURI.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions; 
  
  import org.apache.xalan.xpath.res.XPATHErrorResources;
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  import org.apache.xalan.xpath.XString;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Execute the True() function.
   */
  public class FuncUnparsedEntityURI extends Function
  {
    /**
     * Execute the function.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, Vector args) 
      throws org.xml.sax.SAXException
    {    
      if(args.size() != 1)
      {
        path.error(xctxt, context, 
XPATHErrorResources.ER_UNPARSEDENTITYURI_TAKES_1_ARG, null); //"The 
unparsed-entity-uri function should take one argument!");
      }
      String name = ((XObject)args.elementAt(0)).str();
      Document doc = (Node.DOCUMENT_NODE == context.getNodeType()) 
                     ? ((Document)context) :
                       context.getOwnerDocument();
      String uri = xctxt.getDOMHelper().getUnparsedEntityURI(name, doc);
      return new XString(uri);
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/functions/Function.java
  
  Index: Function.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.functions;
  
  import org.w3c.dom.Node;
  import java.util.Vector;
  import org.apache.xalan.xpath.XPathContext;
  import org.apache.xalan.xpath.XPath;
  import org.apache.xalan.xpath.XObject;
  
  /**
   * <meta name="usage" content="advanced"/>
   * This is a superclass of all XPath functions.  This allows two 
   * ways for the class to be called. One method is that the 
   * super class processes the arguments and hands the results to 
   * the derived class, the other method is that the derived 
   * class may process it's own arguments, which is faster since 
   * the arguments don't have to be added to an array, but causes 
   * a larger code footprint.
   */
  public abstract class Function
  {
    /**
     * Execute an XPath function object.  The function must return 
     * a valid object.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param args A list of XObject arguments.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, 
                                    int opPos, Vector args)
      throws org.xml.sax.SAXException
    {
      // Programmer's assert.  (And, no, I don't want the method to be 
abstract).
      System.out.println("Error! Function.execute should not be called!");
      return null;
    }
    
    /**
     * Execute an XPath function object.  The function must return 
     * a valid object.  The function can either override this function, 
     * in which case it must handle executing it's own arguments, or 
     * it can have the functions processed for it and override the 
     * other execute function.
     * @param path The executing xpath.
     * @param context The current context.
     * @param opPos The current op position.
     * @param endFunc The op position of the end of the function.
     * @return A valid XObject.
     */
    public XObject execute(XPath path, XPathContext xctxt, Node context, int 
opPos, 
                               int funcID, int endFunc)
      throws org.xml.sax.SAXException
    {
          Vector args = new Vector();
      while(opPos < endFunc)
      {
        int nextOpPos = path.getNextOpPos(opPos);
        args.addElement(path.execute(xctxt, context, opPos));
        opPos = nextOpPos;
      }
      return execute(path, xctxt, context, opPos, args);
    }
      
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/res/XPATHErrorResourceBundle.java
  
  Index: XPATHErrorResourceBundle.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.res;
  import java.util.*;
  
  /**
   * <meta name="usage" content="internal"/>
   * LangResources_en.properties
   */
  public class XPATHErrorResourceBundle extends ListResourceBundle 
  {
    public Object[][] getContents()
    {
      return contents;
    }   
  
    static final Object[][] contents = 
    {
  
      {"ui_language","en"},
      {"help_language", "en"},
      {"language", "en"},
  
      {"ERROR0001","0001"},
      {"ERROR0002", "0002"},
      {"ERROR0003", "0003"},
      {"ERROR0004", "0004"},
      {"ERROR0005", "0005"},
      {"ERROR0006", "0006"},
      {"ERROR0007", "0007"},
      {"ERROR0008", "0008"},
      {"ERROR0009", "0009"},
      {"ERROR0010", "0010"},
      {"ERROR0011", "0011"},
      {"ERROR0012", "0012"},
      {"ERROR0013", "0013"},
      {"ERROR0014", "0014"},
      {"ERROR0015", "0015"},
      {"ERROR0016", "0016"},
      {"ERROR0017", "0017"},
      {"ERROR0018", "0018"},
      {"ERROR0019", "0019"},
      {"ERROR0020", "0020"},
      {"ERROR0021", "0021"},
      {"ERROR0022", "0022"},
      {"ERROR0023", "0023"},
      {"ERROR0024", "0024"},
      {"ERROR0025", "0025"},
      {"ERROR0026", "0026"},
      {"ERROR0027", "0027"},
      {"ERROR0028", "0028"},
      {"ERROR0029", "0029"},
      {"ERROR0030", "0030"},
      {"ERROR0031", "0031"},
      {"ERROR0032", "0032"},
      {"ERROR0033", "0033"},
      {"ERROR0034", "0034"},
      {"ERROR0035", "0035"},
      {"ERROR0036", "0036"},
      {"ERROR0037", "0037"},
      {"ERROR0038", "0038"},
      {"ERROR0039", "0039"},
      {"ERROR0040", "0040"},
      {"ERROR0041", "0041"},
      {"ERROR0042", "0042"},
      {"ERROR0043", "0043"},
      {"ERROR0044", "0044"},
      {"ERROR0045", "0045"},
      {"ERROR0046", "0046"},
      {"ERROR0047", "0047"},
      {"ERROR0048", "0048"},
      {"ERROR0049", "0049"},
      {"ERROR0050", "0050"},
      {"ERROR0051", "0051"},
      {"ERROR0052", "0052"},
      {"ERROR0053", "0053"},
      {"ERROR0054", "0054"},
      {"ERROR0055", "0055"},
      {"ERROR0056", "0056"},
      {"ERROR0057", "0057"},
      {"ERROR0058", "0058"},
      {"ERROR0059", "0059"},
      {"ERROR0060", "0060"},
  
  
      {"WARNING0001", "0001"},
      {"WARNING0002", "0002"},
      {"WARNING0003", "0003"},
      {"WARNING0004", "0004"},
      {"WARNING0005", "0005"},
      {"WARNING0006", "0006"},
      {"WARNING0007", "0007"},
      {"WARNING0008", "0008"},
      {"WARNING0009", "0009"},
      {"WARNING0010", "0010"},
      {"WARNING0011", "0011"}
    };    
  }  
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/res/XPATHErrorResources.java
  
  Index: XPATHErrorResources.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.res;
  import org.apache.xalan.res.XSLResourceBundle;
  import java.util.*;
  import java.text.DecimalFormat;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Set up error messages.
   * We build a two dimensional array of message keys and 
   * message strings. In order to add a new message here,
   * you need to first update the count of messages(MAX_CODE)or 
   * the count of warnings(MAX_WARNING). The array will be 
   * automatically filled in with the keys, but you need to 
   * fill in the actual message string. Follow the instructions
   * below.   
   */
  public class XPATHErrorResources extends XSLResourceBundle 
  {
  
    public static final String ERROR_SUFFIX = "ER";  
    public static final String WARNING_SUFFIX = "WR";
  
    public static final int MAX_CODE = 68;                // this is needed to 
keep track of the number of messages          
    public static final int MAX_WARNING = 10;             // this is needed to 
keep track of the number of warnings
    public static final int MAX_OTHERS = 20;
    public static final int MAX_MESSAGES = MAX_CODE + MAX_WARNING +1;
  
    static final Object[][] contents = new Object[MAX_MESSAGES + MAX_OTHERS 
+1][2];
  
    /* 
    * Now fill in the message keys.
    * This does not need to be updated. If MAX_CODE and MAX_WARNING
    * are correct, the keys will get filled in automatically with
    * the value ERxxxx (WRxxxx for warnings) where xxxx is a 
    * formatted number corresponding to the error code (i.e. ER0001).
    */ 
    static 
    {
      for(int i = 0; i < MAX_CODE+1; i++)
      {
        contents[i][0] = getMKey(i);
      }
      for(int i = 1; i < MAX_WARNING+1; i++)
      {
        contents[i+ MAX_CODE][0] = getWKey(i);
      }
    }
  
    /*
    * Now fill in the message text.
    * First create an int for the message code. Make sure you 
    * update MAX_CODE for error messages and MAX_WARNING for warnings
    * Then fill in the message text for that message code in the
    * array. Use the new error code as the index into the array.
    */ 
  
    // Error messages...
  
    public static final int ERROR0000 = 0;
    static 
    {
      contents[ERROR0000][1] 
      = "{0}";
    }
  
    public static final int ER_CURRENT_NOT_ALLOWED_IN_MATCH = 1;
    static 
    {
      contents[ER_CURRENT_NOT_ALLOWED_IN_MATCH][1] 
      = "The current() function is not allowed in a match pattern!";
    }
  
    public static final int ER_CURRENT_TAKES_NO_ARGS = 2;
    static 
    {
      contents[ER_CURRENT_TAKES_NO_ARGS][1] 
      = "The current() function does not accept arguments!";
    }
  
    public static final int ER_DOCUMENT_REPLACED = 3;
    static 
    {
      contents[ER_DOCUMENT_REPLACED][1] 
      = "document() function implementation has been replaced by 
org.apache.xalan.xslt.FuncDocument!";
    }
  
    public static final int ER_CONTEXT_HAS_NO_OWNERDOC = 4;
    static 
    {
      contents[ER_CONTEXT_HAS_NO_OWNERDOC][1] 
      = "context does not have an owner document!";
    }
  
    public static final int ER_LOCALNAME_HAS_TOO_MANY_ARGS  = 5;
    static 
    {
      contents[ER_LOCALNAME_HAS_TOO_MANY_ARGS ][1] 
      = "local-name() has too many arguments.";
    }
  
    public static final int ER_NAMESPACEURI_HAS_TOO_MANY_ARGS  = 6;
    static 
    {
      contents[ER_NAMESPACEURI_HAS_TOO_MANY_ARGS ][1] 
      = "namespace-uri() has too many arguments.";
    }
  
    public static final int ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS  = 7;
    static 
    {
      contents[ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS ][1] 
      = "normalize-space() has too many arguments.";
    }
  
    public static final int ER_NUMBER_HAS_TOO_MANY_ARGS  = 8;
    static 
    {
      contents[ER_NUMBER_HAS_TOO_MANY_ARGS ][1] 
      = "number() has too many arguments.";
    }
  
    public static final int ER_NAME_HAS_TOO_MANY_ARGS  = 9;
    static 
    {
      contents[ER_NAME_HAS_TOO_MANY_ARGS ][1] 
      = "name() has too many arguments.";
    }
  
    public static final int ER_STRING_HAS_TOO_MANY_ARGS  = 10;
    static 
    {
      contents[ER_STRING_HAS_TOO_MANY_ARGS ][1] 
      = "string() has too many arguments.";
    }
  
    public static final int ER_STRINGLENGTH_HAS_TOO_MANY_ARGS  = 11;
    static 
    {
      contents[ER_STRINGLENGTH_HAS_TOO_MANY_ARGS ][1] 
      = "string-length() has too many arguments.";
    }
  
    public static final int ER_TRANSLATE_TAKES_3_ARGS  = 12;
    static 
    {
      contents[ER_TRANSLATE_TAKES_3_ARGS ][1] 
      = "The translate() function takes three arguments!";
    }
  
    public static final int ER_UNPARSEDENTITYURI_TAKES_1_ARG  = 13;
    static 
    {
      contents[ER_UNPARSEDENTITYURI_TAKES_1_ARG ][1] 
      = "The unparsed-entity-uri function should take one argument!";
    }
  
    public static final int ER_NAMESPACEAXIS_NOT_IMPLEMENTED  = 14;
    static 
    {
      contents[ER_NAMESPACEAXIS_NOT_IMPLEMENTED ][1] 
      = "namespace axis not implemented yet!";
    }
  
    public static final int ER_UNKNOWN_AXIS  = 15;
    static 
    {
      contents[ER_UNKNOWN_AXIS ][1] 
      = "unknown axis: {0}";
    }
  
    public static final int ER_UNKNOWN_MATCH_OPERATION  = 16;
    static 
    {
      contents[ER_UNKNOWN_MATCH_OPERATION ][1] 
      = "unknown match operation!";
    }
  
    public static final int ER_INCORRECT_ARG_LENGTH  = 17;
    static 
    {
      contents[ER_INCORRECT_ARG_LENGTH ][1] 
      = "Arg length of processing-instruction() node test is incorrect!";
    }
  
    public static final int ER_CANT_CONVERT_TO_NUMBER  = 18;
    static 
    {
      contents[ER_CANT_CONVERT_TO_NUMBER ][1] 
      = "Can not convert {0} to a number";
    }
  
    public static final int ER_CANT_CONVERT_TO_NODELIST  = 19;
    static 
    {
      contents[ER_CANT_CONVERT_TO_NODELIST ][1] 
      = "Can not convert {0} to a NodeList!";
    }
  
    public static final int ER_CANT_CONVERT_TO_MUTABLENODELIST  = 20;
    static 
    {
      contents[ER_CANT_CONVERT_TO_MUTABLENODELIST ][1] 
      = "Can not convert {0} to a NodeSet!";
    }
  
    public static final int ER_CANT_CONVERT_TO_TYPE  = 21;
    static 
    {
      contents[ER_CANT_CONVERT_TO_TYPE ][1] 
      = "Can not convert {0} to a type#{1}";
    }
  
    public static final int ER_EXPECTED_MATCH_PATTERN  = 22;
    static 
    {
      contents[ER_EXPECTED_MATCH_PATTERN ][1] 
      = "Expected match pattern in getMatchScore!";
    }
  
    public static final int ER_COULDNOT_GET_VAR_NAMED  = 23;
    static 
    {
      contents[ER_COULDNOT_GET_VAR_NAMED ][1] 
      = "Could not get variable named {0}";
    }
  
    public static final int ER_UNKNOWN_OPCODE  = 24;
    static 
    {
      contents[ER_UNKNOWN_OPCODE ][1] 
      = "ERROR! Unknown op code: {0}";
    }
  
    public static final int ER_EXTRA_ILLEGAL_TOKENS  = 25;
    static 
    {
      contents[ER_EXTRA_ILLEGAL_TOKENS ][1] 
      = "Extra illegal tokens: {0}";
    }
  
    public static final int ER_EXPECTED_DOUBLE_QUOTE  = 26;
    static 
    {
      contents[ER_EXPECTED_DOUBLE_QUOTE ][1] 
      = "misquoted literal... expected double quote!";
    }
  
    public static final int ER_EXPECTED_SINGLE_QUOTE  = 27;
    static 
    {
      contents[ER_EXPECTED_SINGLE_QUOTE ][1] 
      = "misquoted literal... expected single quote!";
    }
  
    public static final int ER_EMPTY_EXPRESSION  = 28;
    static 
    {
      contents[ER_EMPTY_EXPRESSION ][1] 
      = "Empty expression!";
    }
  
    public static final int ER_EXPECTED_BUT_FOUND  = 29;
    static 
    {
      contents[ER_EXPECTED_BUT_FOUND ][1] 
      = "Expected {0}, but found: {1}";
    }
  
    public static final int ER_INCORRECT_PROGRAMMER_ASSERTION  = 30;
    static 
    {
      contents[ER_INCORRECT_PROGRAMMER_ASSERTION ][1] 
      = "Programmer assertion is incorrect! - {0}";
    }
  
    public static final int ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL  = 31;
    static 
    {
      contents[ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL ][1] 
      = "boolean(...) argument is no longer optional with 19990709 XPath 
draft.";
    }
  
    public static final int ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG  = 32;
    static 
    {
      contents[ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG ][1] 
      = "Found ',' but no preceding argument!";
    }
  
    public static final int ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG  = 33;
    static 
    {
      contents[ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG ][1] 
      = "Found ',' but no following argument!";
    }
  
    public static final int ER_PREDICATE_ILLEGAL_SYNTAX  = 34;
    static 
    {
      contents[ER_PREDICATE_ILLEGAL_SYNTAX ][1] 
      = "'..[predicate]' or '.[predicate]' is illegal syntax.  Use 
'self::node()[predicate]' instead.";
    }
  
    public static final int ER_ILLEGAL_AXIS_NAME  = 35;
    static 
    {
      contents[ER_ILLEGAL_AXIS_NAME ][1] 
      = "illegal axis name: {0}";
    }
  
    public static final int ER_UNKNOWN_NODETYPE  = 36;
    static 
    {
      contents[ER_UNKNOWN_NODETYPE ][1] 
      = "Unknown nodetype: {0}";
    }
  
    public static final int ER_PATTERN_LITERAL_NEEDS_BE_QUOTED  = 37;
    static 
    {
      contents[ER_PATTERN_LITERAL_NEEDS_BE_QUOTED ][1] 
      = "Pattern literal ({0}) needs to be quoted!";
    }
  
    public static final int ER_COULDNOT_BE_FORMATTED_TO_NUMBER  = 38;
    static 
    {
      contents[ER_COULDNOT_BE_FORMATTED_TO_NUMBER ][1] 
      = "{0} could not be formatted to a number!";
    }
  
    public static final int ER_COULDNOT_CREATE_XMLPROCESSORLIAISON  = 39;
    static 
    {
      contents[ER_COULDNOT_CREATE_XMLPROCESSORLIAISON ][1] 
      = "Could not create XML Processor Liaison: {0}";
    }
  
    public static final int ER_DIDNOT_FIND_XPATH_SELECT_EXP  = 40;
    static 
    {
      contents[ER_DIDNOT_FIND_XPATH_SELECT_EXP ][1] 
      = "Error! Did not find xpath select expression (-select).";
    }
  
    public static final int ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH  = 41;
    static 
    {
      contents[ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH ][1] 
      = "ERROR! Could not find ENDOP after OP_LOCATIONPATH";
    }
  
    public static final int ER_ERROR_OCCURED  = 42;
    static 
    {
      contents[ER_ERROR_OCCURED ][1] 
      = "Error occured!";
    }
  
    public static final int ER_ILLEGAL_VARIABLE_REFERENCE  = 43;
    static 
    {
      contents[ER_ILLEGAL_VARIABLE_REFERENCE][1] 
      = "VariableReference given for variable out of context or without 
definition!  Name = {0}";
    }
  
    public static final int ER_AXES_NOT_ALLOWED  = 44;
    static 
    {
      contents[ER_AXES_NOT_ALLOWED][1] 
      = "Only child:: and attribute:: axes are allowed in match patterns!  
Offending axes = {0}";
    }
  
    public static final int ER_KEY_HAS_TOO_MANY_ARGS  = 45;
    static 
    {
      contents[ER_KEY_HAS_TOO_MANY_ARGS ][1] 
      = "key() has an incorrect number of arguments.";
    }
  
    public static final int ER_COUNT_TAKES_1_ARG  = 46;
    static 
    {
      contents[ER_COUNT_TAKES_1_ARG ][1] 
      = "The count function should take one argument!";
    }
  
    public static final int ER_COULDNOT_FIND_FUNCTION  = 47;
    static 
    {
      contents[ER_COULDNOT_FIND_FUNCTION ][1] 
      = "Could not find function: {0}";
    }
    
    public static final int ER_UNSUPPORTED_ENCODING  = 48;
    static 
    {
      contents[ER_UNSUPPORTED_ENCODING ][1] 
      = "Unsupported encoding: {0}";
    }
    
    public static final int ER_PROBLEM_IN_DTM_NEXTSIBLING  = 49;
    static 
    {
      contents[ER_PROBLEM_IN_DTM_NEXTSIBLING ][1] 
      = "Problem occured in DTM in getNextSibling... trying to recover";
    }
    
    public static final int ER_CANNOT_WRITE_TO_EMPTYNODELISTIMPL  = 50;
    static 
    {
      contents[ER_CANNOT_WRITE_TO_EMPTYNODELISTIMPL ][1] 
      = "Programmer error: EmptyNodeList can not be written to.";
    }
    
    public static final int ER_SETDOMFACTORY_NOT_SUPPORTED  = 51;
    static 
    {
      contents[ER_SETDOMFACTORY_NOT_SUPPORTED ][1] 
      = "setDOMFactory is not supported by XPathContext!";
    }
    
    public static final int ER_PREFIX_MUST_RESOLVE  = 52;
    static 
    {
      contents[ER_PREFIX_MUST_RESOLVE ][1] 
        = "Prefix must resolve to a namespace: {0}";
    }
    
    public static final int ER_PARSE_NOT_SUPPORTED  = 53;
    static 
    {
      contents[ER_PARSE_NOT_SUPPORTED ][1] 
        = "parse (InputSource source) not supported in XPathContext! Can not 
open {0}";
    }
    
    public static final int ER_CREATEDOCUMENT_NOT_SUPPORTED  = 54;
    static 
    {
      contents[ER_CREATEDOCUMENT_NOT_SUPPORTED ][1] 
        = "createDocument() not supported in XPathContext!";
    }
    
    public static final int ER_CHILD_HAS_NO_OWNER_DOCUMENT  = 55;
    static 
    {
      contents[ER_CHILD_HAS_NO_OWNER_DOCUMENT ][1] 
        = "Attribute child does not have an owner document!";
    }
  
    public static final int ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT  = 56;
    static 
    {
      contents[ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT ][1] 
        = "Attribute child does not have an owner document element!";
    }
    
    public static final int ER_SAX_API_NOT_HANDLED  = 57;
    static 
    {
      contents[ER_SAX_API_NOT_HANDLED ][1] 
        = "SAX API characters(char ch[]... not handled by the DTM!";
    }
    
    public static final int ER_IGNORABLE_WHITESPACE_NOT_HANDLED  = 58;
    static 
    {
      contents[ER_IGNORABLE_WHITESPACE_NOT_HANDLED ][1] 
        = "ignorableWhitespace(char ch[]... not handled by the DTM!";
    }
    
    public static final int ER_DTM_CANNOT_HANDLE_NODES  = 59;
    static 
    {
      contents[ER_DTM_CANNOT_HANDLE_NODES ][1] 
        = "DTMLiaison can not handle nodes of type {0}";
    }
    
    public static final int ER_XERCES_CANNOT_HANDLE_NODES  = 60;
    static 
    {
      contents[ER_XERCES_CANNOT_HANDLE_NODES ][1] 
        = "DOM2Helper can not handle nodes of type {0}";
    }
    
    public static final int ER_XERCES_PARSE_ERROR_DETAILS  = 61;
    static 
    {
      contents[ER_XERCES_PARSE_ERROR_DETAILS ][1] 
        = "DOM2Helper.parse error: SystemID - {0} line - {1}";
    }
    
    public static final int ER_XERCES_PARSE_ERROR  = 62;
    static 
    {
      contents[ER_XERCES_PARSE_ERROR ][1] 
        = "DOM2Helper.parse error";
    }
    
    public static final int ER_CANT_OUTPUT_TEXT_BEFORE_DOC  = 63;
    static 
    {
      contents[ER_CANT_OUTPUT_TEXT_BEFORE_DOC ][1] 
        = "Warning: can't output text before document element!  Ignoring...";
    }
    
    public static final int ER_CANT_HAVE_MORE_THAN_ONE_ROOT  = 64;
    static 
    {
      contents[ER_CANT_HAVE_MORE_THAN_ONE_ROOT ][1] 
        = "Can't have more than one root on a DOM!";
    }
    
    public static final int ER_INVALID_UTF16_SURROGATE  = 65;
    static 
    {
      contents[ER_INVALID_UTF16_SURROGATE ][1] 
        = "Invalid UTF-16 surrogate detected: {0} ?";
    }
    
    public static final int ER_OIERROR  = 66;
    static 
    {
      contents[ER_OIERROR ][1] 
        = "IO error";
    }
    
    public static final int ER_CANNOT_CREATE_URL  = 67;
    static 
    {
      contents[ER_CANNOT_CREATE_URL ][1] 
        = "Cannot create url for: {0}";
    }
    
    public static final int ER_XPATH_READOBJECT  = 68;
    static 
    {
      contents[ER_XPATH_READOBJECT ][1] 
        = "In XPath.readObject: {0}";
    }
  
    // Warnings...
  
    public static final int WG_LOCALE_NAME_NOT_HANDLED  = 1;
    static 
    {
      contents[WG_LOCALE_NAME_NOT_HANDLED  + MAX_CODE][1] 
      = "locale name in the format-number function not yet handled!";
    }
  
    public static final int WG_PROPERTY_NOT_SUPPORTED  = 2;
    static 
    {
      contents[WG_PROPERTY_NOT_SUPPORTED  + MAX_CODE][1] 
      = "XSL Property not supported: {0}";
    }
  
    public static final int WG_DONT_DO_ANYTHING_WITH_NS  = 3;
    static 
    {
      contents[WG_DONT_DO_ANYTHING_WITH_NS  + MAX_CODE][1] 
      = "Do not currently do anything with namespace {0} in property: {1}";
    }
  
    public static final int WG_SECURITY_EXCEPTION  = 4;
    static 
    {
      contents[WG_SECURITY_EXCEPTION  + MAX_CODE][1] 
      = "SecurityException when trying to access XSL system property: {0}";
    }
  
    public static final int WG_QUO_NO_LONGER_DEFINED  = 5;
    static 
    {
      contents[WG_QUO_NO_LONGER_DEFINED  + MAX_CODE][1] 
      = "Old syntax: quo(...) is no longer defined in XPath.";
    }
  
  
    public static final int WG_NEED_DERIVED_OBJECT_TO_IMPLEMENT_NODETEST  = 6;
    static 
    {
      contents[WG_NEED_DERIVED_OBJECT_TO_IMPLEMENT_NODETEST  + MAX_CODE][1] 
      = "XPath needs a derived object to implement nodeTest!";
    }
  
    public static final int WG_FUNCTION_TOKEN_NOT_FOUND  = 7;
    static 
    {
      contents[WG_FUNCTION_TOKEN_NOT_FOUND  + MAX_CODE][1] 
      = "function token not found.";
    }
  
    public static final int WG_COULDNOT_FIND_FUNCTION  = 8;
    static 
    {
      contents[WG_COULDNOT_FIND_FUNCTION  + MAX_CODE][1] 
      = "Could not find function: {0}";
    }
  
    public static final int WG_CANNOT_MAKE_URL_FROM  = 9;
    static 
    {
      contents[WG_CANNOT_MAKE_URL_FROM  + MAX_CODE][1] 
      = "Can not make URL from: {0}";
    }
  
    public static final int WG_EXPAND_ENTITIES_NOT_SUPPORTED  = 10;
    static 
    {
      contents[WG_EXPAND_ENTITIES_NOT_SUPPORTED  + MAX_CODE][1] 
      = "-E option not supported for DTM parser";
    }
  
    // Other miscellaneous text used inside the code...
  
    static  
    {
      
      contents[MAX_MESSAGES][0] = "ui_language";
      contents[MAX_MESSAGES][1] = "en";
      
      contents[MAX_MESSAGES + 1][0] = "help_language";
      contents[MAX_MESSAGES + 1][1] = "en";
      
      contents[MAX_MESSAGES + 2][0] = "language";
      contents[MAX_MESSAGES + 2][1] = "en";
      
      contents[MAX_MESSAGES + 3][0] = "BAD_CODE";
      contents[MAX_MESSAGES + 3][1] = "Parameter to createMessage was out of 
bounds";
      
      contents[MAX_MESSAGES + 4][0] = "FORMAT_FAILED";
      contents[MAX_MESSAGES + 4][1] = "Exception thrown during messageFormat 
call";
      
      contents[MAX_MESSAGES + 5][0] = "version";
      contents[MAX_MESSAGES + 5][1] = ">>>>>>> Xalan Version ";
      
      contents[MAX_MESSAGES + 6][0] = "version2";
      contents[MAX_MESSAGES + 6][1] = "<<<<<<<";
      
      contents[MAX_MESSAGES + 7][0] = "yes";
      contents[MAX_MESSAGES + 7][1] = "yes";
      
      contents[MAX_MESSAGES + 8][0] = "line";
      contents[MAX_MESSAGES + 8][1] = "Line #";
      
      contents[MAX_MESSAGES + 9][0] = "column";
      contents[MAX_MESSAGES + 9][1] = "Column #";
      
      contents[MAX_MESSAGES + 10][0] = "xsldone";
      contents[MAX_MESSAGES + 10][1] = "XSLProcessor: done";
      
      contents[MAX_MESSAGES + 11][0] = "xpath_option";
      contents[MAX_MESSAGES + 11][1] = "xpath options: ";
      
      contents[MAX_MESSAGES + 12][0] = "optionIN";
      contents[MAX_MESSAGES + 12][1] = "   [-in inputXMLURL]";
      
      contents[MAX_MESSAGES + 13][0] = "optionSelect";
      contents[MAX_MESSAGES + 13][1] = "   [-select xpath expression]";
      
      contents[MAX_MESSAGES + 14][0] = "optionMatch";
      contents[MAX_MESSAGES + 14][1] = "   [-match match pattern (for match 
diagnostics)]";
      
      contents[MAX_MESSAGES + 15][0] = "optionAnyExpr";
      contents[MAX_MESSAGES + 15][1] = "Or just an xpath expression will do a 
diagnostic dump";
      
  
      contents[MAX_MESSAGES + 16][0] = "noParsermsg1";
      contents[MAX_MESSAGES + 16][1] = "XSL Process was not successful.";
      
      contents[MAX_MESSAGES + 17][0] = "noParsermsg2";
      contents[MAX_MESSAGES + 17][1] = "** Could not find parser **";
  
      contents[MAX_MESSAGES + 18][0] = "noParsermsg3";
      contents[MAX_MESSAGES + 18][1] = "Please check your classpath.";
  
      contents[MAX_MESSAGES + 19][0] = "noParsermsg4"; 
      contents[MAX_MESSAGES + 19][1] = "If you don't have IBM's XML Parser for 
Java, you can download it from";
      
      contents[MAX_MESSAGES + 20][0] = "noParsermsg5";
      contents[MAX_MESSAGES + 20][1] = "IBM's AlphaWorks: 
http://www.alphaworks.ibm.com/formula/xml";;
    }
  
    // ================= INFRASTRUCTURE ======================
  
    public static final String BAD_CODE = "BAD_CODE";
    public static final String FORMAT_FAILED = "FORMAT_FAILED";
  
    public static final String ERROR_RESOURCES = 
"org.apache.xalan.xpath.res.XPATHErrorResources";
    
    public static final String ERROR_STRING = "#error";
    public static final String ERROR_HEADER = "Error: ";
    public static final String WARNING_HEADER = "Warning: ";
    public static final String XSL_HEADER = "XSL ";
    public static final String XML_HEADER = "XML ";
    public static final String QUERY_HEADER = "PATTERN ";
  
    public Object[][] getContents()
    {
      return contents;
    }
  
    /**
     * Return a named ResourceBundle for a particular locale.  This method 
mimics the behavior
     * of ResourceBundle.getBundle(). 
     *
     * @param res the name of the resource to load. 
     * @param locale the locale to prefer when searching for the bundle
     * @return the ResourceBundle
     * @throws MissingResourceException  
     */
    public static final XPATHErrorResources loadResourceBundle (String 
className) 
      throws MissingResourceException
    {
      Locale locale = Locale.getDefault();
      String suffix = getResourceSuffix(locale);  
      try
      {         
        // first try with the given locale
        return (XPATHErrorResources)ResourceBundle.getBundle (className + 
suffix, locale);
      }
      catch (MissingResourceException e)
      {
        try                                                  // try to fall 
back to en_US if we can't load
        {
          // Since we can't find the localized property file,
          // fall back to en_US.
          return (XPATHErrorResources)ResourceBundle.getBundle (className, new 
Locale ("en", "US"));
        }
        catch (MissingResourceException e2)
        {
          // Now we are really in trouble.
          // very bad, definitely very bad...not going to get very far
          throw new MissingResourceException ("Could not load any resource 
bundles.", className, "");
        }
      }
    }
    
    /**
     * Return the resource file suffic for the indicated locale
     * For most locales, this will be based the language code.  However
     * for Chinese, we do distinguish between Taiwan and PRC
     *
     * @param locale the locale
     * @return an String suffix which canbe appended to a resource name
     */        
    private static final String getResourceSuffix(Locale locale)
    {
      String suffix = "_" + locale.getLanguage();
      
      String country = locale.getCountry();        
      
      if (country.equals("TW"))
        suffix += "_" + country;
  
      return suffix;
    }
    
    /**
     * Get the error string associated with the error code
     */ 
    public String getMessageKey(int errorCode)
    {
      if (errorCode > MAX_CODE)
        return null;
      else
      {
        DecimalFormat df = new DecimalFormat("0000");
        return ERROR_SUFFIX + df.format(errorCode);     
      }  
    }
    
    /**
     * Get the error string associated with the error code
     */ 
    public String getWarningKey(int errorCode)
    {
      if (errorCode > MAX_WARNING)
        return null;
      else 
      {
        DecimalFormat df = new DecimalFormat("0000");
        return WARNING_SUFFIX + df.format(errorCode);   
      }
    }
    
    /**
     * Get the error string associated with the error code
     */ 
    public static String getMKey(int errorCode)
    {
      if (errorCode > MAX_CODE)
        return null;
      else
      {
        DecimalFormat df = new DecimalFormat("0000");
        return ERROR_SUFFIX + df.format(errorCode);     
      }  
    }
    
    /**
     * Get the error string associated with the error code
     */ 
    public static String getWKey(int errorCode)
    {
      if (errorCode > MAX_WARNING)
        return null;
      else 
      {
        DecimalFormat df = new DecimalFormat("0000");
        return WARNING_SUFFIX + df.format(errorCode);   
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xpath/res/XPATHErrorResources_en.java
  
  Index: XPATHErrorResources_en.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xpath.res;
  import java.util.*;
  
  /**
   * <meta name="usage" content="advanced"/>
   * Default implementation of XPATHErrorResources.  This is just 
   * an empty class.
   */
  public class XPATHErrorResources_en extends XPATHErrorResources 
  {    
  }
  
  
  
  1.1                  xml-xalan/java/src/org/apache/xalan/xslt/Process.java
  
  Index: Process.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xslt;
  
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.FileWriter;
  import java.io.InputStream;
  import java.io.BufferedInputStream;
  import java.io.ObjectOutputStream;
  import java.io.ObjectInputStream;
  import java.io.OutputStream;
  import java.io.PrintWriter;
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import java.io.StringReader;
  
  import java.net.MalformedURLException;
  import java.net.URL;
  
  import java.lang.reflect.Constructor;
  
  import java.util.TooManyListenersException;
  import java.util.Vector;
  import java.util.Properties;
  import java.util.Enumeration;
  
  // Needed Xalan classes
  import org.apache.xalan.res.XSLMessages;
  
  import org.apache.xalan.processor.XSLProcessorVersion;
  
  import org.apache.xalan.res.XSLTErrorResources;
  
  import org.apache.xalan.templates.Constants;
  import org.apache.xalan.templates.ElemTemplateElement;
  import org.apache.xalan.templates.StylesheetRoot;
  
  import org.apache.xalan.transformer.TransformerImpl;
  
  import org.apache.xalan.trace.PrintTraceListener;
  import org.apache.xalan.trace.TraceListener;
  import org.apache.xalan.trace.TraceManager;
  
  // Needed Xerces classes
  import org.apache.xerces.parsers.DOMParser;
  
  // Needed TRaX classes
  import trax.Result;
  import trax.Processor;
  import trax.ProcessorFactoryException;
  import trax.Transformer;
  import trax.Templates;
  
  // Needed SAX classes
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  import org.xml.sax.SAXParseException;
  import org.xml.sax.XMLReader;
  import org.xml.sax.helpers.ParserAdapter;
  import org.xml.sax.helpers.XMLReaderFactory;
  
  // Needed DOM classes
  import org.w3c.dom.Node;
  import org.w3c.dom.Document;
  
  // Needed Serializer classes
  import org.apache.xml.serialize.OutputFormat;
  import org.apache.xml.serialize.Serializer;
  import org.apache.xml.serialize.SerializerFactory;
  
  
  /**
   * <meta name="usage" content="general"/>
   * The main() method handles the Xalan command-line interface.
   */
  public class Process
  {
    /*
    * Retrieve a propery bundle from a specified file and load it 
    * int the System properties.
    * @param file The string name of the property file.  
    */
    private static void loadPropertyFileToSystem(String file) 
    {
      InputStream is;
      try
      {                    
        Properties props = new Properties();
        is = Process.class.getResourceAsStream(file);    
        // get a buffered version
        BufferedInputStream bis = new BufferedInputStream (is);
        props.load (bis);                                     // and load up 
the property bag from this
        bis.close ();                                          // close out 
after reading
        // OK, now we only want to set system properties that 
        // are not already set.
        Properties systemProps = System.getProperties();
        Enumeration propEnum = props.propertyNames();
        while(propEnum.hasMoreElements())
        {
          String prop = (String)propEnum.nextElement();
          if(!systemProps.containsKey(prop))
            systemProps.put(prop, props.getProperty(prop));
        }
        System.setProperties(systemProps);
      }
      catch (Exception ex)
      {
        ex.printStackTrace();
      }
    }
  
    /**
     * Prints argument options.
     */
    protected static void printArgOptions(XSLTErrorResources resbundle)
    {
      System.out.println(resbundle.getString("xslProc_option")); //"xslproc 
options: ");
      System.out.println(resbundle.getString("optionIN")); //"    -IN 
inputXMLURL");
      System.out.println(resbundle.getString("optionXSL")); //"   [-XSL 
XSLTransformationURL]");
      System.out.println(resbundle.getString("optionOUT")); //"   [-OUT 
outputFileName]");
      System.out.println(resbundle.getString("optionLXCIN")); //"   [-LXCIN 
compiledStylesheetFileNameIn]");
      System.out.println(resbundle.getString("optionLXCOUT")); //"   [-LXCOUT 
compiledStylesheetFileNameOutOut]");
      System.out.println(resbundle.getString("optionPARSER")); //"   [-PARSER 
fully qualified class name of parser liaison]");
      // System.out.println(resbundle.getString("optionE")); //"   [-E (Do not 
expand entity refs)]");
      System.out.println(resbundle.getString("optionV")); //"   [-V (Version 
info)]");
      System.out.println(resbundle.getString("optionQC")); //"   [-QC (Quiet 
Pattern Conflicts Warnings)]");
      System.out.println(resbundle.getString("optionQ")); //"   [-Q  (Quiet 
Mode)]");
      System.out.println(resbundle.getString("optionLF")); //"   [-LF (Use 
linefeeds only on output {default is CR/LF})]");
      System.out.println(resbundle.getString("optionCR")); //"   [-CR (Use 
carriage returns only on output {default is CR/LF})]");
      System.out.println(resbundle.getString("optionINDENT")); //"   [-INDENT 
(Control how many spaces to indent {default is 0})]");
      System.out.println(resbundle.getString("optionTT")); //"   [-TT (Trace 
the templates as they are being called.)]");
      System.out.println(resbundle.getString("optionTG")); //"   [-TG (Trace 
each generation event.)]");
      System.out.println(resbundle.getString("optionTS")); //"   [-TS (Trace 
each selection event.)]");
      System.out.println(resbundle.getString("optionTTC")); //"   [-TTC (Trace 
the template children as they are being processed.)]");
      System.out.println(resbundle.getString("optionTCLASS")); //"   [-TCLASS 
(TraceListener class for trace extensions.)]");
      System.out.println(resbundle.getString("optionVALIDATE")); //"   
[-VALIDATE (Set whether validation occurs.  Validation is off by default.)]");
      System.out.println(resbundle.getString("optionEDUMP")); //"   [-EDUMP 
{optional filename} (Do stackdump on error.)]");
      System.out.println(resbundle.getString("optionXML")); //"   [-XML (Use 
XML formatter and add XML header.)]");
      System.out.println(resbundle.getString("optionTEXT")); //"   [-TEXT (Use 
simple Text formatter.)]");
      System.out.println(resbundle.getString("optionHTML")); //"   [-HTML (Use 
HTML formatter.)]");
      System.out.println(resbundle.getString("optionPARAM")); //"   [-PARAM 
name expression (Set a stylesheet parameter)]");
      System.out.println("[-MEDIA use media attribute to find stylesheet 
associated with a document.]"); //"   [-PARAM name expression (Set a stylesheet 
parameter)]");
      System.out.println("[-SX (User Xerces Serializers]"); //"   [-PARAM name 
expression (Set a stylesheet parameter)]");
    }
    
    static String XSLT_PROPERTIES = "/org/apache/xalan/res/XSLTInfo.properties";
  
    /**
     * Command line interfact to transform the XML according to
     * the instructions found in the XSL stylesheet.
     * <pre>
     *    -IN inputXMLURL
     *    -XSL XSLTransformationURL
     *    -OUT outputFileName
     *    -LXCIN compiledStylesheetFileNameIn
     *    -LXCOUT compiledStylesheetFileNameOut
     *    -PARSER fully qualified class name of parser liaison
     *    -V (Version info)
     *    -QC (Quiet Pattern Conflicts Warnings)
     *    -Q  (Quiet Mode)
     *    -LF (Use linefeeds only on output -- default is CR/LF)
     *    -CR (Use carriage returns only on output -- default is CR/LF)
     *    -INDENT (Number of spaces to indent each level in output tree 
--default is 0)
     *    -TT (Trace the templates as they are being called)
     *    -TG (Trace each result tree generation event)
     *    -TS (Trace each selection event)
     *    -TTC (Trace the template children as they are being processed)
     *    -VALIDATE (Validate the XML and XSL input -- validation is off by 
default)
     *    -EDUMP [optional]FileName (Do stackdump on error)
     *    -XML (Use XML formatter and add XML header)
     *    -TEXT (Use simple Text formatter)
     *    -HTML (Use HTML formatter)
     *    -PARAM name expression (Set a stylesheet parameter)
     * </pre>
     *  <p>Use -IN to specify the XML source document. To specify the XSL 
stylesheet, use -XSL
     *  or -LXCIN. To compile an XSL stylesheet for future use as -LXCIN input, 
use -LXCOUT.</p>
     *  <p>Include -PARSER if you supply your own parser liaison class, which 
is required
     *  if you do not use the &xml4j; parser.</p>
     *  <p>Use -TEXT if you want the output to include only element values (not 
element tags with element names and
     *  attributes). Use -HTML to write 4.0 transitional HTML (some elements, 
such as &lt;br&gt;, are
     *  not well formed.</p>
     *  <p>To set stylesheet parameters from the command line, use -PARAM name 
expression. If
     *  you want to set the parameter to a string value, enclose the string in 
single quotes (') to
     */
    public static void main( String argv[] )
    {
      Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
      boolean doStackDumpOnError = false;
      boolean setQuietMode = false;
  
      // Runtime.getRuntime().traceMethodCalls(false);
      // Runtime.getRuntime().traceInstructions(false);
      /**
      * The default diagnostic writer...
      */
      java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true);
      java.io.PrintWriter dumpWriter = diagnosticsWriter;
  
      XSLTErrorResources resbundle = 
(XSLTErrorResources)(XSLMessages.loadResourceBundle(Constants.ERROR_RESOURCES));
      loadPropertyFileToSystem(XSLT_PROPERTIES);
  
      if(argv.length < 1)
      {
        printArgOptions(resbundle);
      }
      else
      {
        Processor processor;
        try
        {
          processor = Processor.newInstance("xslt");
        }
        catch(ProcessorFactoryException pfe)
        {
          if(doStackDumpOnError)
            pfe.printStackTrace(dumpWriter);
          
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null)); //"XSL Process was not successful.");
          processor = null; // shut up compiler
          System.exit(-1);
        }
        boolean formatOutput = false;
        String inFileName = null;
        String outFileName = null;
        String dumpFileName = null;
        String xslFileName = null;
        String compiledStylesheetFileNameOut = null;
        String compiledStylesheetFileNameIn = null;
        String treedumpFileName = null;
        PrintTraceListener tracer = null;
        String outputType = null;
        String media = null;
        Vector params = new Vector();
        boolean quietConflictWarnings = false;
  
        for (int i = 0;  i < argv.length;  i ++)
        {
          if("-TT".equalsIgnoreCase(argv[i]))
          {
            if(null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);
            tracer.m_traceTemplates = true;
            // processor.setTraceTemplates(true);
          }
          else if("-TG".equalsIgnoreCase(argv[i]))
          {
            if(null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);
            tracer.m_traceGeneration = true;
            // processor.setTraceSelect(true);
          }
          else if("-TS".equalsIgnoreCase(argv[i]))
          {
            if(null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);
            tracer.m_traceSelection = true;
            // processor.setTraceTemplates(true);
          }
          else if("-TTC".equalsIgnoreCase(argv[i]))
          {
            if(null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);
            tracer.m_traceElements = true;
            // processor.setTraceTemplateChildren(true);
          }
          else if ("-INDENT".equalsIgnoreCase(argv[i]))
          {
            int indentAmount;
            if(((i+1) < argv.length) && (argv[i+1].charAt(0) != '-'))
            {
              indentAmount = Integer.parseInt( argv[++i] );
            }
            else
            {
              indentAmount = 0;
            }
            // TBD:
            // xmlProcessorLiaison.setIndent(indentAmount);
          }
          else if ("-IN".equalsIgnoreCase(argv[i]))
          {
            if ( i+1 < argv.length)
              inFileName = argv[++i];
            else
              
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
 new Object[] {"-IN"})); //"Missing argument for);
  
          }
          else if ("-MEDIA".equalsIgnoreCase(argv[i]))
          {
            if ( i+1 < argv.length)
              media = argv[++i];
            else
              
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
 new Object[] {"-MEDIA"})); //"Missing argument for);
  
          }
  
          else if ("-OUT".equalsIgnoreCase(argv[i]))
          {
            if ( i+1 < argv.length)
              outFileName = argv[++i];
            else
              
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
 new Object[] {"-OUT"})); //"Missing argument for);
  
          }
          else if ("-XSL".equalsIgnoreCase(argv[i]))
          {
            if ( i+1 < argv.length)
              xslFileName = argv[++i];
            else
              
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
 new Object[] {"-XSL"})); //"Missing argument for);
  
          }
          else if("-LXCIN".equalsIgnoreCase(argv[i]))
          {
            if ( i+1 < argv.length)
              compiledStylesheetFileNameIn = argv[++i];
            else
              
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
 new Object[] {"-LXCIN"})); //"Missing argument for);
  
          }
          else if("-LXCOUT".equalsIgnoreCase(argv[i]))
          {
            if ( i+1 < argv.length)
              compiledStylesheetFileNameOut = argv[++i];
            else
              
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
 new Object[] {"-LXCOUT"})); //"Missing argument for);
  
          }
          else if ("-PARAM".equalsIgnoreCase(argv[i]))
          {
            if ( i+2 < argv.length)
            {
              String name = argv[++i];
              params.addElement(name);
              String expression = argv[++i];
              params.addElement(expression);
            }
            else
              
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
 new Object[] {"-PARAM"})); //"Missing argument for);
  
          }
          else if ("-treedump".equalsIgnoreCase(argv[i]))
          {
            if ( i+1 < argv.length)
              treedumpFileName = argv[++i];
            else
              
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
 new Object[] {"-treedump"})); //"Missing argument for);
  
          }
          else if("-F".equalsIgnoreCase(argv[i]))
          {
            formatOutput = true;
          }
          else if("-E".equalsIgnoreCase(argv[i]))
          {
            // TBD:
            // xmlProcessorLiaison.setShouldExpandEntityRefs(false);
          }
          else if("-V".equalsIgnoreCase(argv[i]))
          {
            diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> 
Xalan Version "
                                      +XSLProcessorVersion.S_VERSION+", "+
                                      /* 
xmlProcessorLiaison.getParserDescription()+ */
                                      resbundle.getString("version2"));// 
"<<<<<<<");
          }
          else if("-QC".equalsIgnoreCase(argv[i]))
          {
            quietConflictWarnings = true;
          }
          else if("-Q".equalsIgnoreCase(argv[i]))
          {
            setQuietMode = true;
          }
          else if("-VALIDATE".equalsIgnoreCase(argv[i]))
          {
            String shouldValidate;
            if(((i+1) < argv.length) && (argv[i+1].charAt(0) != '-'))
            {
              shouldValidate = argv[++i];
            }
            else
            {
              shouldValidate = "yes";
            }
  
            // 
xmlProcessorLiaison.setUseValidation(shouldValidate.equalsIgnoreCase("yes"));
          }
          else if("-PARSER".equalsIgnoreCase(argv[i]))
          {
            i++;
            // Handled above
          }
          else if("-XML".equalsIgnoreCase(argv[i]))
          {
            outputType = "xml";
          }
          else if("-TEXT".equalsIgnoreCase(argv[i]))
          {
            outputType = "text";
          }
          else if("-HTML".equalsIgnoreCase(argv[i]))
          {
            outputType = "html";
          }
          else if("-EDUMP".equalsIgnoreCase(argv[i]))
          {
            doStackDumpOnError = true;
            if(((i+1) < argv.length) && (argv[i+1].charAt(0) != '-'))
            {
              dumpFileName = argv[++i];
            }
          }
          else
            
System.err.println(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_OPTION,
 new Object[] {argv[i]})); //"Invalid argument:);
  
        }
  
        // The main XSL transformation occurs here!
        try
        {
          if(null != dumpFileName)
          {
            dumpWriter = new PrintWriter( new FileWriter(dumpFileName) );
          }
  
          Templates stylesheet = null;
  
          if(null != compiledStylesheetFileNameIn)
          {
            try
            {
              FileInputStream fileInputStream
                = new FileInputStream(compiledStylesheetFileNameIn);
              ObjectInputStream objectInput
                = new ObjectInputStream(fileInputStream);
              stylesheet = (Templates)objectInput.readObject();
              objectInput.close();
            }
            catch(java.io.UnsupportedEncodingException uee)
            {
              stylesheet = null;
              // 
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_ENCODING_NOT_SUPPORTED,
 new Object[] {stylesheet.getOutputEncoding()})); //"Encoding not supported: 
"+stylesheet.m_encoding);
              // throw new 
XSLProcessorException(XSLMessages.createMessage(XSLTErrorResources.ER_ENCODING_NOT_SUPPORTED,
 new Object[] {stylesheet.getOutputEncoding()})); //"Encoding not supported: 
"+stylesheet.m_encoding);
            }
          }
          else if(null != xslFileName)
          {
            stylesheet = processor.process(new InputSource(xslFileName));
          }
  
          PrintWriter resultWriter;
  
          OutputStream outputStream = (null != outFileName) ? 
                                      new FileOutputStream(outFileName) :
                                      (OutputStream)System.out;
  
          // Did they pass in a stylesheet, or should we get it from the 
          // document?
          if(null == stylesheet)
          {
            InputSource[] sources = processor.getAssociatedStylesheets(new 
InputSource(inFileName),
                                                                       media, 
null, null);
            if(null != sources)
              stylesheet = processor.processMultiple(sources);
            else
              throw new SAXException("No stylesheet found for media: "+media);
          }
  
          if(null != stylesheet)
          {
            if(null != compiledStylesheetFileNameOut)
            {
              FileOutputStream compiledStylesheetOutputStream
                = new FileOutputStream(compiledStylesheetFileNameOut);
              ObjectOutputStream compiledStylesheetOutput
                = new ObjectOutputStream(compiledStylesheetOutputStream);
  
              compiledStylesheetOutput.writeObject(stylesheet);
            }
  
            Transformer transformer = stylesheet.newTransformer();
            
            // Override the output format?
            if(null != outputType)
            {
              OutputFormat of = stylesheet.getOutputFormat();
              of.setMethod(outputType);
              transformer.setOutputFormat(of);
            }
            
            if(transformer instanceof TransformerImpl)
            {
              TransformerImpl impl = ((TransformerImpl)transformer);
              TraceManager tm = impl.getTraceManager();
              
              if(null != tracer)
                tm.addTraceListener(tracer);
              
              impl.setQuietConflictWarnings(quietConflictWarnings);
              // impl.setDiagnosticsOutput( setQuietMode ? null : 
diagnosticsWriter );
  
            }
            int nParams = params.size();
            for(int i = 0; i < nParams; i+=2)
              transformer.setParameter((String)params.elementAt(i), null,
                                       (String)params.elementAt(i+1));
            
            if(null != inFileName)
            {
              transformer.transform(new InputSource(inFileName), new 
Result(outputStream));
            }
            else
            {
              StringReader reader = new StringReader("<?xml version=\"1.0\"?> 
<doc/>");
              transformer.transform(new InputSource(reader), new 
Result(outputStream));
            }
          }
          else
          {
            
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null)); //"XSL Process was not successful.");
            System.exit(-1);
          }
          
        }
        catch(SAXParseException spe)
        {
          Exception containedException = spe.getException();
          if(null != containedException)
          {
            if(doStackDumpOnError)
            {
              containedException = spe;
              while(containedException instanceof SAXException)
              {
                containedException.printStackTrace(dumpWriter);
                containedException = 
((SAXException)containedException).getException();
                dumpWriter.println("====================");
              }
              if(null != containedException)
              {
                containedException.printStackTrace(dumpWriter);
                dumpWriter.println("====================");
             }
            }
            // else
            //  System.out.println("Error! "+se.getMessage());
            
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null)); //"XSL Process was not successful.");
          }
          else
          {
            if(doStackDumpOnError)
              spe.printStackTrace(dumpWriter);
            // else
            //  System.out.println("Error! "+se.getMessage());
            
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null) ); //"XSL Process was not successful.");
          }
          diagnosticsWriter.println(" ID: "+spe.getSystemId()
                                    +" Line #"+spe.getLineNumber()
                                    +" Column #"+spe.getColumnNumber());
          System.exit(-1);
        }      
        catch(TooManyListenersException tmle)
        {
          if(doStackDumpOnError)
            tmle.printStackTrace(dumpWriter);
          // else
          //  System.out.println("Error! "+se.getMessage());
          
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null)); //"XSL Process was not successful.");
          System.exit(-1);
        }
  
        catch(SAXException se)
        {
          Exception containedException = se.getException();
          if(null != containedException)
          {
            if(doStackDumpOnError)
              containedException.printStackTrace(dumpWriter);
            // else
            //  System.out.println("Error! "+se.getMessage());
            
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null)); //"XSL Process was not successful.");
          }
          else
          {
            if(doStackDumpOnError)
              se.printStackTrace(dumpWriter);
            // else
            //  System.out.println("Error! "+se.getMessage());
            
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null) ); //"XSL Process was not successful.");
          }
          System.exit(-1);
        }
        catch(ClassNotFoundException cnfe)
        {
          if(doStackDumpOnError)
            cnfe.printStackTrace(dumpWriter);
          else
            System.out.println("Error! "+cnfe.getMessage());
          
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null)); //"XSL Process was not successful.");
          System.exit(-1);
        }
        catch(IOException ioe)
        {
          if(doStackDumpOnError)
            ioe.printStackTrace(dumpWriter);
          else
            System.out.println("Error! "+ioe.getMessage());
          
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null)); //"XSL Process was not successful.");
          System.exit(-1);
        }
        catch(RuntimeException rte)
        {
          if(doStackDumpOnError)
            rte.printStackTrace(dumpWriter);
          else
            System.out.println("Error! "+rte.getMessage());
          
diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
 null)); //"XSL Process was not successful.");
          System.exit(-1);
        }
  
        if(null != dumpFileName)
        {
          dumpWriter.close();
        }
        if(null != diagnosticsWriter)
        {
          // diagnosticsWriter.close();
        }
        // if(!setQuietMode)
        //  diagnosticsWriter.println(resbundle.getString("xsldone")); 
//"Xalan: done");
        // else
          diagnosticsWriter.println(""); //"Xalan: done");
      }
    }
  }
  
  
  
  1.1                  
xml-xalan/java/src/org/apache/xalan/xslt/StylesheetSpec.java
  
  Index: StylesheetSpec.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 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 "Xalan" 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 [EMAIL PROTECTED]
   *
   * 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 and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.xalan.xslt;
  
  import org.xml.sax.InputSource;
  
  /**
   * <meta name="usage" content="general"/>
   * This class implements the representation of a stylesheet 
   * specification via xml-stylesheet in an XML document.
   */
  public class StylesheetSpec extends InputSource
  {
    String type; // CDATA #REQUIRED
    String title; // CDATA #IMPLIED
    String media; // CDATA #IMPLIED
    boolean alternate; // (yes|no) "no"
    
    /**
     * Create a StylesheetSpec object.
     */
    public StylesheetSpec(String href, String type, String title, 
                          String media, boolean alternate,
                          String encoding)
    {
      this.setSystemId(href);
      this.setEncoding(encoding);
      this.type = type;
      this.title = title;
      this.media = media;
      this.alternate = alternate;
    }
  
    /**
     * Get the type of the stylesheet, i.e. "text/xsl".
     */
  public String       getType()
  {
      return type;
  }
  
    /**
     * Get the title of the element (in other words, the 
     * item to be presented to the user agent).
     */
    public String       getTitle()
  {
      return title;
  }
  
    /**
     * Get the media attribute of the stylesheet.
     */
    public String       getMedia()
  {
      return media;
  }
    /**
     * Get whether or not the stylesheet is specified as 
     * an alternate.
     */
  public boolean    getIsAlternate()
  {
      return alternate;
  }
  }
  
  
  

Reply via email to