<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">% $Id: xtpipes.tex 740 2020-06-13 22:35:32Z karl $

% htlatex xtpipes "xhtml,3,next" "" "-d./"
% htlatex xtpipes "xhtml,3,next,doc" "" "-d./"
% htlatex xtpipes "xhtml,3,next,win"
% htlatex xtpipes "xhtml,3,next,win,doc"

% generalize -i attribute to accept multiple directories, like for -classpath
% gcj support these ``generics''  with a ``-5'' or ``-1.5'' switch

% Copyright 2009-2020 TeX Users Group
% Copyright 1996-2009 Eitan M. Gurari
% Released under LPPL 1.3c+.
% See tex4ht-cpright.tex for license text.

\documentclass{article}
   \usepackage{url}
   \usepackage{verbatim}
   \input{common.tex}
   % make ` be the escape character, instead of |
   \Configure{ProTex}{java,&lt;&lt;&lt;&gt;&gt;&gt;,title,list,`}
\begin{document}
\input tex4ht-cpright.tex
\input tex4ht-dir.tex

\def\CNT{0}
\bgroup
   \catcode`\^=7
   \catcode`\^^M=13  %
   \gdef\OP#1{%
      \edef\temp{%
        \noexpand\&lt;#1\noexpand\&gt;&lt;&lt;&lt;
            \CNT
        &gt;&gt;&gt; %
      } \temp %
      \immediate\write15{...... \CNT\space #1}
      \HAdvance\CNT by 1 %
   }   %
\egroup

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \AddFile[optional: target file name; default: given file name]
%         (optional: target home dir; default MYDIR)
%         {file name}{dir}

\ifOption{win}
   {\def\mv{move }}
   {\def\mv{mv }}

\def\Slash{/}
{
   \catcode`\/=0
   \catcode`\\=12
   /ifOption{win}{/gdef/Slash{\}}{}
}
\def\SLASH{/}

\def\AddFile{\futurelet\ext\AddFileA}
\def\AddFileA{%
   \if [\ext \def\ext[##1]{\def\ext{##1}\futurelet\dir\AddFileB}%
   \else     \def\ext{\def\ext{}\futurelet\dir\AddFileB}\fi
   \ext}
\def\AddFileB{%
   \if (\dir \def\dir(##1){\def\dir{##1}\AddFileC}%
   \else     \def\dir{\let\dir\MYdir\AddFileC}\fi
   \dir}


\def\AddFileC#1#2{%
   \expandafter\setStartDir \dir #2!%
   \bgroup
     \def\Slash{/}%
     \xdef\EndDir{\dir
                #2\Slash
             \ifx\ext\empty
                  \if !#1!\else #1\fi
             \else \ext\fi}%
   \egroup
   \MakeDir
   \if !#1!\else
      \Needs{"\mv #1\space \dir #2\Slash
                    \ifx\ext\empty #1\else \ext\fi"}%
   \fi
}

\ifOption{win}
{
   \def\MakeDir{\relax
      \expandafter \ifx  \csname !\StartDir\endcsname\relax
         \expandafter\let\csname !\StartDir\endcsname=\empty
         \Needs{"if NOT EXIST \StartDir \space mkdir -p \StartDir"}%
      \fi
      \ifx \EndDir\empty \else
          \expandafter\AppendDir \EndDir////*%
          \expandafter\MakeDir
      \fi
   }
}{
   \def\MakeDir{\relax
      \expandafter \ifx  \csname !\StartDir\endcsname\relax
         \expandafter\let\csname !\StartDir\endcsname=\empty
         \Needs{"mkdir -p \StartDir"}%
      \fi
      \ifx \EndDir\empty \else
          \expandafter\AppendDir \EndDir////*%
          \expandafter\MakeDir
      \fi
   }
}

\def\AppendDir#1/#2/#3/*{%
   \def\temp{#2}\ifx \temp\empty
      \let\EndDir=\empty
   \else
      \edef\StartDir{\ifx \StartDir\empty\else
                     \ifx \StartDir\SLASH \Slash \else
                     \StartDir\Slash\fi   \fi
                     #1}%
      \def\EndDir{#2/#3}%
      \expandafter\MakeDir
   \fi
}
\def\setStartDir#1#2!{%
    \def\StartDir{#1}\ifx\StartDir\SLASH\else
    \def\StartDir{}\fi
}



% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % \AddFile[optional: target file name; default: given file name]
% %         (optional: target home dir; default MYDIR)
% %         {file name}{dir}
%
% \def\AddFile{\futurelet\ext\AddFileA}
% \def\AddFileA{%
%    \if [\ext \def\ext[##1]{\def\ext{##1}\futurelet\dir\AddFileB}%
%    \else     \def\ext{\def\ext{}\futurelet\dir\AddFileB}\fi
%    \ext}
% \def\AddFileB{%
%    \if (\dir \def\dir(##1){\def\dir{##1}\AddFileC}%
%    \else     \def\dir{\let\dir\MYdir\AddFileC}\fi
%    \dir}
% \def\AddFileC#1#2{%
%    \expandafter\setStartDir \dir #2!%
%    \edef\EndDir{\ifx \dir\empty \else \dir/\fi
%                 #2/\ifx\ext\empty \if !#1!XXX\else #1\fi\else \ext\fi}\MakeDir
%    \if !#1!\else
%       \Needs{"mv #1\space \dir /#2/\ifx\ext\empty #1\else \ext\fi"}%
%    \fi
% }
% \def\MakeDir{\relax
%    \expandafter \ifx  \csname !\StartDir\endcsname\relax
%       \expandafter\let\csname !\StartDir\endcsname=\empty
%       \Needs{"mkdir -p \StartDir"}%
%    \fi
%    \ifx \EndDir\empty \else
%        \expandafter\AppendDir \EndDir////*%
%        \expandafter\MakeDir
%    \fi
% }
% \def\AppendDir#1/#2/#3/*{%
%    \def\temp{#2}\ifx \temp\empty  \let\EndDir=\empty
%    \else
%       \edef\StartDir{\ifx \StartDir\empty\else
%                      \ifx \StartDir\SLASH /\else
%                      \StartDir/\fi   \fi
%                      #1}\def\EndDir{#2/#3}%
%    \fi
% }
% \def\setStartDir#1#2!{%
%     \def\StartDir{#1}\ifx\StartDir\SLASH\else
%     \def\StartDir{}\fi
% }
% \def\SLASH{/}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% TODO : make \WORK MSDOS / Linux agnostic.
\def\MYdir{\WORK}


\expandafter\let\csname !/\endcsname\empty
\expandafter\let\csname !/\endcsname\empty
\expandafter\let\csname !/home\endcsname\empty
\expandafter\let\csname !/home/4\endcsname\empty
\expandafter\let\csname !/home/4/gurari\endcsname\empty
\expandafter\let\csname !/home/4/gurari/xtpipes.dir\endcsname\empty
%\expandafter\let\csname !/home/4/gurari/tex4ht.dir/texmf\endcsname\empty
%\expandafter\let\csname !/home/4/gurari/xtpipes.dir\endcsname\empty

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%









%%%%%%%%%%%%%%%%%%
\part{Core}
%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%%%%%%
\section{Control}
%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%%%%%%
\subsection{Outline}
%%%%%%%%%%%%%%%%%%


\AtEndDocument{
   \OutputCode[java]\&lt;xtpipes.java\&gt;  % double .java to avoid problems on MS
   \OutputCodE\&lt;Xtpipes.java\&gt;
   \OutputCodE\&lt;xtpipes.dtd\&gt;
}

% \Needs{"
%    mkdir -p work.dir
%    ;
%    mkdir -p work.dir/xtpipes
% "}

\ifdojava
\ifOption{win} {}{
\AtEndDocument{\Needs{"
    find \WORK\space -type f -iname '*.java' -print0
    | xargs -0 javac -d \XTPIPES\space -sourcepath \WORK
    ;
"}}
}
\fi


\ifOption{win} {
    \def\BIN{}
}{
    \def\BIN{(\XTPIPES)}
}

% 
\expandafter\AddFile\BIN{xtpipes.dtd}{xtpipes\Slash lib}

\AddFile{Xtpipes.java}{xtpipes}

\&lt;Xtpipes.java\&gt;&lt;&lt;&lt;
package xtpipes;
/* Xtpipes.java (`version), generated from `jobname.tex
   Copyright (C) 2009-2010 TeX Users Group
   Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; */
`&lt;xtpipes imports`&gt;
`&lt;class XtpipesPrintWriter  `&gt;
public class Xtpipes {
   `&lt;xtpipes fields`&gt;
   `&lt;static void main(String [])`&gt;
   `&lt;static void xtpipes(String [], OutputStream, PrintWriter)`&gt;
   `&lt;static void xtpipes(String [], OutputStreamWriter, PrintWriter)`&gt;
   `&lt;static void xtpipes(String [], XtpipesPrintWriter, PrintWriter)`&gt;
   `&lt;static Document getDOM(...)`&gt;
   `&lt;static void mainMethod(String [])`&gt;
   `&lt;static void execute( node )`&gt;
   `&lt;static String execute( node, xml )`&gt;
   `&lt;static void instructionErr(...)`&gt;
   `&lt;static String serialize( dom )`&gt;
   `&lt;static void cleanXmlns( dom )`&gt;
}
`&lt;class XtpipesEntityResolver`&gt;
&gt;&gt;&gt;

\Needs{"\mv xtpipes.java.java \MYdir xtpipes.java"}

NOTE: We can not place Xtpipes.class and xtpipes.class at the same
directory because MS Windows get confused between the two.


\&lt;xtpipes.java\&gt;&lt;&lt;&lt;
/* xtpipes.java (`version), generated from `jobname.tex
   Copyright (C) 2009-2010 TeX Users Group
   Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; */
import xtpipes.*;
public class xtpipes {
  public static void main(String [] args) throws Exception {
    Xtpipes.main(args);
} }
&gt;&gt;&gt;


\&lt;static String execute( node, xml )\&gt;&lt;&lt;&lt;
public static String execute( Node node, String xml )
                                      throws Exception {
  String name = ".";
  String old = (String) map.get(name);
  map.put( name, (Object) xml );
  execute( node.getFirstChild() );
  String s = (String) map.get(name);
  if( old != null ){ map.put( name, (Object) old ); }
  return s;
}
&gt;&gt;&gt;







\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static HashMap &lt;String,Object&gt; map;
private static boolean needScript;
&gt;&gt;&gt;


The members of xtpipes need to be initiated each time the methods of
the program are invoked from external point.  That can happen multiple
times for a given run. Hence, the fields are not initiated in the
declaration points, but within the main method.  All the external
calls go directly or indirectly through that method.


\&lt;init fields\&gt;&lt;&lt;&lt;
map = new HashMap  &lt;String,Object&gt; ();
needScript = true;
&gt;&gt;&gt;


\&lt;xtpipes imports\&gt;&lt;&lt;&lt;
// import xtpipes.util.InputObject;
// import xtpipes.util.FileInfo;
import xtpipes.XtpipesPrintWriter;
import java.net.URLConnection;
import java.io.*;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Stack;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.net.URL;
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Invocation Interfaces}
%%%%%%%%%%%%%

\&lt;static void main(String [])\&gt;&lt;&lt;&lt;
public static void main(String args[]) throws Exception {
  `&lt;init fields`&gt;
  mainMethod(args);
}
&gt;&gt;&gt;




\&lt;static void xtpipes(String [], OutputStream, PrintWriter)\&gt;&lt;&lt;&lt;
public static void xtpipes(String [] args,
                           OutputStream out,
                           PrintWriter log)
                                                throws Exception {
  `&lt;init fields`&gt;
  outPrintWriter = new XtpipesPrintWriter( out, true );
  logWriter = (log==null)? (new PrintWriter( System.err )) : log;
  mainMethod(args);
  outPrintWriter.flush();
}
&gt;&gt;&gt;



\&lt;static void xtpipes(String [], OutputStreamWriter, PrintWriter)\&gt;&lt;&lt;&lt;
public static void xtpipes(String [] args,
                           OutputStreamWriter out,
                           PrintWriter log)
                                                throws Exception {
  `&lt;init fields`&gt;
  outPrintWriter = new XtpipesPrintWriter( out );
  logWriter = (log==null)? (new PrintWriter( System.err )) : log;
  mainMethod(args);
  outPrintWriter.flush();
}
&gt;&gt;&gt;

\&lt;static void xtpipes(String [], XtpipesPrintWriter, PrintWriter)\&gt;&lt;&lt;&lt;
public static void xtpipes(String [] args,
                           XtpipesPrintWriter out,
                           PrintWriter log)
                                                throws Exception {
  `&lt;init fields`&gt;
  outPrintWriter = out;
  logWriter = (log==null)? (new PrintWriter( System.err )) : log;
  mainMethod(args);
  outPrintWriter.flush();
}
&gt;&gt;&gt;


\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static boolean returnDom;
private static String result;
&gt;&gt;&gt;

\&lt;init fields\&gt;&lt;&lt;&lt;
returnDom = false;
result = null;
&gt;&gt;&gt;


\&lt;static Document getDOM(...)\&gt;&lt;&lt;&lt;
public static Document getDOM(String args[])
                               throws Exception {
  `&lt;init fields`&gt;
   returnDom = true;
   mainMethod(args);
   Document dom = null;
   if( result == null ){
     System.err.println(
       "--- xtpipes warning --- getDOM without &lt;return name=\"...\"&gt; from 4xt file: "
         + scriptFile );
   } else {
      try{
         byte [] bytes = result.getBytes("UTF-8");
         InputStream is =  new ByteArrayInputStream( bytes );
         dom = domBuilder.parse (is);
      } catch ( org.xml.sax.SAXParseException e ){
         if( Xtpipes.trace ){
            Xtpipes.logWriter.println(
               "\n---------------------------------------------------\n"
                        + result +
               "\n---------------------------------------------------\n" );
         }
         String s = "";
         `&lt;s += input file name within args`&gt;
         if( scriptFile != null ){ s += "    script file: " + scriptFile; }
         instructionErr( null,
            "parsing error: " + e.getMessage() +s, 21 );
      } catch ( Exception e ){
         instructionErr( null, e.toString(), 5 );
      }
      `&lt;close ml2xml files`&gt;
   }
   return dom;
}
&gt;&gt;&gt;

\&lt;static Document getDOM(...)\&gt;&lt;&lt;&lt;
public static Document getDOM(String s, String args[])
                                           throws Exception {
   `&lt;init fields`&gt;
   returnDom = true;
   inData = s;
   mainMethod(args);
   Document dom = null;
   if( result == null ){
     System.err.println(
       "--- xtpipes warning --- getDOM without"
         + " &lt;return name=\"...\"&gt; from 4xt file: "
         + scriptFile );
   } else {
      try{
         byte [] bytes = result.getBytes("UTF-8");
         InputStream is =  new ByteArrayInputStream( bytes );
         dom = domBuilder.parse (is);
      } catch ( org.xml.sax.SAXParseException e ){
         instructionErr( null, "improper xml: " + e.getMessage()
           + "\n code starts with: "
           + result.substring(0, Math.min(100,result.length()))
         , 17 );
      } catch ( Exception e ){
         instructionErr( null, e.toString(), 6 );
      }
      `&lt;close ml2xml files`&gt;
   }
   return dom;
}
&gt;&gt;&gt;


\&lt;static Document getDOM(...)\&gt;&lt;&lt;&lt;
public static Document getDOM(String args[], PrintWriter log)
                               throws Exception {
   logWriter = (log==null)? new PrintWriter( System.err ) : log;
   return getDOM(args);
}
&gt;&gt;&gt;

\&lt;static Document getDOM(...)\&gt;&lt;&lt;&lt;
public static Document getDOM(String s, String args[], PrintWriter log)
                                           throws Exception {
   logWriter = (log==null)? (new PrintWriter( System.err )) : log;
   return getDOM(s, args);
}
&gt;&gt;&gt;




\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
static PrintWriter logWriter = new PrintWriter( System.err );
&gt;&gt;&gt;




%%%%%%%%%%%%%
\subsection{Core Entry Code}
%%%%%%%%%%%%%
g

\&lt;static void mainMethod(String [])\&gt;&lt;&lt;&lt;
private static void mainMethod(String args[]) throws Exception {
  try{
    `&lt;command line vars`&gt;
    `&lt;process command line`&gt;
  } catch (Exception e){
     instructionErr( null, e.getMessage(), e.getStackTrace(), 31 );
  }
  try {
     DocumentBuilderFactory domFactory =
           DocumentBuilderFactory.newInstance();
     domFactory.setValidating(true);
     DocumentBuilder validatingDomBuilder =
                     domFactory.newDocumentBuilder();
     validatingDomBuilder.setEntityResolver(`&lt;new EntityResolver()`&gt;);
     validatingDomBuilder.setErrorHandler(`&lt;new ErrorHandler()`&gt;);
     `&lt;xtpipes initialization`&gt;
     `&lt;scriptFile := entry script file name`&gt;
     while( needScript ){
       if( scriptFile == null ){
          instructionErr( null, "Missing 4xt script file name", 32 );
       }
       `&lt;search script file`&gt;
       Document script = validatingDomBuilder.parse(scriptFile);
       `&lt;trace open script`&gt;
       execute( script.getFirstChild() );
     }
     `&lt;close output file`&gt;
      Xtpipes.logWriter.flush();
  } catch( org.xml.sax.SAXParseException e ){
     String s = "Improper file " + scriptFile + ": " + e.getMessage();
     instructionErr( null, s, 2 );
  } catch( java.io.FileNotFoundException e ){
     String s;
     if( scriptFile.equals( e.getMessage() ) ){
        s =  "Could not find file: " + scriptFile;
     } else {
        s = "Problem at script " + scriptFile + ": Could not find file "
                                                     + e.getMessage();
     }
     instructionErr( null, s, 3 );
  } catch( Exception e ){
     String s = "Problems at file: " + scriptFile + "\n   " + e;
     instructionErr( null, s, 4 );
} }
&gt;&gt;&gt;






%%%%%%%%%%%%%
\subsection{Locate the Script File}
%%%%%%%%%%%%%




\&lt;search script file\&gt;&lt;&lt;&lt;
String f = FileInfo.searchFile( scriptFile );
if( f == null ){
   throw new java.io.FileNotFoundException( scriptFile );
} else {
   scriptFile = f;
}
&gt;&gt;&gt;



[\HPage{System Properties}

\&lt;sys.java\&gt;&lt;&lt;&lt;
// `version
import java.util.*;
class sys{
  public static void main( String [] args ) {
     java.util.Properties p = System.getProperties();
     java.util.Enumeration keys = p.keys();
     while( keys.hasMoreElements() ) {
         String name = (String) keys.nextElement();
         String value = System.getProperty( name );
         logWriter.println( name + " : " + value );
} }  }
&gt;&gt;&gt;
\EndHPage{}]


%%%%%%%%%%%%%
\subsection{Flow of Control}
%%%%%%%%%%%%%


\&lt;static void execute( node )\&gt;&lt;&lt;&lt;
private static void execute( Node node ) throws Exception {
  while( node != null ){
    if( node.getNodeType()==Node.ELEMENT_NODE ){
      String instruction = node.getNodeName();
      `&lt;trace element`&gt;
      if( instruction.equals( "xtpipes" ) ){
         `&lt;execute xtpipes`&gt;
      } else if( instruction.equals( "set" ) ){
         `&lt;execute set`&gt;
      } else if( instruction.equals( "get" ) ){
         `&lt;execute get`&gt;
      } else if( instruction.equals( "print" ) ){
         `&lt;execute print`&gt;
      } else if( instruction.equals( "return" ) ){
         `&lt;execute return`&gt;
      } else if( instruction.equals( "if" ) ){
         `&lt;execute if`&gt;
      } else if( instruction.equals( "xslt" ) ){
         `&lt;execute xslt`&gt;
      } else if( instruction.equals( "dom" ) ){
         `&lt;execute dom`&gt;
      } else if( instruction.equals( "sax" ) ){
         `&lt;execute sax`&gt;
      } else {
         instructionErr( node, "Improper instruction: " + instruction, 11 );
    } }
    node = node.getNextSibling();
} }
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Comamnd Line Options: Outline}
%%%%%%%%%%%%%



\&lt;get args[n]\&gt;&lt;&lt;&lt;
if( args[n] == null ){}
else if( args[n].equals("") ){}
else if( args[n].charAt(0)!='-' ){ inFile = args[n]; }
else if( args[n].equals("-m") ){
  messages = true;
  `&lt;output system info`&gt;
}
else if( args[n].equals("-s") ){
  `&lt;scan script file name`&gt;
}
else if( args[n].equals("-S") ){
  `&lt;scan script map file name`&gt;
}
else if( args[n].equals("-i") ){
  `&lt;scan script dir name`&gt;
}
else if( args[n].equals("-o") ){
  `&lt;scan output file name`&gt;
}
else if( args[n].startsWith("-x") ){
  `&lt;scan ml2xml argument`&gt;
}
else if( args[n].equals("-E") ){
  exceptionErrs = true;
}
else if( args[n].equals("-d") ){
  `&lt;scan input data`&gt;
}
else if( args[n].equals("-trace") ){ trace=true; }
else if( args[n].equals("-help") ){ help=true; }
else { `&lt;improper args[n]`&gt; }
&gt;&gt;&gt;


\&lt;display command line syntax\&gt;&lt;&lt;&lt;
System.err.println( xtpipes_call );
&gt;&gt;&gt;

\&lt;command line vars\&gt;&lt;&lt;&lt;
String xtpipes_call =
     "   xtpipes (`version)"
   + "\n   Command line options: "
   + "\n     java xtpipes [-trace] [-help] [-m] [-E] [-s script_file]"
   +                                               " [-S script_map]"
   + "\n                  [-i script_dir] [-o out_file] "
   + "\n                  [-x...ml2xml_arg...]  "
   +                     "(-d in_data | in_file)"
   + "\n     -m        messages printing mode"
   + "\n     -E        error messages into exception calls"
   + "\n     in_data   XML data directly into the command line\n"
;
&gt;&gt;&gt;



At least one  `-x'  command line option is required for ml2xml
to be called.  An empty postfix is also fine.



\&lt;s += input file name within args\&gt;&lt;&lt;&lt;
for( int n=0; n&lt;args.length; n++ ){
  if( args[n].charAt(0)!='-' ){
     s += "  input file: " + args[n] + ".";  break;
  }
  else if( args[n].equals("-s")
           || args[n].equals("-S")
           || args[n].equals("-i")
           || args[n].equals("-o")
           || args[n].equals("-d") ){ n++;  }
}
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Comamnd Line Options: Processing}
%%%%%%%%%%%%%



\&lt;process command line\&gt;&lt;&lt;&lt;
boolean help=false;
for( int n=0; n&lt;args.length; n++ ){
  `&lt;get args[n]`&gt;
}
`&lt;default stdio output`&gt;
`&lt;help message and stop on improper args in batch mode`&gt;
new FileInfo(logWriter, i_scriptDir, trace);
if( inFile != null ){
   inputObject = new InputObject( inFile, logWriter );
   if( inputObject.getInputStream() == null ){
      instructionErr( null, "Could not find or open file: " + inFile, 28 );
   }
   inFile = inputObject.getFilename();
} else {
   inputObject = new InputObject( inData.getBytes("UTF-8"), logWriter );
}
inputObject.buildProfile( trace );
&gt;&gt;&gt;

\&lt;help message and stop on improper args in batch mode\&gt;&lt;&lt;&lt;
if( !returnDom ){
   if( help || ((inFile == null) &amp;&amp; (inData == null)) ){
     `&lt;display command line syntax`&gt;
     if( (inFile == null) &amp;&amp; (inData == null) ){
        System.exit(0);
}  } }
&gt;&gt;&gt;

\&lt;improper args[n]\&gt;&lt;&lt;&lt;
if( !exceptionErrs ){
  for(int i=n+1; i&lt;args.length; i++ ){
    if( args[i].equals("-E") ){ exceptionErrs = true; }
} }
instructionErr( null,
     "Improper argument: " + args[n] + "\n" + xtpipes_call, 26 );
&gt;&gt;&gt;




\&lt;scan input data\&gt;&lt;&lt;&lt;
n++;
if( n &lt; args.length ){
   inData = args[n];
} else {
   System.err.println(
       "--- Error --- Missing field for -d argument" );
   inFile = null; inData = null; break;
}
&gt;&gt;&gt;






\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static String     inFile,
                          inData;
private static boolean exceptionErrs, messages;
public static InputObject inputObject;
&gt;&gt;&gt;


\&lt;init fields\&gt;&lt;&lt;&lt;
inFile = null;
inData = null;
exceptionErrs = false;
messages = false;
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Output File}
%%%%%%%%%%%%%


The output file name mentioned in the input command line `-o file.out' is
employed in the following cases.

\begin{itemize}
\item
Within sax commands without `name' argument

\item Within the return instruction, if none of the sax commands wrote
  into the file.  The returnToFile field is used for book keeping of
  whether a sax command used the file earlier for an output target.


NOTE: check the case of `cond copy input preamble' ??
\end{itemize}


\&lt;scan output file name\&gt;&lt;&lt;&lt;
n++;
if( n &lt; args.length ){
   outFileName = args[n];
} else {
   System.err.println(
       "--- Error --- Missing field for -o argument" );
   inFile = null; inData = null; break;
}
&gt;&gt;&gt;


\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static String outFileName;
private static PrintWriter outPrintWriter;
private static boolean returnToFile = false;
&gt;&gt;&gt;

\&lt;init fields\&gt;&lt;&lt;&lt;
outFileName = null;
outPrintWriter = null;
&gt;&gt;&gt;



\&lt;open output file\&gt;&lt;&lt;&lt;
if( outFileName != null ){
   try {
      FileWriter fw = new FileWriter( outFileName );
      outPrintWriter = new XtpipesPrintWriter( fw );
      returnToFile = true;
   } catch(Exception e){
      instructionErr( null, e.toString(), 12 );
}  }
&gt;&gt;&gt;

\&lt;close output file\&gt;&lt;&lt;&lt;
if( outFileName != null ){
   outPrintWriter.close();
}
&gt;&gt;&gt;

\&lt;default stdio output\&gt;&lt;&lt;&lt;
if( outPrintWriter == null ){
   outPrintWriter = new XtpipesPrintWriter(System.out,true);
}
&gt;&gt;&gt;

% 
\AtEndDocument{
   \OutputCodE\&lt;XtpipesPrintWriter.java\&gt;
}
\AddFile{XtpipesPrintWriter.java}{xtpipes}

\&lt;XtpipesPrintWriter.java\&gt;&lt;&lt;&lt;
package xtpipes;
/* XtpipesPrintWriter.java (`version), generated from `jobname.tex
   Copyright (C) 2009-2010 TeX Users Group
   Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; */
import java.io.*;
public class XtpipesPrintWriter extends PrintWriter {
   public XtpipesPrintWriter() {
     super(System.out, true);
   }
   public XtpipesPrintWriter (PrintStream ps, boolean b){
     super(ps, b);
   }
   public XtpipesPrintWriter (OutputStream ps, boolean b){
     super(ps, b);
   }
   public XtpipesPrintWriter (FileWriter fw){
     super(fw);
   }
   public XtpipesPrintWriter (Writer wr){
     super(wr);
   }
   public void print(String str) {
     super.print( XtpipesUni.toUni(str, "") );
   }
   public void println(String str) {
     super.println( XtpipesUni.toUni(str, "") );
}  }
&gt;&gt;&gt;





%%%%%%%%%%%%%%%%%%
\section{The xtpipes Script}
%%%%%%%%%%%%%%%%%%


The translation of a file is driven by a script that determines the
transformations to be applied to the diffrent fragments of the input
data.  The name of the script may be found in different locations.

\begin{itemize}
\item
A xtpipes processing instruction within the input
\item
Command line option `-s'
\item
A .map  file that checks the data characteristics to determine the
script. Currently available only to input files, not to input strings.
\end{itemize}



%%%%%%%%%%%%%
\subsection{Command Line Options}
%%%%%%%%%%%%%


A script should satisfy  the rules of `xtpipes.dtd',
and a map should satisfy the rules of `xtpipes-map.dtd'.




\&lt;scan script file name\&gt;&lt;&lt;&lt;
n++;
if( n &lt; args.length ){ scriptFile=args[n]; }
else {
  System.err.println(
      "--- Error --- Missing field for -s argument" );
  inFile = null; inData = null;  break;
}
&gt;&gt;&gt;


\&lt;scan script map file name\&gt;&lt;&lt;&lt;
n++;
if( n &lt; args.length ){ scriptMap=args[n]; }
else {
  System.err.println(
      "--- Error --- Missing field for -S argument" );
  inFile = null; inData = null;  break;
}
&gt;&gt;&gt;


\&lt;scan script dir name\&gt;&lt;&lt;&lt;
n++;
if( n &lt; args.length ){
   i_scriptDir=args[n];
} else {
  System.err.println(
      "--- Error --- Missing field for -i argument" );
  inFile = null; inData = null; break;
}
&gt;&gt;&gt;




\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
public static String scriptFile;
private static String scriptMap;
static String i_scriptDir;
&gt;&gt;&gt;


\&lt;init fields\&gt;&lt;&lt;&lt;
scriptFile = null;
i_scriptDir = null;
scriptMap = null;
&gt;&gt;&gt;




%%%%%%%%%%%%%
\subsection{Getting the Start Up Script}
%%%%%%%%%%%%%

The command line arguments may provide a pointer to
a `scriptFile' and a pointer to an algorithm `scriptMap'
for getting the script file name.

With and without ml2xml

\&lt;scriptFile := entry script file name\&gt;&lt;&lt;&lt;
if( scriptMap != null ){
   try{
      String f = FileInfo.searchFile( scriptMap );
      if( f == null ){
         throw new java.io.FileNotFoundException( scriptMap );
      } else {
         scriptMap = f;
      }
      `&lt;get sax reader`&gt;
      saxReader.setContentHandler( new DefaultHandler(){
         `&lt;process script map`&gt;
        } );
      InputStream inputStream =
           (InputStream) (new File(scriptMap).toURI().toURL().openStream());
      saxReader.parse( new InputSource(inputStream) );
      saxReaderStack.push( saxReader );
   } catch( java.io.FileNotFoundException e ){
      instructionErr( null,
                      "File not found: " + e.getMessage()
                      + "; command line option -i",
                      33 );
   } catch( Exception e ){
      instructionErr( null, e.toString(), e.getStackTrace(), 27 );
   }
}
if( scriptFile == null ){
    scriptFile = "xtpipes-default.4xt";
}
&gt;&gt;&gt;


\&lt;process script map\&gt;&lt;&lt;&lt;
private Stack &lt;Boolean&gt; condition = new Stack &lt;Boolean&gt; ();
&gt;&gt;&gt;

\&lt;process script map\&gt;&lt;&lt;&lt;
public void startDocument () {
   condition.push( Boolean.valueOf(true) );
}
&gt;&gt;&gt;

\&lt;process script map\&gt;&lt;&lt;&lt;
public void startElement(String ns, String sName,
                        String qName, Attributes atts) {
   if( condition == null ){ return; }
   `&lt;trace start map element`&gt;
   boolean cond = ((Boolean) condition.peek()).booleanValue();
   if( qName.equals("when") ){
      if( cond ){ `&lt;cond := when ...`&gt; }
   }
   else
   if( qName.equals("command-line") ){
      if( scriptFile != null ){
        `&lt;trace found script in map`&gt;
        condition = null;
        return;
   }  }
   else
   if( qName.equals("processing-instruction") ){
      if( cond ){
         String s = inputObject.getXtpipes();
         if( s != null ){
           Xtpipes.scriptFile = s;
           `&lt;trace found script in map`&gt;
           condition = null;
           return;
   }  }  }
   else
   if( qName.equals("select") ){
      if( cond ){
        Xtpipes.scriptFile = atts.getValue("name");
        `&lt;trace found script in map`&gt;
        condition = null;
        return;
   }  }
   condition.push( Boolean.valueOf(cond) );
}
&gt;&gt;&gt;




\&lt;process script map\&gt;&lt;&lt;&lt;
public void endElement(String ns, String sName, String qName) {
   if( condition == null ){ return; }
   `&lt;trace end map element`&gt;
   condition.pop();
}
&gt;&gt;&gt;



\&lt;cond := when ...\&gt;&lt;&lt;&lt;
String name = atts.getValue("name");
String value = atts.getValue("value");
if( name.equals("system-id") ){
   cond = value.equals(inputObject.getSystemId());
}
else
if( name.equals("public-id") ){
   cond = value.equals(inputObject.getPublicId());
}
else
if( name.equals("dtd-root") ){
   cond = value.equals(inputObject.getDtdRoot());
}
else
if( name.equals("root") ){
   cond = value.equals(inputObject.getRoot());
}
else
if( name.equals("ext") ){
   cond = inputObject.getFilename().endsWith("." + value);
}
else
if( name.equals("prefix") ){
   name = inputObject.getFilename();
   if( name != null ){
      int i = name.lastIndexOf('/');
      if( (i != -1) &amp;&amp; ((i+1) &lt; name.length()) ){
         name = name.substring(i+1);
      }
      i = name.lastIndexOf('\\');
      if( (i != -1) &amp;&amp; ((i+1) &lt; name.length()) ){
         name = name.substring(i+1);
      }
      cond = name.startsWith(value);
}  }
else
if( name.equals("meta-type") ){
   cond = value.equals(inputObject.getMetaType());
}
else
if( name.equals("content-type") ){
   cond = value.equals(inputObject.getContentType());
}
&gt;&gt;&gt;







\&lt;trace found script in map\&gt;&lt;&lt;&lt;
if( trace ){
   Xtpipes.logWriter.println( " Found script file in map: "
                                + Xtpipes.scriptFile );
}
&gt;&gt;&gt;


\&lt;trace start map element\&gt;&lt;&lt;&lt;
if( Xtpipes.trace ){
   String s =  "&lt;" + qName + "\n";
   for(int i=0; i&lt;atts.getLength(); i++ ){
      String name = atts.getQName(i);
      s += " " + name + "=\"" + atts.getValue(i) + "\"";
   }
   s += "&gt;" ;
   Xtpipes.logWriter.println( s );
}
&gt;&gt;&gt;

\&lt;trace end map element\&gt;&lt;&lt;&lt;
if( Xtpipes.trace ){
   String s =  "&lt;/" + qName + "&gt;";
   Xtpipes.logWriter.println( s );
}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{DTDs}
%%%%%%%%%%%%%



%%%%%%%%%%%%%
\immediate\openin15=xtpipes.dtd
\ifeof15 \else
   \immediate\closein15
   [\HPage{xtpipes.dtd}
     \verbatiminput{xtpipes.dtd}
   \EndHPage{}]
\fi
%%%%%%%%%%%%%
%
%%%%%%%%%%%%%
\immediate\openin15=xtpipes-map.dtd
\ifeof15 \else
   \immediate\closein15
   [\HPage{xtpipes-map.dtd}
     \verbatiminput{xtpipes-map.dtd}
   \EndHPage{}]
\fi
%%%%%%%%%%%%%

\begin{verbatim}
&lt;xtpipes&gt; ... &lt;/xtpipes&gt;
\end{verbatim}

\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!-- xtpipes.dtd (`version), generated from `jobname.tex
     Copyright (C) 2009-2010 TeX Users Group
     Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; --&gt;
&lt;!ELEMENT xtpipes (#PCDATA `&lt;xtpipes entries`&gt;)* &gt;
&lt;!ATTLIST xtpipes
          preamble  CDATA #IMPLIED DEFAULT (yes | no) "no"
          signature CDATA #IMPLIED                         &gt;
&gt;&gt;&gt;


% 
\AtEndDocument{
   \OutputCodE\&lt;xtpipes-map.dtd\&gt;
}

\expandafter\AddFile\BIN{xtpipes-map.dtd}{xtpipes\Slash lib}

\&lt;xtpipes-map.dtd\&gt;&lt;&lt;&lt;
&lt;!-- xtpipes-map.dtd (`version), generated from `jobname.tex
     Copyright (C) 2009-2010 TeX Users Group
     Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; --&gt;
&lt;!ELEMENT xtpipes-map (when | processing-instruction
                            | select
                            | command-line)*  &gt;
&lt;!ELEMENT when (when | select
                     | processing-instruction
                     | command-line )*  &gt;
&lt;!ELEMENT select EMPTY &gt;
&lt;!ELEMENT processing-instruction EMPTY &gt;
&lt;!ELEMENT command-line EMPTY &gt;
&lt;!ATTLIST xtpipes-map
          signature      CDATA #IMPLIED
&gt;
&lt;!ATTLIST when
          name   (
                    system-id
                  | public-id
                  | dtd-root
                  | root
                  | ext
                  | meta-type
                  | content-type
                  | prefix      )  "public-id"
          value   CDATA #IMPLIED
          case-sensitive (yes|no) "no"
&gt;
&lt;!ATTLIST select
          name      CDATA #REQUIRED
&gt;
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Indirect Scripts}
%%%%%%%%%%%%%



If the root xtpipes element has no children, the input file is
searched for an alternative script within a processing instruction of
the form \verb+&lt;?xtpipes file="..." ?&gt;+.

\&lt;script := xtpipes processing instruction\&gt;&lt;&lt;&lt;
if( inData == null ){
   `&lt;search file for xtpipes instruction`&gt;
} else {
   `&lt;search string for xtpipes instruction`&gt;
}
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Search File}
%%%%%%%%%%%%%




\&lt;search file for xtpipes instruction\&gt;&lt;&lt;&lt;
/*
errMsg = "Searching &lt;?xtpipes file=\"...\"?&gt;  in "
                      + inFile + ": ";
*/
scriptFile = inputObject.getXtpipes();
rootName = inputObject.getRoot();
needScript = true;
&gt;&gt;&gt;

\&lt;search file for xtpipes instructionOLD\&gt;&lt;&lt;&lt;
errMsg = "Searching &lt;?xtpipes file=\"...\"?&gt;  in "
                      + inFile + ": ";
       `&lt;get sax reader`&gt;
       saxReader.setContentHandler( new XtPipesSearch() );
try{
    saxReader.parse( new File(inFile).toURI().toURL().toString() );
} catch ( java.io.FileNotFoundException ioe ){
    try{
       saxReader.parse( new InputSource(
                        new URL(inFile) . openStream() ));
    } catch ( java.io.FileNotFoundException fnf ){
        saxReader.parse( new File(inFile).toURI().toURL().toString() );
}   }
       saxReaderStack.push( saxReader );
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Copy Preamble}
%%%%%%%%%%%%%


Copy into th eoutput the code preceeding the root. Note: assumes proper
XML file as it doesn't use ml2xml. NEEDS FIXING.
Example:

\begin{verbatim}
----&gt; &lt;?xml version="1.0" encoding="UTF-8"?&gt;
----&gt; &lt;!DOCTYPE math:math PUBLIC "-//W3C//DTD MathML 2.0//EN" "math.dtd"&gt;
----&gt; &lt;?xtpipes file="oo-math.4xt" ?&gt;
----&gt; &lt;!-- try-m12 by TeX4ht from try.tex line 69 2007-01-09-11:20
----&gt; (http://www.cse.ohio-state.edu/~gurari/TeX4ht/) --&gt;
\end{verbatim}



\&lt;cond copy input preamble\&gt;&lt;&lt;&lt;
if( node.hasAttributes() ){
   Node attr = node.getAttributes()
                   .getNamedItem( "signature" );
   `&lt;preamble output into log`&gt;
   attr = node.getAttributes()
                   .getNamedItem( "preamble" );
   if( (attr != null)
       &amp;&amp; attr.getNodeValue().equals( "yes" ) ){
      `&lt;get src preamble`&gt;
} }
&gt;&gt;&gt;


\&lt;get src preamble\&gt;&lt;&lt;&lt;
// BufferedReader br = null;
try {
   String s;
   boolean front = true;
   rootName = "&lt;" + ((rootName==null)? inputObject.getRoot() : rootName);
   if( inData == null ){
      `&lt;get src preamble from file`&gt;
   } else {
      `&lt;get src preamble from string`&gt;
   }
} catch (Exception e) {
   System.err.println(
        "--- Error --- Couldn't copy preamble: " + e);
}
&gt;&gt;&gt;




\&lt;get src preamble from file\&gt;&lt;&lt;&lt;
// FileReader fr = new FileReader(inFile);
// BufferedReader in = new BufferedReader(fr);
`&lt;BufferedReader in := inFile`&gt;
while (  ((s = in.readLine()) != null) &amp;&amp; front ) {
   int i = s.indexOf( rootName );
   if( i &gt; -1 ){
      front = false;
      s = s.substring(0,i);
   }
   outPrintWriter.println(s);
   returnToFile = false;
}
in.close();
&gt;&gt;&gt;

\&lt;BufferedReader in := inFile\&gt;&lt;&lt;&lt;
URLConnection connection =
             new URL(inFile).openConnection();
connection.setRequestProperty("User-Agent",
                "["
              + System.getProperty("os.name")
              + " / "
              + System.getProperty("os.arch")
              + "]"
              + "["
              + System.getProperty("java.version")
              + " - "
              + System.getProperty("java.vendor")
              + "]"
);
InputStream inputStream = connection.getInputStream();
BufferedReader in = new BufferedReader (
                        new InputStreamReader ( inputStream ) );
&gt;&gt;&gt;






\&lt;get src preamble from string\&gt;&lt;&lt;&lt;
int i = inData.indexOf( rootName );
if( i &gt; -1 ){
   front = false;
   s = inData.substring(0,i);
} else { s = ""; }
outPrintWriter.println(s);
returnToFile = false;
&gt;&gt;&gt;




%%%%%%%%%%%%%%%%%%
\section{The Instructions}
%%%%%%%%%%%%%%%%%%



%%%%%%%%%%%%%
\subsection{XtPipes}
%%%%%%%%%%%%%

The xtpipes element is the root of the script file through which
the transformation starts.

\&lt;execute xtpipes\&gt;&lt;&lt;&lt;
// String errMsg = "";
needScript = false;
if( node.hasChildNodes() ){
  `&lt;open output file`&gt;
  `&lt;cond copy input preamble`&gt;
   execute( node.getFirstChild() );
} else {
   `&lt;script := xtpipes processing instruction`&gt;
}
&gt;&gt;&gt;






If the root xtpipes element has no children, the input file is
searched for an alternative script within a processing instruction of
the form \verb+&lt;?xtpipes file="..." ?&gt;+.





%%%%%%%%%%%%%
\subsection{Handle Set}
%%%%%%%%%%%%%

Associate a name to the given enclosed  code.

\begin{verbatim}
&lt;set name="..."&gt;
&lt;![CDATA[
  ...
]]&gt;
&lt;/set&gt;
\end{verbatim}

\&lt;xtpipes entries\&gt;&lt;&lt;&lt;
| set
&gt;&gt;&gt;

\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!ELEMENT set (#PCDATA) &gt;
&lt;!ATTLIST set
          name CDATA #REQUIRED &gt;
&gt;&gt;&gt;





\&lt;execute set\&gt;&lt;&lt;&lt;
String name = node.getAttributes().getNamedItem( "name" )
                                  .getNodeValue();
Node cdata = node.getFirstChild();
while( cdata.getNodeType() != Node.CDATA_SECTION_NODE ){
   cdata = cdata.getNextSibling();
}
String code = cdata.getNodeValue().trim();
map.put( name, (Object) code );
&gt;&gt;&gt;









%%%%%%%%%%%%%
\subsection{Handle Get XML Code}
%%%%%%%%%%%%%

Stores a XML file content under the given name.

\begin{verbatim}
&lt;get name="..." file="..." /&gt;
\end{verbatim}


\&lt;xtpipes entries\&gt;&lt;&lt;&lt;
| get
&gt;&gt;&gt;


\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!ELEMENT get EMPTY &gt;
&lt;!ATTLIST get
          name CDATA #REQUIRED
          file CDATA #REQUIRED
&gt;
&gt;&gt;&gt;


\&lt;execute get\&gt;&lt;&lt;&lt;
try {
  String name = node.getAttributes()
                  .getNamedItem( "name" ).getNodeValue();
  String file = node.getAttributes()
               .getNamedItem( "file" ).getNodeValue();
  StreamSource in   = new StreamSource( new File(file) );
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  identityTransformer.transform( in, new StreamResult(baos) );
  byte [] bytes = baos.toByteArray();
  map.put( name, (Object) new String(bytes) );
} catch( Exception e ){
   instructionErr( node, e.toString(), 14 );
}
&gt;&gt;&gt;



\&lt;xtpipes initialization\&gt;&lt;&lt;&lt;
fc = TransformerFactory.newInstance();
identityTransformer =  fc.newTransformer();
identityTransformer.setErrorListener(
    `&lt;identity transformer XML error listener`&gt; );
&gt;&gt;&gt;

\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static TransformerFactory fc;
private static Transformer identityTransformer;
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Print Named XML Code}
%%%%%%%%%%%%%

Prints the content of the named XML code. If a file name is not
provided in the `file' attribute,
the stderr is assumed.
% the file name from the command line
% is assumed. If a file name is not provided in both places, the stdio
% is assumed.
%    outPrintWriter.println( xml );

\begin{verbatim}
&lt;print name="..." file="..." /&gt;
\end{verbatim}



\&lt;xtpipes entries\&gt;&lt;&lt;&lt;
| print
&gt;&gt;&gt;


\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!ELEMENT print EMPTY &gt;
&lt;!ATTLIST print
          name CDATA #REQUIRED
          file CDATA #IMPLIED
&gt;
&gt;&gt;&gt;



\&lt;execute print\&gt;&lt;&lt;&lt;
String name = node.getAttributes()
                 .getNamedItem( "name" ).getNodeValue();
String xml = (String) map.get(name);
if( node.getAttributes().getNamedItem( "file" )==null ){
   if( !Xtpipes.trace ){
      logWriter.println( "[##]  = xtpipes =&gt; print: " + scriptFile );
   }
   logWriter.println( XtpipesUni.toUni(xml, "") );
} else {
   String file = node.getAttributes()
                 .getNamedItem( "file" ).getNodeValue();
   try{
       FileWriter fw = new FileWriter( file );
       XtpipesPrintWriter out = new XtpipesPrintWriter( fw );
       out.println( xml );
       out.close();
   } catch(Exception e){
       instructionErr( node, e.toString(),15 );
}  }
&gt;&gt;&gt;




%%%%%%%%%%%%%
\subsection{Result for Returned Value}
%%%%%%%%%%%%%

A call to getDOM uses the data for its returned value.

\begin{verbatim}
&lt;return name="..." /&gt;
\end{verbatim}



\&lt;xtpipes entries\&gt;&lt;&lt;&lt;
| return
&gt;&gt;&gt;


\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!ELEMENT return EMPTY &gt;
&lt;!ATTLIST return
          name CDATA #REQUIRED
&gt;
&gt;&gt;&gt;



\&lt;execute return\&gt;&lt;&lt;&lt;
String name = node.getAttributes()
                 .getNamedItem( "name" ).getNodeValue();
result = (String) map.get(name);
if( returnToFile ){
   outPrintWriter.println(result);
}
&gt;&gt;&gt;




%%%%%%%%%%%%%
\subsection{Conditional `if' statements}
%%%%%%%%%%%%%

Execute the enclosed instructions provided the named XML code
satisfied the named DTD conditions.

\begin{verbatim}
&lt;if xml="..." dtd="..." root="..." &gt;
   ...
&lt;/if&gt;
\end{verbatim}


\&lt;xtpipes entries\&gt;&lt;&lt;&lt;
| if
&gt;&gt;&gt;


\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!ELEMENT if (#PCDATA `&lt;xtpipes entries`&gt;)* &gt;
&lt;!ATTLIST if
          xml CDATA #REQUIRED
          dtd CDATA #REQUIRED
          root CDATA #REQUIRED
&gt;
&gt;&gt;&gt;

\&lt;execute if\&gt;&lt;&lt;&lt;
try{
   `&lt;doc = dtd + xml`&gt;
   byte [] bytes = doc.getBytes("UTF-8");
   ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
   InputSource in = new InputSource( bais );
   SAXParser saxParser = saxFactory.newSAXParser();
   XMLReader xmlReader = saxParser.getXMLReader();
   xmlReader.parse( in );
   `&lt;trace if true`&gt;
   execute( node.getFirstChild() );
} catch ( Exception e ){ `&lt;trace if false`&gt; }
&gt;&gt;&gt;


\&lt;doc = dtd + xml\&gt;&lt;&lt;&lt;
String xml = node.getAttributes()
                 .getNamedItem( "xml" ).getNodeValue();
String dtd = node.getAttributes()
                 .getNamedItem( "dtd" ).getNodeValue();
// String root = node.getAttributes()
//                 .getNamedItem( "root" ).getNodeValue();
String doc = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\" ?&gt;\n"
             + "&lt;!DOCTYPE doc [\n"
             + (String) map.get(dtd)
             + "\n]&gt;\n"
             + (String) map.get(xml) ;
&gt;&gt;&gt;



\&lt;xtpipes initialization\&gt;&lt;&lt;&lt;
saxFactory = SAXParserFactory.newInstance();
saxFactory.setValidating(true);
&gt;&gt;&gt;


\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static SAXParserFactory saxFactory;
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Handle XSLT}
%%%%%%%%%%%%%

%%%%%%%%%%%%%
\subsubsection{Outline}
%%%%%%%%%%%%%

Associate a name to the result of applying the named XSLT
transformation on the named XML code.  If the name is omitted, the
outcome is sent to the output file named in the command line. If such
file name is not provided, the standard I/O stream is assumed.


\begin{verbatim}
&lt;xslt  name="..." xml="..."  xsl="..." /&gt;
\end{verbatim}

Note that XSLT is just a restricted kind of XML code.



\&lt;xtpipes entries\&gt;&lt;&lt;&lt;
| xslt
&gt;&gt;&gt;


\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!ELEMENT xslt EMPTY &gt;
&lt;!ATTLIST xslt
          name CDATA #IMPLIED
          xml  CDATA #REQUIRED
          xsl  CDATA #REQUIRED
&gt;
&gt;&gt;&gt;

\&lt;execute xslt\&gt;&lt;&lt;&lt;
try{
   `&lt;StreamSource inDoc = ...`&gt;
   `&lt;StreamSource inXslt = ...`&gt;
   `&lt;StreamResult outDoc = ...`&gt;
   errMssg = null;
   fc.setErrorListener( `&lt;transformer factory XSLT error listener`&gt; );
   Transformer transformer = fc.newTransformer( inXslt );
   transformer.setErrorListener( `&lt;transformer XML error listener`&gt; );
   transformer.transform(inDoc, outDoc );
   `&lt;store xslt outcome`&gt;
} catch ( javax.xml.transform.TransformerException e ){
   if( Xtpipes.trace ){ e.printStackTrace(); }
   instructionErr( node,
                   e.getMessage()
                   +
                   ((errMssg==null)? "" : ("; " +errMssg))
                   , 37);
} catch ( Exception e ){
   if( Xtpipes.trace ){ e.printStackTrace(); }
   instructionErr( node, (errMssg==null)? e.toString()
                                        : e.toString() + "; " + errMssg
                       , 16 );
}
&gt;&gt;&gt;







%%%%%%%%%%%%%
\subsubsection{Input}
%%%%%%%%%%%%%

\&lt;StreamSource inDoc = ...\&gt;&lt;&lt;&lt;
Node xmlNode = node.getAttributes().getNamedItem( "xml" );
StreamSource inDoc = null;
String xml;
if( xmlNode == null ){
   `&lt;inDoc = input stream source`&gt;
} else {
   xml = xmlNode.getNodeValue();
   String doc = (String) map.get(xml);
   if( doc!=null ){
      byte [] bytes = doc.getBytes("UTF-8");
      ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
      inDoc = new StreamSource( bais );
}  }
&gt;&gt;&gt;




\&lt;inDoc = input stream source\&gt;&lt;&lt;&lt;
if( inData == null ){
   inDoc = new StreamSource( new File(inFile) );
} else {
   byte [] bytes = inData.getBytes("UTF-8");
   ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
   inDoc = new StreamSource( bais );
}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsubsection{XSLT}
%%%%%%%%%%%%%

\&lt;StreamSource inXslt = ...\&gt;&lt;&lt;&lt;
String xslt = node.getAttributes()
                  .getNamedItem( "xsl" ).getNodeValue();
String templates = (String) map.get(xslt);
byte [] bytes = templates.getBytes("UTF-8");
ByteArrayInputStream bais =  new ByteArrayInputStream( bytes );
StreamSource inXslt = new StreamSource( bais );
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsubsection{Output}
%%%%%%%%%%%%%



\&lt;StreamResult outDoc = ...\&gt;&lt;&lt;&lt;
Node nameNode = node.getAttributes().getNamedItem("name");
StreamResult outDoc;
CharArrayWriter caos = null;
if( nameNode == null ){
   outDoc = new StreamResult(outPrintWriter);
   returnToFile = false;
} else {
   caos = new CharArrayWriter();
   outDoc  = new StreamResult(caos);
}
&gt;&gt;&gt;


\&lt;store xslt outcome\&gt;&lt;&lt;&lt;
`&lt;store chars into map`&gt;
&gt;&gt;&gt;





\&lt;NO\&gt;&lt;&lt;&lt;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamResult outDoc  = new StreamResult(baos);
&gt;&gt;&gt;


\&lt;NO\&gt;&lt;&lt;&lt;
String name = node.getAttributes()
                .getNamedItem( "name" ).getNodeValue();
bytes = baos.toByteArray();
map.put( name, (Object) new String(bytes) );
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{DOM}
%%%%%%%%%%%%%


%%%%%%%%%%%%%
\subsubsection{Outline}
%%%%%%%%%%%%%


Associate a name to the result of applying the named method on the DOM
of the named XML code. The method should have an interface similar to
\verb+public static void m( Node dom )+.

\begin{verbatim}
&lt;dom name="..." xml="..." method="..." class="..." /&gt;
\end{verbatim}


\&lt;xtpipes entries\&gt;&lt;&lt;&lt;
| dom
&gt;&gt;&gt;


\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!ELEMENT dom EMPTY &gt;
&lt;!ATTLIST dom
          name   CDATA #REQUIRED
          xml    CDATA #REQUIRED
          method CDATA #REQUIRED
          class  CDATA #REQUIRED
          dcl    CDATA #IMPLIED DEFAULT (yes | no) "no"
&gt;
&gt;&gt;&gt;



\&lt;execute dom\&gt;&lt;&lt;&lt;
try{
   `&lt;load xml into dom`&gt;
   `&lt;transform dom`&gt;
   `&lt;store dom into map`&gt;
} catch ( NoSuchMethodException e ){
   instructionErr( node,
       "could not find method: " + e.getMessage(), 18 );
} catch ( java.lang.reflect.InvocationTargetException e ){
   if( Xtpipes.trace ){ e.printStackTrace(); }
   instructionErr( node, e.getCause().toString(), 36);
} catch ( Exception e ){
   if( Xtpipes.trace ){ e.printStackTrace(); }
   instructionErr( node, e.toString(), 20 );
}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsubsection{Transform}
%%%%%%%%%%%%%


\&lt;transform dom\&gt;&lt;&lt;&lt;
String className = node.getAttributes()
             .getNamedItem( "class" ).getNodeValue();
String methodName = node.getAttributes()
             .getNamedItem( "method" ).getNodeValue();
Class &lt;?&gt; cls = Class.forName( className );
Class&lt;?&gt;  [] argTypes = { Node.class };
Method m = cls.getMethod( methodName, argTypes );
Object parmValues[] = new Object[1];
parmValues[0] = dom;
m.invoke( null, parmValues );
&gt;&gt;&gt;

\&lt;xtpipes initialization\&gt;&lt;&lt;&lt;
domFactory.setValidating(false);
domBuilder = domFactory.newDocumentBuilder();
&gt;&gt;&gt;

\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static DocumentBuilder domBuilder;
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsubsection{Input Stream}
%%%%%%%%%%%%%


\&lt;load xml into dom\&gt;&lt;&lt;&lt;
Node xmlNode = node.getAttributes().getNamedItem( "xml" );
Document dom;
if( xmlNode == null ){
   `&lt;dom = parse input`&gt;
} else {
   String xml = xmlNode.getNodeValue();
   String doc = (String) map.get(xml);
   if( doc == null ){
      instructionErr( node, "improper xml attribute value", 18 );
   }
   byte [] bytes = doc.getBytes("UTF-8");
   InputStream is = new ByteArrayInputStream( bytes );
   dom = domBuilder.parse (is);
}
&gt;&gt;&gt;

\&lt;dom = parse input\&gt;&lt;&lt;&lt;
if( inData == null ){
   dom = domBuilder.parse( new File(inFile) );
} else {
   byte [] bytes = inData.getBytes("UTF-8");
   InputStream is =  new ByteArrayInputStream( bytes );
   dom = domBuilder.parse (is);}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsubsection{Output Stream}
%%%%%%%%%%%%%


\&lt;store dom into map\&gt;&lt;&lt;&lt;
`&lt;StreamResult outDoc = ...`&gt;
cleanXmlns(dom);
DOMSource domSource = new DOMSource(dom);
try{
   identityTransformer.transform( domSource, outDoc );
} catch ( javax.xml.transform.TransformerException e ){
  String s = Xtpipes.trace?
      (
        "\n------------------------ xml code ------------------------\n"
      + serialize( dom )
      + "\n----------------------------------------------------------\n"
      )
      : "";
   instructionErr( node, e.getMessage() + s, 35 );
}
if( nameNode != null ){
  String name = nameNode.getNodeValue();
  char [] chars = caos.toCharArray() ;
  String domString = new String(chars);
  `&lt;remove dom dcl`&gt;
  map.put( name, (Object) domString );
}
&gt;&gt;&gt;


\&lt;remove dom dcl\&gt;&lt;&lt;&lt;
Node dcl = node.getAttributes().getNamedItem( "dcl" );
if(  ((dcl == null) || (dcl.getNodeValue().equals("no") ))
     &amp;&amp;
       (domString.length() &gt; 7)
     &amp;&amp;
       domString.startsWith("&lt;?xml")
     &amp;&amp;
       !Character.isLetterOrDigit( domString.charAt(5) )
){
    domString = domString.substring( domString.indexOf("?&gt;") + 2 );
}
&gt;&gt;&gt;






\&lt;NO\&gt;&lt;&lt;&lt;
String name = node.getAttributes()
             .getNamedItem( "name" ).getNodeValue();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
identityTransformer.transform( new DOMSource(dom),
                             new StreamResult(baos) );
bytes = baos.toByteArray();
map.put( name, (Object) new String(bytes) );
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Handle SAX}
%%%%%%%%%%%%%


%%%%%%%%%%%%%
\subsubsection{outline}
%%%%%%%%%%%%%

Apply the specified content-handler and filters on the XML
content.

\begin{verbatim}
&lt;sax name="..." xml="..." content-handler="..."
                          lexical-handler="..." &gt;
   &lt;script element="..." &gt; ... &lt;/script&gt;
   ...
   &lt;script element="..." &gt; ... &lt;/script&gt;
&lt;/sax&gt;
\end{verbatim}


If provided, the {\bf name attribute} is associated to the outcome.
If omitted, the output file name from the command line is assumed. If
such file name is not provided, the standard I/O stream is assumed.

If the {\bf xml attribute} is not internally defined (within the hash
table), a file name is assumed.  If not provided, it stands for the
input file name provided in the command line.

The \verb+content-handler+ attribute gets a comma seperated list of
classes names. The first argument refers to a content handler, the
other arguments refer to filters. A content handler gets five
arguments: output stream, an HashMap refering to the different scripts
enclosed by the sax instruction, a method, log stream, and a boolean
trace indicator.  A filter and a lexical-constractor gets three
arguments: output stream, log stream, and a boolean trace indicator.

The sax instruction applies the filters and the content handler on the
provided xml string.  The script elements offer definitions of scripts
delivered to the content handler. The ScriptsManager content handler
of the distribution (Section~\ref{ScriptsManager}), for instance,
invokes these scripts when their corresponding named elemets are
encountered.


\&lt;xtpipes entries\&gt;&lt;&lt;&lt;
| sax
&gt;&gt;&gt;


\&lt;xtpipes.dtd\&gt;&lt;&lt;&lt;
&lt;!ELEMENT sax (#PCDATA | script)*  &gt;
&lt;!ELEMENT script (#PCDATA `&lt;xtpipes entries`&gt; )*  &gt;
&lt;!ATTLIST sax
          name            CDATA #IMPLIED
          xml             CDATA #IMPLIED
          content-handler CDATA #REQUIRED
          lexical-handler CDATA #IMPLIED
&gt;
&lt;!ATTLIST script
          element CDATA #REQUIRED
&gt;
&gt;&gt;&gt;

\&lt;execute sax\&gt;&lt;&lt;&lt;
String errMsg = "";
try{
   `&lt;load xml into input source`&gt;
   `&lt;String [] className = ...`&gt;
   `&lt;ch := content handler`&gt;
   `&lt;get sax reader`&gt;
   XMLReader reader = saxReader;
   `&lt;insert sax filters`&gt;
   errMsg = "setContentHandler( "
            + className[0].trim() + " )";
   saxReader.setContentHandler( (org.xml.sax.ContentHandler) ch );
   `&lt;saxReader += lexical handler`&gt;
   `&lt;saxReader := ignore DOCTYPE statement`&gt;
   if( inputSource==null ){
       `&lt;open sax input file`&gt;
   } else {
       errMsg = "xtpipes sax parsing error";
       saxReader.parse( inputSource );
   }
   `&lt;store chars into map`&gt;
   saxReaderStack.push( reader );
} catch ( java.io.FileNotFoundException e ){
   instructionErr( node, errMsg
                   + "could not find file: " + e.getMessage(), 19 );
} catch ( ClassNotFoundException e ){
   instructionErr( node, errMsg
                   + " class not found: "
                   + e.getMessage() + "\n classpath = "
                   + System.getProperty("java.class.path")
                   + " ---", 22 );
} catch ( java.lang.reflect.InvocationTargetException e ){
   instructionErr( node, errMsg + ": " + e.getCause(), 23 );
} catch ( Exception e ){
   Xtpipes.logWriter.flush();
   e.printStackTrace();
   instructionErr( node, errMsg + ": " + e.toString(), 29 );
}
&gt;&gt;&gt;

\&lt;open sax input file\&gt;&lt;&lt;&lt;
errMsg = "While parsing file " + xml + ": ";
InputStream inputStream = null;
if( Xtpipes.ml2xml == null ){
   if( Xtpipes.trace ){
       Xtpipes.logWriter.println(
         "No request for ml2xml configuration (command line option -x)" );
   }
   `&lt;inputStream := ml2xml-less imput`&gt;
} else {
   `&lt;inputStream := (InputStream) new Ml2xml(filename, "foo.m2x")`&gt;
}
saxReader.parse( new InputSource(inputStream) );
`&lt;Ml2xml close files`&gt;
&gt;&gt;&gt;

\&lt;inputStream := ml2xml-less imput\&gt;&lt;&lt;&lt;
try{
    inputStream = (InputStream) (new File(xml).toURI().toURL().openStream());
} catch ( java.io.FileNotFoundException ioe ){
    try{
       URL url = null;
       try {
           url = new URL(xml);
       } catch ( java.net.MalformedURLException fnf ){
           url = new File(xml).toURI().toURL();
       }
       inputStream = (InputStream) (url.openStream());
    } catch ( java.io.FileNotFoundException fnf ){
        inputStream = (InputStream)
           (
              new File( new File(xml).toURI().toURL().toString() )
              . toURI().toURL()
              . openStream()
           );
}   }
&gt;&gt;&gt;





%%%%%%%%%%%%%
\subsubsection{SAX Reader}
%%%%%%%%%%%%%

The sax reader is pushed into the stack when its job is done, for
use in other sax instructions.  The stack is needed because nested sax
instructions need unspecified number of readers. The filters may
change the sax readers, so the readers need saving for later storing
them in the stacks.

\&lt;get sax reader\&gt;&lt;&lt;&lt;
XMLReader saxReader;
if( saxReaderStack.empty() ){
   SAXParser saxParser = saxFactory.newSAXParser();
   saxReader = saxParser.getXMLReader();
   `&lt;saxReader := ignore DOCTYPE statement`&gt;
} else {
   saxReader = (XMLReader) saxReaderStack.pop();
}
&gt;&gt;&gt;




\&lt;xtpipes initialization\&gt;&lt;&lt;&lt;
saxFactory = SAXParserFactory.newInstance();
saxFactory.setValidating(false);
&gt;&gt;&gt;

\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static Stack &lt;XMLReader&gt; saxReaderStack;
&gt;&gt;&gt;


\&lt;init fields\&gt;&lt;&lt;&lt;
saxReaderStack = new Stack &lt;XMLReader&gt; ();
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Handling DOCTYPE Statements}
%%%%%%%%%%%%%


The following code hides the DOCTYPE entry when searching the xtpipes
processing instruction and when loading an input file.

\&lt;saxReader := ignore DOCTYPE statement\&gt;&lt;&lt;&lt;
saxReader.setEntityResolver(new org.xml.sax.EntityResolver() {
   public InputSource resolveEntity(
                          String publicId, String systemId) {
     if( (new File(systemId)).exists() ){
        return new org.xml.sax.InputSource( systemId );
      }
      StringReader strReader = new StringReader("");
      return new org.xml.sax.InputSource(strReader);
   }
});
&gt;&gt;&gt;

The default SAX behavior observes the DOCTYPE statement and assumes
the following setup.

\begin{verbatim}
saxReader.setEntityResolver(new org.xml.sax.EntityResolver() {
   public InputSource resolveEntity(
      String publicId, String systemId) {
      return null;
   }
});
\end{verbatim}




%%%%%%%%%%%%%
\subsubsection{Input}
%%%%%%%%%%%%%


\&lt;load xml into input source\&gt;&lt;&lt;&lt;
Node xmlNode = node.getAttributes().getNamedItem( "xml" );
InputSource inputSource=null;
String xml = null;
if( xmlNode == null ){
   `&lt;load xml from input`&gt;
} else {
   xml = xmlNode.getNodeValue();
   String doc = (String) map.get(xml);
   if( doc!=null ){
      byte [] bytes = doc.getBytes("UTF-8");
      ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
      inputSource = new InputSource( bais );
}  }
&gt;&gt;&gt;


\&lt;load xml from input\&gt;&lt;&lt;&lt;
if( inData == null ){
   xml = inFile;
} else {
   byte [] bytes = inData.getBytes("UTF-8");
   ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
   inputSource = new InputSource( bais );
}
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsubsection{Output Stream}
%%%%%%%%%%%%%


\&lt;output stream for sax\&gt;&lt;&lt;&lt;
Node nameNode = node.getAttributes().getNamedItem("name");
PrintWriter out;
CharArrayWriter caos = null;
if( nameNode == null ){
   out = outPrintWriter;
   returnToFile = false;
} else {
   caos = new CharArrayWriter();
   out = new PrintWriter( caos );
}
&gt;&gt;&gt;

\&lt;store chars into map\&gt;&lt;&lt;&lt;
if( nameNode != null ){
   String name = nameNode.getNodeValue();
   char [] chars = caos.toCharArray() ;
   map.put( name, (Object) new String(chars) );
}
&gt;&gt;&gt;

Note: Characters are prefered over bytes as they support
unicode.

%%%%%%%%%%%%%
\subsection{Get Content Handler for SAX}
%%%%%%%%%%%%%

\&lt;String [] className = ...\&gt;&lt;&lt;&lt;
String [] className = node.getAttributes()
                     .getNamedItem( "content-handler" )
                     .getNodeValue()
                     .split(",");
&gt;&gt;&gt;




The constructor of a content handler is provided five arguments:

\begin{itemize}
\item
An output stream
\item
A hash map containing the enclosed defdinitions of scripts
\item A method name
\item A log stream
\item A trace flag
\end{itemize}


\&lt;ch := content handler\&gt;&lt;&lt;&lt;
Class&lt;?&gt; [] argTypes = {
         PrintWriter.class, HashMap.class, Method.class,
         PrintWriter.class, boolean.class };
`&lt;output stream for sax`&gt;
Object parmValues[] = new Object[5];
parmValues[0] = out;
`&lt;sax scripts`&gt;  parmValues[1] = scripts;
parmValues[2] = method;
parmValues[3] = Xtpipes.logWriter;
parmValues[4] = (Object) Xtpipes.trace;
Class&lt;?&gt; cls = Class.forName( className[0].trim() );
Constructor&lt;?&gt; c = cls.getConstructor( argTypes );
Object ch = (Object) c.newInstance( parmValues );
&gt;&gt;&gt;

\&lt;sax scripts\&gt;&lt;&lt;&lt;
HashMap &lt;String,Object&gt; scripts = new HashMap &lt;String,Object&gt; ();
Node script = node.getFirstChild();
while( script != null ){
  if( script.getNodeType()==Node.ELEMENT_NODE ){
     String element = script.getAttributes().getNamedItem( "element" )
                                       .getNodeValue();
     if( scripts.containsKey(element) ){
        System.err.println(
           "--- Warning --- redfining script: " + element );
     }
     scripts.put( element, (Object) script );
  }
  script = script.getNextSibling();
}
&gt;&gt;&gt;

\&lt;xtpipes initialization\&gt;&lt;&lt;&lt;
Class &lt;?&gt; cls = Xtpipes.class;
Class&lt;?&gt; [] argTypes = { Node.class, String.class };
method = cls.getMethod( "execute", argTypes );
&gt;&gt;&gt;

\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static Method method;
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Get Filters}
%%%%%%%%%%%%%



\&lt;insert sax filters\&gt;&lt;&lt;&lt;
for( int i=1; i&lt;className.length; i++ ){
   argTypes = new Class [3];
   argTypes[0] = PrintWriter.class;
   argTypes[1] = PrintWriter.class;
   argTypes[2] = boolean.class;
   parmValues = new Object[3];
   parmValues[0] = out;
   parmValues[1] = Xtpipes.logWriter;
   parmValues[2] = (Object) Xtpipes.trace;
   errMsg = "Class.forName( " + className[i].trim() + ") " ;
   cls = Class.forName( className[i].trim() );
   errMsg = "get-constructor "
            + className[i].trim()
            + "( PrintWriter, PrintWriter, boolean ) " ;
   c = cls.getConstructor( argTypes );
   errMsg = "get-object "
            + className[i].trim()
            + "( PrintWriter, PrintWriter, boolean ) " ;
   if( (cls.getModifiers() % 2) != 1 ){
      errMsg += "; class not defined to be public. ";
   }
   XMLFilter filter = (XMLFilter) c.newInstance( parmValues );
   errMsg = "set-parent "
            +  className[i].trim()
            + "( PrintWriter, PrintWriter, boolean ) " ;
   filter.setParent(saxReader);
   saxReader = filter;
}
&gt;&gt;&gt;


The filters are assumed to have a tri-parameter constructors which
get an output stream for first arguments, log stream for second argument, and
a trace boolean value for third argument.



%%%%%%%%%%%%%
\subsection{Get Lexical Handler for SAX}
%%%%%%%%%%%%%









The constructor of a lexical handler is provided the
content handler as an argument.



\&lt;saxReader += lexical handler\&gt;&lt;&lt;&lt;
Node lexAttr = node.getAttributes()
                  .getNamedItem( "lexical-handler" );
if( lexAttr != null ){
   String lexName = lexAttr.getNodeValue();
   argTypes = new Class[3];
   argTypes[0] = Class.forName( className[0].trim() );
   argTypes[1] = PrintWriter.class;
   argTypes[2] = boolean.class;
   parmValues = new Object[3];
   parmValues[0] = ch;
   parmValues[1] = Xtpipes.logWriter;
   parmValues[2] = (Object) Xtpipes.trace;
   errMsg = "Class.forName( " + lexName.trim() + ") " ;
   cls = Class.forName( lexName.trim() );
   errMsg = "get-constructor " +
                lexName.trim() +
                "( " + className[0].trim() + " ) " ;
   c = cls.getConstructor( argTypes );
   errMsg = "get-object " +
               lexName.trim() + "( ... ) " ;
   Object xh = (Object) c.newInstance( parmValues );
   errMsg = "set lexical handler " + lexName.trim() + " ";
   saxReader.setProperty(
       "http://xml.org/sax/properties/lexical-handler",
       (org.xml.sax.ext.LexicalHandler) xh
    );
}
&gt;&gt;&gt;










%%%%%%%%%%%%%%%%%%
\section{Entity Resolver}
%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%
\subsection{Interface}
%%%%%%%%%%%%%




\&lt;new EntityResolver()\&gt;&lt;&lt;&lt;
new XtpipesEntityResolver()
&gt;&gt;&gt;

\&lt;class XtpipesEntityResolver\&gt;&lt;&lt;&lt;
class XtpipesEntityResolver implements  org.xml.sax.EntityResolver {
   `&lt;InputSource resolveEntity(publicID, systemId)`&gt;
}
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Implementation}
%%%%%%%%%%%%%



\&lt;InputSource resolveEntity(publicID, systemId)\&gt;&lt;&lt;&lt;
public InputSource resolveEntity(String publicID, String systemID)
                                                    throws SAXException {
   if( Xtpipes.trace ){
      Xtpipes.logWriter.println( "Resolving: publicID = \" " + publicID
                + "\"  systemID = \"" + systemID + "\"" );
   }
   String file = FileInfo.searchFile( systemID );
   if( file != null ){
     try{
        file = new File(file).toURI().toURL().toString();
        return new InputSource( file );
     } catch( java.net.MalformedURLException mfe){
        throw new SAXException(
          "--- xtpipes error 30 --- improper file name: " + file  );
   } }
   return null;
}
&gt;&gt;&gt;



%%%%%%%%%%%%%%%%%%
\section{File Information}
%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%
\subsection{Outline}
%%%%%%%%%%%%%




% 
\AtEndDocument{
   \OutputCodE\&lt;FileInfo.java\&gt;
}

\AddFile{FileInfo.java}{xtpipes}

\&lt;FileInfo.java\&gt;&lt;&lt;&lt;
package xtpipes;
/* FileInfo.java (`version), generated from `jobname.tex
   Copyright (C) 2009-2010 TeX Users Group
   Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; */
`&lt;FileInfo imports`&gt;
public class FileInfo{
     `&lt;FileInfo fields`&gt;
   public FileInfo(PrintWriter log, String iii_scriptDir, boolean trace) {
      FileInfo.log = log;
      FileInfo.ii_scriptDir = iii_scriptDir;
      FileInfo.trace = trace;
      `&lt;classPaths[] := ...`&gt;
      `&lt;scriptPaths[] := ...`&gt;
   }
   `&lt;static String searchFile( file )`&gt;
   `&lt;static String [] getPaths( dirs )`&gt;
   `&lt;static String cleanPath( path )`&gt;
   `&lt;static String searchDirectory(dir, file)`&gt;
}
&gt;&gt;&gt;

\&lt;FileInfo fields\&gt;&lt;&lt;&lt;
static String [] classPaths = null;
static String [] scriptPaths = null;
static java.util.HashMap &lt;String,String&gt; registry =
                                  new java.util.HashMap &lt;String,String&gt;();
static String slash = System.getProperty("file.separator");
static String ii_scriptDir;
static PrintWriter log;
static boolean trace;
&gt;&gt;&gt;


\&lt;FileInfo imports\&gt;&lt;&lt;&lt;
import java.io.File;
import java.io.PrintWriter;
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Search Engine}
%%%%%%%%%%%%%




\&lt;static String searchFile( file )\&gt;&lt;&lt;&lt;
public static String searchFile( String file ){
   String key = ((ii_scriptDir == null)? "" : ii_scriptDir )
                + "!" + file;
   String result = (String) registry.get( key );
   if( result == null ){
      for(int i=0; i&lt;2; i++){
         if( trace ){
            log.println( "Searching: " + file );
         }
         if( (new File(file)).exists() ){
            result = ( file.indexOf(slash) == -1 )?
                         (System.getProperty("user.dir") + slash + file)
                        :
                         file;
         }
         else {
            if( ii_scriptDir != null ){
               `&lt;search file in script directories`&gt;
            }
            if( result == null ){
               `&lt;search file in classpath/xtpipes/lib`&gt;
         }  }
         if( result != null ){ break; }
         file =  new File(file).getName();
      }
      if( result != null ){
        result = FileInfo.cleanPath(result);
        registry.put(key, result);
      }
   }
   if( trace ){
      if( result == null ){
         log.println(
            "Directory paths from xtpipes command line option -i: "
                                            + ii_scriptDir );
      } else { log.println( "Found: " + result + "\n" ); }
      log.flush();
   }
   return result;
}
&gt;&gt;&gt;



\&lt;search file in script directories\&gt;&lt;&lt;&lt;
int k = scriptPaths.length;
while( k&gt;0 ){
  k--;
  if( trace ){
    log.println( "Searching: " + file
                   + ", recursively in directory: " + scriptPaths[k] );
  }
  result = searchDirectory( new File(scriptPaths[k]), file);
  if( result != null ){ break; }
}
String s = ii_scriptDir + file;
if( (new File( s )).exists() ){ result = s; }
&gt;&gt;&gt;


\&lt;search file in classpath/xtpipes/lib\&gt;&lt;&lt;&lt;
int k = classPaths.length;
String toFile = "xtpipes" + slash + "lib" + slash + file;
while( k&gt;0 ){
  k--;
  String s =  classPaths[k] + toFile;
  if( trace ){ log.println( "Searching: " + s ); }
  if( new File(s).exists() ){ result = s; break; }
}
&gt;&gt;&gt;


\&lt;static String searchDirectory(dir, file)\&gt;&lt;&lt;&lt;
static String searchDirectory(File dir, String file) {
    String result = null;
    if( dir.isDirectory() ){
       String [] children = dir.list();
       for (int i=0; i&lt;children.length; i++) {
          result = searchDirectory( new File(dir,children[i]), file);
          if( result != null ) { break; }
       }
    } else {
       String s = dir.toString();
       if( s.equals(file) || s.endsWith(slash + file) ){
           result = s;
        }
     }
     return result;
}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Class Paths}
%%%%%%%%%%%%%




\&lt;classPaths[] := ...\&gt;&lt;&lt;&lt;
classPaths = FileInfo.getPaths( System.getProperty("java.class.path") );
&gt;&gt;&gt;

Script paths are to be encoded in a similar manner as class paths.

\&lt;classPaths[] := ...\&gt;&lt;&lt;&lt;
if( iii_scriptDir != null ){
   scriptPaths = FileInfo.getPaths( iii_scriptDir );
}
&gt;&gt;&gt;

\&lt;static String [] getPaths( dirs )\&gt;&lt;&lt;&lt;
static String [] getPaths( String dirs ){
      String [] paths = null;
   paths = dirs.split( System.getProperty("path.separator") );
   int k = paths.length;
   while( k&gt;0 ){
      k--;
      `&lt;set full path`&gt;
      int len = paths[k].length();
      if( (len&gt;1) &amp;&amp; (paths[k].lastIndexOf(slash + ".") == (len-1)) ){
         paths[k]  = paths[k].substring(0,len-1);
      } else if( (len&gt;0) &amp;&amp; ((len-1) != paths[k].lastIndexOf( slash )) ){
         paths[k] += slash;
   }  }
   return paths;
}
&gt;&gt;&gt;



\&lt;set full path\&gt;&lt;&lt;&lt;
paths[k] = cleanPath( paths[k] );
&gt;&gt;&gt;

\&lt;\&gt;&lt;&lt;&lt;
if( (paths[k].length() &gt; 0) &amp;&amp; (paths[k].charAt(0) == '~') ){
  if( (paths[k].length() == 1)|| (paths[k].charAt(1) != '~') ){
    paths[k] = System.getProperty( "user.home" ) + paths[k].substring(1);
}  }
if( paths[k].charAt(0) == '.' ){
   paths[k] = System.getProperty( "user.dir" ) + slash + paths[k];
}
&gt;&gt;&gt;


%%%%%%%%%%%%%%%%%%
\section{Input Objects for  XML Files}
%%%%%%%%%%%%%%%%%%

The XML files my contain faults as a brute force approach is applied in
which the file is scanned directly without trying to build an XML object.

%%%%%%%%%%%%%
\subsection{Outline}
%%%%%%%%%%%%%

% 
\AtEndDocument{
   \OutputCodE\&lt;InputObject.java\&gt;
}

\AddFile{InputObject.java}{xtpipes}


\&lt;InputObject.java\&gt;&lt;&lt;&lt;
package xtpipes;
/* InputObject.java (`version), generated from `jobname.tex
   Copyright (C) 2009-2010 TeX Users Group
   Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; */
`&lt;InputObject imports`&gt;

public class InputObject{
      `&lt;InputObject fields`&gt;
   `&lt;public InputObject(...)`&gt;
   `&lt;java.io.InputStream getInputStream( filename )`&gt;
   `&lt;java.io.InputStream getInputStream( url )`&gt;
   `&lt;void buildProfile( boolean trace )`&gt;
   public InputStream getInputStream(){ return inputStream; }
   public String getFilename(){
      return (url == null)?
         ( (connection == null)? filename
                               :
                                 connection . getURL() . toString()
         )
       : url;
   }
   public String getContentType(){ return contentType; }
   public String getMetaType(){ return metaType; }
   public String getPublicId(){ return publicId; }
   public String getSystemId(){ return systemId; }
   public String getXtpipes(){ return xtpipes; }
   public String getRoot(){ return root; }
   public String getDtdRoot(){ return dtdRoot; }
}
&gt;&gt;&gt;

\&lt;InputObject fields\&gt;&lt;&lt;&lt;
InputStream inputStream = null;
URLConnection connection = null;
String filename = null;
static PrintWriter log;
&gt;&gt;&gt;

\&lt;InputObject imports\&gt;&lt;&lt;&lt;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Constructor}
%%%%%%%%%%%%%




\&lt;public InputObject(...)\&gt;&lt;&lt;&lt;
public InputObject( String filename, PrintWriter log ){
   InputObject.log = log;
   filename = filename.trim();
   try{
      inputStream = getInputStream(filename);
   } catch (Exception exp0){
      if( !filename.startsWith( "http://" ) ){
         try{
            String name = "http://" + filename;
            inputStream = getInputStream( name );
            filename = name;
         } catch (Exception exp1){
            try{
               String name = FileInfo.cleanPath(filename);
               inputStream = getInputStream( name );
               filename = name;
            } catch (Exception exp2){ inputStream = null; }
   }  }  }
   this.filename = filename;
}
&gt;&gt;&gt;

\&lt;public InputObject(...)\&gt;&lt;&lt;&lt;
public InputObject( byte [] bytes, PrintWriter log ){
   InputObject.log = log;
   inputStream = new ByteArrayInputStream( bytes );
}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Stream from a  File Name}
%%%%%%%%%%%%%



\&lt;java.io.InputStream getInputStream( filename )\&gt;&lt;&lt;&lt;
private java.io.InputStream getInputStream(
                                      String filename )
                                   throws java.io.IOException{
   if( filename == null ){ return null; }
   URL url;
   java.io.InputStream inputStream = null;
//   String loadingError = "Failed to get requested file.";
   try {
      url = new File(filename).toURI().toURL();
      inputStream =  getInputStream( url );
   } catch (Exception ie) {
       try {
           url = new URL(filename);
           inputStream =  getInputStream( url );
       } catch (java.io.FileNotFoundException ife) {
           throw new java.io.IOException(
              "File not found: " + filename);
       } catch (Exception ife) {
           throw new java.io.IOException(ife + "\n" + ie);
   }   }
   return inputStream;
}
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Stream from a URL}
%%%%%%%%%%%%%

\&lt;java.io.InputStream getInputStream( url )\&gt;&lt;&lt;&lt;
private java.io.InputStream getInputStream( URL url )
                            throws java.io.FileNotFoundException,
                                             java.io.IOException {
   java.io.InputStream inputStream = null;
   String errMssg = "";
   try{
      connection = null;
      connection = url.openConnection();
      connection.setRequestProperty("User-Agent",
                      "["
                    + System.getProperty("os.name")
                    + " / "
                    + System.getProperty("os.arch")
                    + "]"
                    + "["
                    + System.getProperty("java.version")
                    + " - "
                    + System.getProperty("java.vendor")
                    + "]"

           );
      inputStream = connection.getInputStream();
   } catch(java.io.FileNotFoundException ve){
      errMssg = "File not found: " + url;
      throw new java.io.FileNotFoundException(
                 "--- Ml2xml input error --- " + errMssg );
   } catch (javax.net.ssl.SSLHandshakeException ve){
      errMssg = "SSL Handshake Exception: " + ve.getMessage();
      throw new javax.net.ssl.SSLHandshakeException(
                 "--- Ml2xml input error --- " + errMssg );
   } catch (java.net.UnknownHostException ve){
      errMssg = "Unknown Host Exception: " + ve.getMessage();
      throw new java.net.UnknownHostException(
                   "--- Ml2xml input error --- " + errMssg );
   }
   return inputStream;
}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Clean Path}
%%%%%%%%%%%%%



\&lt;static String cleanPath( path )\&gt;&lt;&lt;&lt;
public static String cleanPath( String path ){
     String slash = System.getProperty("file.separator");
     String userDir = System.getProperty( "user.dir" );
  `&lt;clean leading wigle`&gt;
  `&lt;clean leading dots`&gt;
  `&lt;clean internal dots`&gt;
  return path;
}
&gt;&gt;&gt;

\&lt;clean leading wigle\&gt;&lt;&lt;&lt;
  if( (path.length() &gt; 0) &amp;&amp; (path.charAt(0) == '~') ){
    if( (path.length() == 1) || (path.charAt(1) != '~') ){
      path = System.getProperty( "user.home" )
                             + path.substring(1);
  } }
&gt;&gt;&gt;

\&lt;clean leading dots\&gt;&lt;&lt;&lt;
  if( path.startsWith("..") ){
     path = userDir.substring(0,
               Math.max(0,Math.max(
                 userDir.lastIndexOf("/")
                 ,
                 userDir.lastIndexOf("\\")
               )))
            + path.substring(2);
  }
  if( path.startsWith(".") ){
     path = userDir + slash + path.substring(1);
  }
&gt;&gt;&gt;

\&lt;clean internal dots\&gt;&lt;&lt;&lt;
  int i;
  while(
    ((i=path.indexOf("/..")) != -1)
    ||
    ((i=path.indexOf("\\..")) != -1)
  ){
    String s = path.substring(0,i);
    int j = Math.max(s.lastIndexOf("/"), s.lastIndexOf("\\"));
    path = path.substring(0,j) + path.substring(i+3);
  }
  while(
    ((i=path.indexOf("/.")) != -1)
    ||
    ((i=path.indexOf("\\.")) != -1)
  ){
    String s = path.substring(0,i);
    int j = Math.max(s.indexOf("/"), s.indexOf("\\"));
    path = path.substring(0,j) + path.substring(i+2);
  }
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Profile: Connecting and Reading the Input File}
%%%%%%%%%%%%%

\&lt;void buildProfile( boolean trace )\&gt;&lt;&lt;&lt;
public void buildProfile( boolean trace ){
   if( trace ){
      log.println(
         "xtpipes (`version)"
         + "\n   java.version: "    + System.getProperty("java.version")
         + "\n   java.class.path: " + System.getProperty("java.class.path")
         + "\n   os.name: "         + System.getProperty("os.name")
         + "\n   user.home: "       + System.getProperty("user.home")
         + "\n   user.dir: "        + System.getProperty("user.dir")
           );
   }
   if( connection != null ){
     `&lt;profile info from connection`&gt;
   }
   `&lt;profile from preamble of file`&gt;
   if( trace ){
      log.println(
           " url = "           + url
         + "\n contentType = " + contentType
         + "\n publicId = "    + publicId
         + "\n systemId = "    + systemId
         + "\n xtpipes = "     + xtpipes
         + "\n root = "        + root
         + "\n dtdRoot = "     + dtdRoot
      );
}  }
&gt;&gt;&gt;


\&lt;profile info from connection\&gt;&lt;&lt;&lt;
contentType = connection . getContentType();
url = connection . getURL() . toString();
&gt;&gt;&gt;



\&lt;profile from preamble of file\&gt;&lt;&lt;&lt;
int max = 8192;
int buffSize = 4096;
byte [] buff = new byte [ buffSize ];
int m = 0;
int length = 0;
int ch;
int type = `&lt;undef type`&gt;;
String token = null;
while( m &lt; max ){
   try{
      int k = Math.min( max - m, buffSize );
      length = inputStream.read( buff, 0, k );
      if( length == -1 ){ break; }
      if( length == 0  ){ continue; }
   } catch (java.io.IOException e){
      System.err.println( "--- xtpipes error --- : " + e );
      break;
   }
   for(int i = 0 ; i &lt; length; i++ ){
     `&lt;search preamble info`&gt;
     m++;
}  }
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Profile: Scanning the Different Cases}
%%%%%%%%%%%%%




\&lt;search preamble info\&gt;&lt;&lt;&lt;
switch( ch = buff[i] ){
   case  '&lt;':  token = "";
               type = `&lt;new tok`&gt;;
               break;
   case  '&gt;':  if( token != null ){
                  token = token . replaceAll( "\\s+", " ");
                  `&lt;at token end`&gt;
                  token = null;
               }
               break;
   case '\n':
   case  ' ':  if( token != null ){
                  `&lt;at token space`&gt;
               }
               break;
   case  '"':
   case '\'':  if( token == null ){ break; }
               `&lt;public and system ids`&gt;
   default:    if( token != null ){
                  if( type == `&lt;pre doctype`&gt; ){
                     if( ch == 'D' ){
                        type = `&lt;doctype`&gt;;
                        token += (char) ch;
                     } else { token = null; type = `&lt;undef type`&gt;; }
                  }
                  else
                  if( token.equals("") &amp;&amp; (type == `&lt;new tok`&gt;) ){
                     `&lt;get token type`&gt;
                  } else { token += (char) ch; }
}              }
&gt;&gt;&gt;


\&lt;public and system ids\&gt;&lt;&lt;&lt;
if( !token.trim().equals("") ){
   if( token.trim().charAt(0) == ch ){
     if( type == `&lt;public id`&gt; ){
        publicId = token.trim().substring(1);
        type = `&lt;system id`&gt;;
        token = "";
        break;
     }
     else if( type == `&lt;system id`&gt; ){
        systemId = token.trim().substring(1);
        token = null;
        break;
     }
} }
&gt;&gt;&gt;


\&lt;get token type\&gt;&lt;&lt;&lt;
switch( ch ){
   case '!': type = `&lt;pre doctype`&gt;;
             break;
   case '?': type = `&lt;proc instruction`&gt; ;
             break;
   default:  if( Character.isLetter(ch)
                 &amp;&amp; ((root == null) || (metaType == null)) ){
                type = `&lt;root or meta`&gt;;
                token += (char) ch;
             } else { token = null; }
}
&gt;&gt;&gt;

\&lt;at token end\&gt;&lt;&lt;&lt;
if( type == `&lt;proc instruction`&gt; ){
   if( xtpipes == null ){
      int n = token.length();
      if( (n &gt; 1) &amp;&amp; (token.charAt( n - 1 ) == '?')
                  &amp;&amp; (token.startsWith("xtpipes") ) ){
         String s = token . substring(7,n-1) . replaceAll( "\\s+", "");
         n = s.length();
         if( (n&gt;6) &amp;&amp; (s.startsWith("file="))
                   &amp;&amp; (s.charAt(5) == s.charAt(n-1)) ){
           xtpipes = s.substring(6,n-1);
   }  }  }
} else if( type == `&lt;meta`&gt; ){
   if( metaType == null ){
      token = token . replaceAll( "\\s+", "");
      int k = token.indexOf("http-equiv");
      int n = token.indexOf("content");
      if( (k != -1) &amp;&amp; (n != -1) ){
         if( token.length() &gt; (Math.max(k,n)+3) ){
            if( token.substring(k+12).startsWith("Content-Type") ){
               token = token.substring(n+9);
               n = token.indexOf(";");
               if( n !=-1 ){ metaType = token.substring(0,n); }
   }  }  }  }
} else if( (type == `&lt;root or meta`&gt;) &amp;&amp; (root == null) ){
   root = token;
}
&gt;&gt;&gt;

\&lt;at token space\&gt;&lt;&lt;&lt;
if( type == `&lt;root or meta`&gt; ){
   if( token.equals("meta") ){
      if( metaType == null ){
         type = `&lt;meta`&gt;;
         token = " ";
      } else {
         token = null;
      }
   } else {
      if( root == null ){
        root = token;
      }
      token = null;
   }
} else if( type == `&lt;doctype`&gt; ){
   if( token.equals("DOCTYPE") ){
      type = `&lt;doctype root`&gt;;
      token = " ";
   } else { token = null; }
} else if( type == `&lt;doctype root`&gt; ){
   if( !token.trim().equals("") ){
      dtdRoot = token.trim();
      token = " ";
      type = `&lt;doctype id`&gt;;
   } else { token = null; }
} else if( type == `&lt;doctype id`&gt; ){
   if( !token.trim().equals("") ){
      token = token.trim();
      if( token.equals("PUBLIC") ){
         type = `&lt;public id`&gt;;
         token = "";
      } else if( token.equals("SYSTEM") ){
         type = `&lt;system id`&gt;;
         token = "";
      } else { token = null; }
   }
} else { token += ' '; }
&gt;&gt;&gt;


\&lt;InputObject fields\&gt;&lt;&lt;&lt;
String dtdRoot = null,
      publicId = null,
      systemId = null,
       xtpipes = null,
           url = null,
      metaType = null,
   contentType = null,
          root = null;
&gt;&gt;&gt;

\OP{undef type}
\OP{new tok}
\OP{root or meta}
\OP{pre doctype}
\OP{doctype}
\OP{doctype root}
\OP{doctype id}
\OP{public id}
\OP{system id}
\OP{proc instruction}
\OP{proc root}
\OP{meta}


%%%%%%%%%%%%%%%%%%
\section{Input Objects for XML Strings}
%%%%%%%%%%%%%%%%%%



%%%%%%%%%%%%%
\subsection{Search String for Indirection}
%%%%%%%%%%%%%


\&lt;search string for xtpipes instruction\&gt;&lt;&lt;&lt;
scriptFile = inputObject.getXtpipes();
rootName = inputObject.getRoot();
needScript = true;
&gt;&gt;&gt;


Remove XtPipesSearch!!!!!!!!!!!!!!

\&lt;\&gt;&lt;&lt;&lt;
try{
       `&lt;get sax reader`&gt;
       saxReader.setContentHandler( new XtPipesSearch() );
      `&lt;body of search string for xtpipes instruction`&gt;
       saxReaderStack.push( saxReader );
} catch(Exception e){
e.printStackTrace();
   instructionErr( node, errMsg + e.toString(), 13 );
}
&gt;&gt;&gt;

\&lt;body of search string for xtpipes instruction\&gt;&lt;&lt;&lt;
errMsg = "Searching &lt;?xtpipes file=\"...\"?&gt;  in "
        + inData.substring(0, Math.min(70,inData.length()))
        + "... : ";
byte [] bytes = inData.getBytes("UTF-8");
ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
InputSource is = new InputSource( bais );
saxReader.parse(is);
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{The Search Engine}
%%%%%%%%%%%%%



\&lt;xtpipes fields DELETED\&gt;&lt;&lt;&lt;
private static class XtPipesSearch extends DefaultHandler {
   public void  endElement(String uri,
                           String localName, String qName){
     `&lt;extract root element name`&gt;
   }
   public void processingInstruction(String target, String attrs) {
     if( !needScript &amp;&amp; target.equals("xtpipes") ){
        `&lt;extract script file name`&gt;
}  } }
&gt;&gt;&gt;


The input file is
searched for an alternative script within a processing instruction of
the form \verb+&lt;?xtpipes file="..." ?&gt;+.


\&lt;extract root element name\&gt;&lt;&lt;&lt;
rootName = qName;
&gt;&gt;&gt;


\&lt;extract script file name\&gt;&lt;&lt;&lt;
try {
   `&lt;get sax reader`&gt;
   saxReader.setContentHandler(new DefaultHandler() {
      public void startElement(String uri, String localName,
         String qName, Attributes atts) {
         String filename = atts.getValue("file");
         if( filename != null ){
            scriptFile = filename;
            `&lt;show script file name in log file`&gt;
            needScript = true;
      }  }
   });
   String str = "&lt;xtpipes " + attrs + "/&gt;";
   StringReader reader = new StringReader(str);
   InputSource in = new InputSource(reader);
   saxReader.parse(in);
   saxReaderStack.push( saxReader );
} catch(Exception e){
   System.err.println( "--- Error 10 --- " + e );
}
&gt;&gt;&gt;







\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static String  rootName;
&gt;&gt;&gt;


\&lt;init fields\&gt;&lt;&lt;&lt;
rootName = null;
&gt;&gt;&gt;




%%%%%%%%%%%%%%%%%%
\section{Information About the Transformation}
%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%
\subsection{User's System}
%%%%%%%%%%%%%



\&lt;output system info\&gt;&lt;&lt;&lt;
logWriter.println(
     "xtpipes (`version)"
     + "\n java.version: "    + System.getProperty("java.version")
     + "\n java.class.path: " + System.getProperty("java.class.path")
     + "\n os.name: "         + System.getProperty("os.name")
     + "\n user.home: "       + System.getProperty("user.home")
     + "\n user.dir: "        + System.getProperty("user.dir")
);
for( int k=0; k&lt;args.length; k++ ){
  logWriter.println( "     " + args[k] );
}
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Script to be Used}
%%%%%%%%%%%%%


\&lt;show script file name in log file\&gt;&lt;&lt;&lt;
if( messages ){
   logWriter.println(
      "Requesting XtPipes script file: "
      + filename );
}
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Preamble Attribute}
%%%%%%%%%%%%%

\&lt;preamble output into log\&gt;&lt;&lt;&lt;
if ( (attr != null) &amp;&amp; messages ) {
   logWriter.println( attr.getNodeValue() );
}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Tracing}
%%%%%%%%%%%%%


\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
static boolean trace;
&gt;&gt;&gt;

\&lt;init fields\&gt;&lt;&lt;&lt;
trace = false;
&gt;&gt;&gt;



\&lt;trace element\&gt;&lt;&lt;&lt;
if( trace ){
   logWriter.print( "[##] = xtpipes =&gt; " + instruction );
   if( node.hasAttributes() ){
      NamedNodeMap attributes = node.getAttributes();
      for(int i=0; i &lt; attributes.getLength(); i++ ){
         Node attr = attributes.item(i);
         logWriter.print( " "   + attr.getNodeName()
                         + "=\"" + attr.getNodeValue() + "\"" );
   } }
   logWriter.println(); logWriter.flush();
}
&gt;&gt;&gt;

\&lt;trace if true\&gt;&lt;&lt;&lt;
if( trace ){
   logWriter.print( "--&gt; true" );
}
&gt;&gt;&gt;

\&lt;trace if false\&gt;&lt;&lt;&lt;
if( trace ){
   logWriter.print( "--&gt; true" );
}
&gt;&gt;&gt;


\&lt;trace open script\&gt;&lt;&lt;&lt;
if( trace ){
   logWriter.println( "(" + scriptFile + ")" );
}
&gt;&gt;&gt;



%%%%%%%%%%%%%%%%%%
\section{loose Ends}
%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%
\subsection{Fix XML Defaults}
%%%%%%%%%%%%%%%%%%

\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
private static String [] ml2xml = null;
static Class&lt;?&gt; ml2xmlClassObj = null;
&gt;&gt;&gt;

\&lt;scan ml2xml argument\&gt;&lt;&lt;&lt;
if( args[n].substring(2).equals("") ){
   if( ml2xml == null ){ ml2xml = new String[0]; }
} else {
   if( ml2xml == null ){
      ml2xml = new String[1];
   } else {
      String [] m2x = new String [ml2xml.length + 1];
      for(int cnt=0; cnt &lt; ml2xml.length; cnt++){
        m2x[cnt] = ml2xml[cnt];
      }
      ml2xml = m2x;
   }
   ml2xml[ ml2xml.length - 1 ] = args[n].substring(2);
}
&gt;&gt;&gt;


\&lt;inputStream := (InputStream) new Ml2xml(filename, "foo.m2x")\&gt;&lt;&lt;&lt;
try{
   ml2xmlClassObj = Class.forName( "ml2xml.Ml2xml" );
} catch (java.lang.ClassNotFoundException cnf ){
   instructionErr( null, "Class not found: ml2xml.Ml2xml", 25 );
}
Class&lt;?&gt; [] argTyp = { String.class, String[].class };
Constructor&lt;?&gt; con = ml2xmlClassObj.getConstructor( argTyp );
try{
   `&lt;trace call to ml2xml`&gt;
   inputStream = (InputStream) con.newInstance(
         new Object[]{xml, ml2xml}
      );
} catch(java.lang.reflect.InvocationTargetException ite){
   String s = "Problem at: ml2xml.Ml2xml(" + xml + ","
              + "new String[]{" ;
   for(int i=0; i &lt; Xtpipes.ml2xml.length; i++){
      s += ((i==0)? "\"" : ", \"") + Xtpipes.ml2xml[i] + "\"";
   }
   s += "})";
   instructionErr( null, s + "; " + ite.getCause(), 38);
}
&gt;&gt;&gt;

 ite.getTargetException().printStackTrace();


\&lt;Ml2xml close files\&gt;&lt;&lt;&lt;
if( Xtpipes.ml2xml != null ){
   Class&lt;?&gt; [] argTyp = {};
   Method m = ml2xmlClassObj . getMethod( "closeFiles", argTyp );
   m.invoke( null, new Object[0] );
}
&gt;&gt;&gt;

\&lt;trace call to ml2xml\&gt;&lt;&lt;&lt;
if( Xtpipes.trace ){
   String s = "Calling: ml2xml.Ml2xml(inputStream,"
              + "new String[]{" ;
   for(int i=0; i &lt; Xtpipes.ml2xml.length; i++){
      s += ((i==0)? "\"" : ", \"") + Xtpipes.ml2xml[i] + "\"";
   }
   s += "})";
   Xtpipes.logWriter.println( s );
}
&gt;&gt;&gt;


\&lt;close ml2xml files\&gt;&lt;&lt;&lt;
if( ml2xmlClassObj != null ){
  Class&lt;?&gt; [] argTypes = { };
  Method m = ml2xmlClassObj.getMethod( "closeFiles", argTypes );
  Object parmValues[] = new Object[0];
  m.invoke( null, parmValues );
}
&gt;&gt;&gt;


\&lt;xtpipes imports\&gt;&lt;&lt;&lt;
import java.lang.reflect.Constructor;
&gt;&gt;&gt;

Ml2xml is referenced through reflection instead of directly so that xtpipes can
be delivered also without that utility, e.g., for tex4ht where no treatment of faulty
XML file is to be done. In fact, this approach can be generalized to offer
arbitrary filter for the input.




%%%%%%%%%%%%%%%%%% 
\subsection{Unicode Filter}
%%%%%%%%%%%%%%%%%%

Non-ASCII characters are translated into unicode hexadecimal entities.
The same holds for ascii characters listed within the filter.

\AtEndDocument{
   \OutputCodE\&lt;XtpipesUni.java\&gt;
}
\AddFile{XtpipesUni.java}{xtpipes}


\&lt;XtpipesUni.java\&gt;&lt;&lt;&lt;
/* XtpipesUni.java (`version), generated from `jobname.tex
   Copyright (C) 2009-2010 TeX Users Group
   Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; */
package xtpipes;
public class XtpipesUni{
   `&lt;String toUni( char[], start, length, filter )`&gt;
   `&lt;String toUni( String, filter )`&gt;
}
&gt;&gt;&gt;

\&lt;String toUni( char[], start, length, filter )\&gt;&lt;&lt;&lt;
private static int D800 = Integer.parseInt("D800", 16);
private static int DFFF = Integer.parseInt("DFFF", 16);
private static int DC00 = Integer.parseInt("DC00", 16);
private static int X400 = Integer.parseInt("400",16);
private static int X10000 = Integer.parseInt("10000",16);


public static String toUni( char[] ch, int start, int length,
                                           String filter ){
   StringBuffer buf = new StringBuffer(length);
   for (int i = 0; i &lt; length; i++) {
       int chr = ch[ start + i ];
       boolean ascii =  (chr == '\n')
                        || (chr &gt; 31) &amp;&amp; (chr &lt; 127) ;
       if( filter.indexOf(chr) &gt; -1 ){ ascii = false; }

       if( (chr &gt;= D800) &amp;&amp; (chr&lt;= DFFF) ){
          chr = ((ch[i] - D800) * X400 + (ch[++i] - DC00)) + X10000;
       }


       buf.append(
         ascii ? Character.toString((char) chr)
               : ("&amp;#x"
                 + Integer.toHexString(chr).toUpperCase()
                 + ";" ) );
   }
   return new String(buf);
}
&gt;&gt;&gt;

\&lt;String toUni( String, filter )\&gt;&lt;&lt;&lt;
public static String toUni( String s, String filter ){
   char [] ch = s.toCharArray();
   int length = ch.length;
   return toUni(ch, 0, length, filter);
}
&gt;&gt;&gt;







%%%%%%%%%%%%%
\subsection{Error Messagesg}
%%%%%%%%%%%%%






\&lt;static void instructionErr(...)\&gt;&lt;&lt;&lt;
private static void instructionErr( Node node, String e, int num )
                                     throws Exception {
   String err = "--- xtpipes error " + num + " --- ";
   if( node != null ){
      err += "At &lt;" + node.getNodeName();
      NamedNodeMap attr = node.getAttributes();
      for(int i=0; i&lt;attr.getLength(); i++){
         Node nd = attr.item(i);
         err += " " +
             nd.getNodeName()  + "=\"" +
             nd.getNodeValue() + "\"" ;
      }
      err += " &gt; : " ;
   }
   err += e;
   `&lt;close ml2xml files`&gt;
   Xtpipes.logWriter.flush();
   if( exceptionErrs ) { throw new Exception( err );  }
   else {
      System.err.println( err );
      System.exit(1);
   }
}
&gt;&gt;&gt;



\&lt;static void instructionErr(...)\&gt;&lt;&lt;&lt;
private static void instructionErr( Node node, String e,
                                StackTraceElement[] st, int num )
                                     throws Exception {
   Xtpipes.logWriter.println(
      "--- xtpipes error " + num + " --- " + e
   );
   for(int i=st.length-1; i&gt;=0; i-- ){
      Xtpipes.logWriter.println( st[i].toString() );
   }
   instructionErr( node, e, num );
}
&gt;&gt;&gt;




\&lt;new ErrorHandler()\&gt;&lt;&lt;&lt;
new ErrorHandler() {
    public void warning(SAXParseException e) throws SAXParseException {
      showSpecifics("warning",e);
    }
    public void error(SAXParseException e) throws SAXParseException {
      showSpecifics("error",e);
    }
    public void fatalError(SAXParseException e) throws SAXParseException {
      showSpecifics("fatal error",e);
    }
    public void showSpecifics(String s, SAXParseException e)
                                                throws SAXParseException {
      String err =   "--- xtpipes " + s + " 24 --- " + e.getSystemId()
                     + " line " + e.getLineNumber()
                     + " col "  + e.getColumnNumber()
                     + " : "    + e.getMessage() ;
      if( exceptionErrs ) { throw new SAXParseException(
                                     err, (org.xml.sax.Locator) null ); }
      else {
         System.err.println( err );
         System.exit(1);
}   } }
&gt;&gt;&gt;





The follower listeners catch errors but their messages are not
delivered through the call to the new exceptions (why?).  The field
errMssg is used so that error 16 will produce the same error messages.

\begin{description}
\item[Catches errors in the XSLT file]



\&lt;transformer factory XSLT error listener\&gt;&lt;&lt;&lt;
new ErrorListener() {
   public void warning(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   public void error(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   public void fatalError(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   void showSpecifics(TransformerException e)
                                               throws  TransformerException{
     String err = e.getMessage() ;
     String loc = e.getLocationAsString();
     if( loc != null ){ err = loc + ": " + err; }
     err = "XSL stylesheet problem: " + err;
     if( errMssg == null ){ errMssg = err; }
     throw new TransformerException(err);
}  }
&gt;&gt;&gt;


\item [Catches errors in the XML file]

\&lt;transformer XML error listener\&gt;&lt;&lt;&lt;
new ErrorListener() {
   public void warning(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   public void error(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   public void fatalError(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   void showSpecifics(TransformerException e)
                                               throws  TransformerException{
     String err = e.getMessage() ;
     String loc = e.getLocationAsString();
     if( loc != null ){ err = loc + ": " + err; }
     if( errMssg == null ){ errMssg = err; }
     err = "XML document prblem: " + err;
     throw new TransformerException(err);
}  }
&gt;&gt;&gt;


\&lt;identity transformer XML error listener\&gt;&lt;&lt;&lt;
new ErrorListener() {
   public void warning(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   public void error(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   public void fatalError(TransformerException e) throws TransformerException {
     showSpecifics(e);
   }
   void showSpecifics(TransformerException e)
                                               throws  TransformerException{
     String err = e.getMessage() ;
     String loc = e.getLocationAsString();
     if( loc != null ){ err = loc + ": " + err; }
     throw new TransformerException(err);
}  }
&gt;&gt;&gt;



\end{description}


\&lt;xtpipes fields\&gt;&lt;&lt;&lt;
public static String errMssg;
&gt;&gt;&gt;

%%%%%%%%%%%%%%%%%%
\section{Serialize Dom}
%%%%%%%%%%%%%%%%%%


\&lt;static String serialize( dom )\&gt;&lt;&lt;&lt;
static String serialize( Node root ){
   if( root.getNodeType() == Node.TEXT_NODE) {
         return root.getNodeValue();
   }
   if( root.getNodeType() == Node.ELEMENT_NODE) {
      String ser = "";
      String tagName = root.getNodeName();
      ser += "&lt;" + tagName;
      `&lt;res += serialize attributes`&gt;
      ser += "\n&gt;";
      `&lt;res += serialize children`&gt;
      ser += "&lt;/" + tagName + "&gt;";
      return ser;
   }
   if( root.getNodeType() == Node.DOCUMENT_NODE) {
      String ser = "";
      `&lt;res += serialize children`&gt;
      return ser;
   }
   if( root == null ){ return "null"; }
   return "";
}
&gt;&gt;&gt;

\&lt;res += serialize children\&gt;&lt;&lt;&lt;
NodeList children = root.getChildNodes();
if(children.getLength() &gt; 0) {
   for(int i = 0; i &lt; children.getLength(); i++) {
      ser += serialize(children.item(i));
}  }
&gt;&gt;&gt;

\&lt;res += serialize attributes\&gt;&lt;&lt;&lt;
NamedNodeMap attributes = root.getAttributes();
for(int i = 0; i &lt; attributes.getLength(); i++) {
   Attr attribute = (Attr) attributes.item(i);
   ser += "\n" + attribute.getName() + "=\""
               + attribute.getValue() + "\" ";
}
&gt;&gt;&gt;




%%%%%%%%%%%%%
\subsection{Clean Xmlns}
%%%%%%%%%%%%%


\&lt;static void cleanXmlns( dom )\&gt;&lt;&lt;&lt;
static ArrayList&lt;String&gt; nsName, nsValue;
static void cleanXmlns( Node root ){
   if( root.getNodeType() == Node.ELEMENT_NODE) {
      int top = nsName.size();
      `&lt;clean xmlns attributes`&gt;
      `&lt;clean xmlns in children`&gt;
       for(int i=nsName.size(); i&gt;top; ){
         i--;
         nsName.remove(i);
         nsValue.remove(i);
       }
   } else if( root.getNodeType() == Node.DOCUMENT_NODE) {
      nsName = new ArrayList&lt;String&gt;();
      nsValue = new ArrayList&lt;String&gt;();
      `&lt;clean xmlns in children`&gt;
      nsName = null;
      nsValue = null;
}  }
&gt;&gt;&gt;



\&lt;clean xmlns in children\&gt;&lt;&lt;&lt;
NodeList children = root.getChildNodes();
if(children.getLength() &gt; 0) {
   for(int i = 0; i &lt; children.getLength(); i++) {
      cleanXmlns(children.item(i));
}  }
&gt;&gt;&gt;

\&lt;clean xmlns attributes\&gt;&lt;&lt;&lt;
ArrayList&lt;Attr&gt; remove = new ArrayList&lt;Attr&gt;();
NamedNodeMap attributes = root.getAttributes();
for(int i = 0; i &lt; attributes.getLength(); i++) {
   Attr attribute = (Attr) attributes.item(i);
   String name = attribute.getName();
   if( name.startsWith("xmlns") ){
     if( (name.length() == 5) || (name.charAt(5) == ':') ){
        String value = attribute.getValue();
        `&lt;bool := xmlns active?`&gt;
        if( bool ){ remove.add(attribute);
        } else { nsName.add(name); nsValue.add(value); }
}  } }
for(int i=remove.size(); i&gt;0; ){
   i--;
  ((Element) root).removeAttributeNode( (Attr) remove.get(i) );
}
remove = null;
&gt;&gt;&gt;

\&lt;bool := xmlns active?\&gt;&lt;&lt;&lt;
boolean bool = false;
for(int k=nsName.size(); k&gt;0; ){
  k--;
  if( ((String) nsName.get(k)) . equals(name) ){
     bool = ((String) nsValue.get(k)) . equals(value);
     break;
} }
&gt;&gt;&gt;

\&lt;xtpipes imports\&gt;&lt;&lt;&lt;
import java.util.ArrayList;
&gt;&gt;&gt;



%%%%%%%%%%%%%%%%%% 
\subsection{Default Script}
%%%%%%%%%%%%%%%%%%

\AtEndDocument{
   \OutputCodE\&lt;xtpipes-default.4xt\&gt;
}
\expandafter\AddFile\BIN{xtpipes-default.4xt}{xtpipes\Slash lib}

\&lt;xtpipes-default.4xt\&gt;&lt;&lt;&lt;
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
&lt;!DOCTYPE xtpipes PUBLIC "-//GURARI//DTD xtpipes//EN" "xtpipes.dtd"  &gt;
&lt;!-- xtpipes-default.4xt (`version), generated from `jobname.tex
     Copyright (C) 2009-2010 TeX Users Group
     Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; --&gt;
&lt;xtpipes /&gt;
&gt;&gt;&gt;












%%%%%%%%%%%%%%%%%%
\part{Useful Pre Fabricated Modules}
%%%%%%%%%%%%%%%%%%




%%%%%%%%%%%%%
\section{ScriptsManager: A Content Handler}
%%%%%%%%%%%%%

\label{ScriptsManager}


%%%%%%%%%%%%% 
\subsection{Outline}
%%%%%%%%%%%%%

\AtEndDocument{
   \OutputCodE\&lt;ScriptsManager.java\&gt;
}
\AddFile{ScriptsManager.java}{xtpipes\Slash util}

\&lt;ScriptsManager.java\&gt;&lt;&lt;&lt;
/* ScriptsManager.java (`version), generated from `jobname.tex
   Copyright (C) 2009-2010 TeX Users Group
   Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; */
package xtpipes.util;
`&lt;ScriptsManager imports`&gt;
public class ScriptsManager extends DefaultHandler {
     `&lt;ScriptsManager fields`&gt;
     PrintWriter out = null, log = null;
     HashMap&lt;String,Object&gt; scripts = null;
     Method method = null;
     boolean savemode=false;
     String code="", match = null;
     Stack&lt;Object[]&gt; stack = new Stack&lt;Object[]&gt;();
   public ScriptsManager( PrintWriter out,
                          HashMap&lt;String,Object&gt; scripts,
                          Method method,
                          PrintWriter log, boolean trace ){
     this.out = out;
     this.log = (log==null)? new PrintWriter( System.err ) : log;
     this.scripts = scripts;
     this.method = method;
   }
   public void characters(char[] ch, int start, int length){
     add( XtpipesUni.toUni(ch, start, length, "&lt;&gt;&amp;") );
   }
   `&lt;ScriptsManager: void startElement(ns, sName, qName, atts)`&gt;
   `&lt;ScriptsManager: void endElement(ns, sName, qName)`&gt;
   protected void add(String s){
      if( savemode ){ code+=s; }
      else { out.print(s); }
}  }
&gt;&gt;&gt;


\&lt;ScriptsManager imports\&gt;&lt;&lt;&lt;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Stack;
&gt;&gt;&gt;

%%%%%%%%%%%%%
\subsection{Start Elements}
%%%%%%%%%%%%%




\&lt;ScriptsManager: void startElement(ns, sName, qName, atts)\&gt;&lt;&lt;&lt;
public void startElement(String ns, String sName,
                        String qName, Attributes atts) {
   `&lt;save status of xmlns above element`&gt;
   `&lt;flag := start new save?`&gt;
   inBody = true;
   String s =  "&lt;" + qName + "\n";
   for(int i=0; i&lt;atts.getLength(); i++ ){
      String name = atts.getQName(i),
             value = atts.getValue(i);
      `&lt;record xmlns`&gt;
      s += " " + name + "=\"" +
         XtpipesUni.toUni(value, "&lt;&gt;&amp;\"") + "\"";
   }
   if( flag ){ `&lt;add missing xmlns attributes`&gt; }
   s += "&gt;" ;
   `&lt;set start element`&gt;
}
&gt;&gt;&gt;


\&lt;ScriptsManager fields\&gt;&lt;&lt;&lt;
boolean inBody = false;
&gt;&gt;&gt;


\&lt;flag := start new save?\&gt;&lt;&lt;&lt;
String key = (atts==null)?
               null
             : (qName + "::" + atts.getValue("class"));
boolean flag = (key != null) &amp;&amp; scripts.containsKey(key);

if( !flag ){
   key = qName;
   flag = scripts.containsKey(key);
}
&gt;&gt;&gt;

\&lt;set start element\&gt;&lt;&lt;&lt;
if( flag ){
   Object [] state = { Boolean.valueOf(savemode), code, match };
   stack.push( state );
   savemode=true; code=""; match= key;
} else {
   Object [] state = { Boolean.valueOf(savemode), null, null };
   stack.push( state );
}
add( s );
&gt;&gt;&gt;

The parsing of an XML string is similar to that of done by a
left-to-right bottom up parser of a programming language.
Specifically, the token are read and send on to the output stream,
until an element whose name appears in the hash table of scripts is
encountered.  When such an element is encountered, its body is
assembled and the corresponding script is applied on the body.  The
processing might be recursive, in the sense that enclosed elements
might also have scripts to process them.

The above applies also to an element name concatenated with its class
attribute value, with the substring `::' as a separator.

%%%%%%%%%%%%%
\subsection{End Elements}
%%%%%%%%%%%%%



\&lt;ScriptsManager: void endElement(ns, sName, qName)\&gt;&lt;&lt;&lt;
public void endElement(String ns, String sName, String qName){
   String s = "&lt;/" + qName + "&gt;";
   add( s );
   Object [] state = (Object []) stack.pop();
   if( (String) state[1] != null ){
     `&lt;s := invoke script`&gt;
     `&lt;set end element`&gt;
     `&lt;recall status of xmlns above element`&gt;
     if( !s.equals("") ){
       `&lt;remove xmlns attributes supported from above`&gt;
       add( s );
     }
   } else { `&lt;recall status of xmlns above element`&gt; }
}
&gt;&gt;&gt;







\&lt;s := invoke script\&gt;&lt;&lt;&lt;
Object parmValues[] = new Object[2];
parmValues[0] = scripts.get( match );
parmValues[1] = code;
try {
  s = (String) method.invoke( null, parmValues );
} catch(java.lang.reflect.InvocationTargetException e){
   log.println("--- ScriptsManager Error 1 --- " + e.getCause() );
   log.flush();
} catch (Exception e){
   log.println("--- ScriptsManager Error 2 --- " + e );
   log.flush();
}
&gt;&gt;&gt;


Can't invoke exception above.

\&lt;set end element\&gt;&lt;&lt;&lt;
savemode = ((Boolean) state[0]).booleanValue();
code = (String) state[1];
match = (String) state[2];
&gt;&gt;&gt;




%%%%%%%%%%%%%
\subsection{Name Spaces at Start of Elements}
%%%%%%%%%%%%%

\&lt;record xmlns\&gt;&lt;&lt;&lt;
if( name.startsWith("xmlns") ){
  if( (name.length() == 5) || (name.charAt(5) == ':') ){
     `&lt;bool := xmlns active?`&gt;
     if( !bool ){
        nsName.add(name); nsValue.add(value);
} }  }
&gt;&gt;&gt;





\&lt;add missing xmlns attributes\&gt;&lt;&lt;&lt;
HashSet&lt;String&gt; registry = new HashSet&lt;String&gt;();
for(int i=nsName.size(); i&gt;top; ){
  i--;
  registry.add( (String) nsName.get(i) );
}
for(int i=top; i&gt;0; ){
  i--;
  String nm = (String) nsName.get(i);
  if( ! registry.contains(nm) ){
     registry.add( nm );
     s += " " + nm + "=\"" +
         XtpipesUni.toUni( (String) nsValue.get(i), "&lt;&gt;&amp;\"") + "\"";
} }
&gt;&gt;&gt;




\&lt;ScriptsManager fields\&gt;&lt;&lt;&lt;
ArrayList&lt;String&gt; nsName = new ArrayList&lt;String&gt;(),
                         nsValue = new ArrayList&lt;String&gt;();
Stack&lt;Integer&gt; nsStack = new Stack&lt;Integer&gt;();
&gt;&gt;&gt;

\&lt;ScriptsManager imports\&gt;&lt;&lt;&lt;
import java.util.ArrayList;
import java.util.HashSet;
import xtpipes.XtpipesUni;
&gt;&gt;&gt;


%%%%%%%%%%%%%
\subsection{Name Spaces at End of Elements}
%%%%%%%%%%%%%


\&lt;remove xmlns attributes supported from above\&gt;&lt;&lt;&lt;
int m = s.indexOf('&gt;');
char [] attrs = s.substring(0,m).toCharArray();
int result = qName.length()+1,
    mark = result,
    from=-1,
    control = `&lt;xmlns name`&gt;;
char delimiter = ' ';
String name="";
for(int i=result; i&lt;m; i++ ){
  attrs[result++] = attrs[i];
  switch( control ){
    case  `&lt;xmlns name`&gt;: { `&lt;insert attribute name`&gt;  break; }
    case `&lt;xmlns quote`&gt;: { `&lt;insert attribute quote`&gt; break; }
    case `&lt;xmlns value`&gt;: { `&lt;insert attribute value`&gt; break; }
} }
s =  (new String(attrs,0, Math.min(result,attrs.length)))
          + s.substring(m);
&gt;&gt;&gt;



\&lt;insert attribute name\&gt;&lt;&lt;&lt;
if( attrs[i] == '=' ){
   name = (new String(attrs,mark,result-mark-1)).trim();
   control = `&lt;xmlns quote`&gt;;
}
&gt;&gt;&gt;

\&lt;insert attribute quote\&gt;&lt;&lt;&lt;
if( (attrs[i] == '"') || (attrs[i] == '\'') ){
   delimiter = attrs[i];
   control = `&lt;xmlns value`&gt;;
   from = result;
}
&gt;&gt;&gt;

\&lt;insert attribute value\&gt;&lt;&lt;&lt;
if( attrs[i] == delimiter ){
   if( name.startsWith("xmlns")
       &amp;&amp; ((name.length() == 5) || (name.charAt(5) == ':')) ){
      String value = (new String(attrs,from,result-from-1)).trim();
      `&lt;bool := xmlns active?`&gt;
      if( bool ){ result = mark; }
   }
   mark = result;
   control = `&lt;xmlns name`&gt;;
}
&gt;&gt;&gt;



%%%%%%%%%%%%%
\subsection{Name Spaces Inheritence}
%%%%%%%%%%%%%





\&lt;save status of xmlns above element\&gt;&lt;&lt;&lt;
int top = nsName.size();
nsStack.push( Integer.valueOf(top) );
&gt;&gt;&gt;

\&lt;recall status of xmlns above element\&gt;&lt;&lt;&lt;
int top = ((Integer) nsStack.pop()) . intValue();
for(int i=nsName.size(); i&gt;top; ){
  i--;
  nsName.remove(i);
  nsValue.remove(i);
}
&gt;&gt;&gt;





\OP{xmlns name}
\OP{xmlns quote}
\OP{xmlns value}












%%%%%%%%%%%%%%%%%% 
\section{ScriptsManagerLH: A Lexical Handler}
%%%%%%%%%%%%%%%%%%

\label{ScriptsManagerLH}

The lexical handler sends its strings to the content hadler.

\AtEndDocument{
   \OutputCodE\&lt;ScriptsManagerLH.java\&gt;
}
\AddFile{ScriptsManagerLH.java}{xtpipes\Slash util}

\&lt;ScriptsManagerLH.java\&gt;&lt;&lt;&lt;
/* ScriptsManagerLH.java (`version), generated from `jobname.tex
   Copyright (C) 2009-2010 TeX Users Group
   Copyright (C) `CopyYear.2002. Eitan M. Gurari
`&lt;TeX4ht copyright`&gt; */
package xtpipes.util;
import org.xml.sax.ext.LexicalHandler;
// import org.xml.sax.ContentHandler;
import java.io.PrintWriter;
public class ScriptsManagerLH implements LexicalHandler {
       ScriptsManager contentHandler;
       PrintWriter log;
   public ScriptsManagerLH( ScriptsManager contentHandler,
                          PrintWriter log, boolean trace ){
     this.contentHandler = contentHandler;
     this.log = (log==null)? new PrintWriter( System.err ) : log;
   }
   public void comment(char[] ch, int start, int length){
     if( contentHandler.inBody ){
        String s = new String(ch, start, length);
        contentHandler.add(  "&lt;!--" + s + "\n--&gt;");
   } }
   public void startEntity(String x){}
   public void endEntity(String x){}
   public void startCDATA(){}
   public void endCDATA(){}
   public void startDTD(String x, String y, String z){}
   public void endDTD(){}
}
&gt;&gt;&gt;

\begin{itemize}
\item
The line breaks in the comments are to avoid sequences of comments
loosing their intermediate line breaks and as a result causing
overflow of buffers.

\item The comments in the preamble are included through the
preamble pattribute of xtpipes.
\end{itemize}











%%%%%%%%%%%%%%%%%%%%%%%
\begin{thebibliography}{10}
\bibitem{ref}
{\sl The Reflection API},
Tutorial, Sun Microsystems,
\url{http://java.sun.com/docs/books/tutorial/reflect/TOC.html}.
\end{thebibliography}




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\ifOption{win}
{
     \AtEndDocument{
        \OutputCodE\&lt;dodoc.bat\&gt;
        \Needs{"dodoc"}
     }
}
{ \ifOption{doc}{
  \AtEndDocument{\Needs{"
     mkdir -p doc.dir
     ;
     cd doc.dir
     ;
     java
        -classpath
        ..:../cgjsapi.jar:../../../jldir.dir:../../../jldir.dir/jldoc.jar:../../../ml2xml.dir/ml2xml.dir/bin/ml2xml.jar
        jldoc.Jldoc
        -title "Xtpipes APIs"
        ../work.dir
     ;
     cd ..
     ;
     /usr/bin/rm -r doc.dir
  "}}}{}
}




\&lt;dodoc.bat\&gt;&lt;&lt;&lt;
cd work.dir
if NOT EXIST bin mkdir bin
 javac -Xlint:unchecked  -d bin  xtpipes/*.java
 javac -Xlint:unchecked  -d bin  xtpipes/util/*.java
 javac -Xlint:unchecked  -d bin  *.java
cd bin
 jar cf xtpipes.jar *
cd ..
cd xtpipes
if NOT EXIST bin mkdir bin
 move ..\bin\xtpipes.jar bin\.
cd ..
cd ..
&gt;&gt;&gt;

\ifOption{win}{
\immediate\write16{......... work.dir\string \xtpipes\string \lib\string \*}
\immediate\write16{......... work.dir\string \xtpipes\string \bin\string \xtpipes.jar}
}{}


\ifOption{doc}{\let\DOC\def}{}



\ifx\DOC\def
%%%%%%%%%%%%%%%%%%%%%%%
\&lt;dodoc.bat\&gt;&lt;&lt;&lt;
if NOT EXIST doc.dir mkdir doc.dir
cd doc.dir
java -classpath ../../jldoc.dir;../../jldoc.dir/jldoc.jar;../../ml2xml.dir/ml2xml.dir/bin/ml2xml.jar jldoc.Jldoc -title "Xtpipes APIs"  ../work.dir/xtpipes
cd ..
rmdir /s /q doc.dir
&gt;&gt;&gt;
%%%%%%%%%%%%%%%

\fi
\




../../..;..;../../jldoc;../../xtpipes/cgjsapi.jar;../../xtpipes/xtpipes.jar;../../jldoc/jldoc.jar;../../ml2xml.dir/ml2xml.dir/bin/ml2xml.jar

\ifdojava
\ifOption{win} {}{
\AtEndDocument{\Needs{%
    "pushd \XTPIPES || exit 1
     ;
     jar cf xtpipes.jar *
     ;
     popd
     ;
     mkdir -p \LIB || exit 1
     ;
     mv \XTPIPES xtpipes.jar \LIB
     ;
     mkdir -p \HOME texmf/tex4ht/xtpipes/. || exit 1
     ;
     cp \XTPIPES xtpipes/lib/*
        \HOME texmf/tex4ht/xtpipes/.
"}}
}
\fi



\ifdojava
\ifOption{win} {}{
  \AtEndDocument{\Needs{"
      mkdir -p \LIB\space || exit 1
      ;
      find \WORK\space -type f -iname '*.java' -print0
      | xargs -0 javac -d \XTPIPES\space -sourcepath \WORK
      ;
      pushd \XTPIPES || exit 1
      ;
      jar cf xtpipes.jar *
      ;
      popd
      ;
      mv \XTPIPES xtpipes.jar \LIB
      ;
      "}}}
\fi


\end{document}
</pre></body></html>