Debian Codegraph @

texmf-dist/source/generic/tex4ht/xtpipes.tex

raw
1 % $Id: xtpipes.tex 740 2020-06-13 22:35:32Z karl $
2
3 % htlatex xtpipes "xhtml,3,next" "" "-d./"
4 % htlatex xtpipes "xhtml,3,next,doc" "" "-d./"
5 % htlatex xtpipes "xhtml,3,next,win"
6 % htlatex xtpipes "xhtml,3,next,win,doc"
7
8 % generalize -i attribute to accept multiple directories, like for -classpath
9 % gcj support these ``generics'' with a ``-5'' or ``-1.5'' switch
10
11 % Copyright 2009-2020 TeX Users Group
12 % Copyright 1996-2009 Eitan M. Gurari
13 % Released under LPPL 1.3c+.
14 % See tex4ht-cpright.tex for license text.
15
16 \documentclass{article}
17 \usepackage{url}
18 \usepackage{verbatim}
19 \input{common.tex}
20 % make ` be the escape character, instead of |
21 \Configure{ProTex}{java,<<<>>>,title,list,`}
22 \begin{document}
23 \input tex4ht-cpright.tex
24 \input tex4ht-dir.tex
25
26 \def\CNT{0}
27 \bgroup
28 \catcode`\^=7
29 \catcode`\^^M=13 %
30 \gdef\OP#1{%
31 \edef\temp{%
32 \noexpand\<#1\noexpand\><<<
33 \CNT
34 >>> %
35 } \temp %
36 \immediate\write15{...... \CNT\space #1}
37 \HAdvance\CNT by 1 %
38 } %
39 \egroup
40
41 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42 % \AddFile[optional: target file name; default: given file name]
43 % (optional: target home dir; default MYDIR)
44 % {file name}{dir}
45
46 \ifOption{win}
47 {\def\mv{move }}
48 {\def\mv{mv }}
49
50 \def\Slash{/}
51 {
52 \catcode`\/=0
53 \catcode`\\=12
54 /ifOption{win}{/gdef/Slash{\}}{}
55 }
56 \def\SLASH{/}
57
58 \def\AddFile{\futurelet\ext\AddFileA}
59 \def\AddFileA{%
60 \if [\ext \def\ext[##1]{\def\ext{##1}\futurelet\dir\AddFileB}%
61 \else \def\ext{\def\ext{}\futurelet\dir\AddFileB}\fi
62 \ext}
63 \def\AddFileB{%
64 \if (\dir \def\dir(##1){\def\dir{##1}\AddFileC}%
65 \else \def\dir{\let\dir\MYdir\AddFileC}\fi
66 \dir}
67
68
69 \def\AddFileC#1#2{%
70 \expandafter\setStartDir \dir #2!%
71 \bgroup
72 \def\Slash{/}%
73 \xdef\EndDir{\dir
74 #2\Slash
75 \ifx\ext\empty
76 \if !#1!\else #1\fi
77 \else \ext\fi}%
78 \egroup
79 \MakeDir
80 \if !#1!\else
81 \Needs{"\mv #1\space \dir #2\Slash
82 \ifx\ext\empty #1\else \ext\fi"}%
83 \fi
84 }
85
86 \ifOption{win}
87 {
88 \def\MakeDir{\relax
89 \expandafter \ifx \csname !\StartDir\endcsname\relax
90 \expandafter\let\csname !\StartDir\endcsname=\empty
91 \Needs{"if NOT EXIST \StartDir \space mkdir -p \StartDir"}%
92 \fi
93 \ifx \EndDir\empty \else
94 \expandafter\AppendDir \EndDir////*%
95 \expandafter\MakeDir
96 \fi
97 }
98 }{
99 \def\MakeDir{\relax
100 \expandafter \ifx \csname !\StartDir\endcsname\relax
101 \expandafter\let\csname !\StartDir\endcsname=\empty
102 \Needs{"mkdir -p \StartDir"}%
103 \fi
104 \ifx \EndDir\empty \else
105 \expandafter\AppendDir \EndDir////*%
106 \expandafter\MakeDir
107 \fi
108 }
109 }
110
111 \def\AppendDir#1/#2/#3/*{%
112 \def\temp{#2}\ifx \temp\empty
113 \let\EndDir=\empty
114 \else
115 \edef\StartDir{\ifx \StartDir\empty\else
116 \ifx \StartDir\SLASH \Slash \else
117 \StartDir\Slash\fi \fi
118 #1}%
119 \def\EndDir{#2/#3}%
120 \expandafter\MakeDir
121 \fi
122 }
123 \def\setStartDir#1#2!{%
124 \def\StartDir{#1}\ifx\StartDir\SLASH\else
125 \def\StartDir{}\fi
126 }
127
128
129
130 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
131 % % \AddFile[optional: target file name; default: given file name]
132 % % (optional: target home dir; default MYDIR)
133 % % {file name}{dir}
134 %
135 % \def\AddFile{\futurelet\ext\AddFileA}
136 % \def\AddFileA{%
137 % \if [\ext \def\ext[##1]{\def\ext{##1}\futurelet\dir\AddFileB}%
138 % \else \def\ext{\def\ext{}\futurelet\dir\AddFileB}\fi
139 % \ext}
140 % \def\AddFileB{%
141 % \if (\dir \def\dir(##1){\def\dir{##1}\AddFileC}%
142 % \else \def\dir{\let\dir\MYdir\AddFileC}\fi
143 % \dir}
144 % \def\AddFileC#1#2{%
145 % \expandafter\setStartDir \dir #2!%
146 % \edef\EndDir{\ifx \dir\empty \else \dir/\fi
147 % #2/\ifx\ext\empty \if !#1!XXX\else #1\fi\else \ext\fi}\MakeDir
148 % \if !#1!\else
149 % \Needs{"mv #1\space \dir /#2/\ifx\ext\empty #1\else \ext\fi"}%
150 % \fi
151 % }
152 % \def\MakeDir{\relax
153 % \expandafter \ifx \csname !\StartDir\endcsname\relax
154 % \expandafter\let\csname !\StartDir\endcsname=\empty
155 % \Needs{"mkdir -p \StartDir"}%
156 % \fi
157 % \ifx \EndDir\empty \else
158 % \expandafter\AppendDir \EndDir////*%
159 % \expandafter\MakeDir
160 % \fi
161 % }
162 % \def\AppendDir#1/#2/#3/*{%
163 % \def\temp{#2}\ifx \temp\empty \let\EndDir=\empty
164 % \else
165 % \edef\StartDir{\ifx \StartDir\empty\else
166 % \ifx \StartDir\SLASH /\else
167 % \StartDir/\fi \fi
168 % #1}\def\EndDir{#2/#3}%
169 % \fi
170 % }
171 % \def\setStartDir#1#2!{%
172 % \def\StartDir{#1}\ifx\StartDir\SLASH\else
173 % \def\StartDir{}\fi
174 % }
175 % \def\SLASH{/}
176
177
178 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
179
180 % TODO : make \WORK MSDOS / Linux agnostic.
181 \def\MYdir{\WORK}
182
183
184 \expandafter\let\csname !/\endcsname\empty
185 \expandafter\let\csname !/\endcsname\empty
186 \expandafter\let\csname !/home\endcsname\empty
187 \expandafter\let\csname !/home/4\endcsname\empty
188 \expandafter\let\csname !/home/4/gurari\endcsname\empty
189 \expandafter\let\csname !/home/4/gurari/xtpipes.dir\endcsname\empty
190 %\expandafter\let\csname !/home/4/gurari/tex4ht.dir/texmf\endcsname\empty
191 %\expandafter\let\csname !/home/4/gurari/xtpipes.dir\endcsname\empty
192
193 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
194
195
196
197
198
199
200
201
202
203 %%%%%%%%%%%%%%%%%%
204 \part{Core}
205 %%%%%%%%%%%%%%%%%%
206
207
208 %%%%%%%%%%%%%%%%%%
209 \section{Control}
210 %%%%%%%%%%%%%%%%%%
211
212
213 %%%%%%%%%%%%%%%%%%
214 \subsection{Outline}
215 %%%%%%%%%%%%%%%%%%
216
217
218 \AtEndDocument{
219 \OutputCode[java]\<xtpipes.java\> % double .java to avoid problems on MS
220 \OutputCodE\<Xtpipes.java\>
221 \OutputCodE\<xtpipes.dtd\>
222 }
223
224 % \Needs{"
225 % mkdir -p work.dir
226 % ;
227 % mkdir -p work.dir/xtpipes
228 % "}
229
230 \ifdojava
231 \ifOption{win} {}{
232 \AtEndDocument{\Needs{"
233 find \WORK\space -type f -iname '*.java' -print0
234 | xargs -0 javac -d \XTPIPES\space -sourcepath \WORK
235 ;
236 "}}
237 }
238 \fi
239
240
241 \ifOption{win} {
242 \def\BIN{}
243 }{
244 \def\BIN{(\XTPIPES)}
245 }
246
247 %
248 \expandafter\AddFile\BIN{xtpipes.dtd}{xtpipes\Slash lib}
249
250 \AddFile{Xtpipes.java}{xtpipes}
251
252 \<Xtpipes.java\><<<
253 package xtpipes;
254 /* Xtpipes.java (`version), generated from `jobname.tex
255 Copyright (C) 2009-2010 TeX Users Group
256 Copyright (C) `CopyYear.2002. Eitan M. Gurari
257 `<TeX4ht copyright`> */
258 `<xtpipes imports`>
259 `<class XtpipesPrintWriter `>
260 public class Xtpipes {
261 `<xtpipes fields`>
262 `<static void main(String [])`>
263 `<static void xtpipes(String [], OutputStream, PrintWriter)`>
264 `<static void xtpipes(String [], OutputStreamWriter, PrintWriter)`>
265 `<static void xtpipes(String [], XtpipesPrintWriter, PrintWriter)`>
266 `<static Document getDOM(...)`>
267 `<static void mainMethod(String [])`>
268 `<static void execute( node )`>
269 `<static String execute( node, xml )`>
270 `<static void instructionErr(...)`>
271 `<static String serialize( dom )`>
272 `<static void cleanXmlns( dom )`>
273 }
274 `<class XtpipesEntityResolver`>
275 >>>
276
277 \Needs{"\mv xtpipes.java.java \MYdir xtpipes.java"}
278
279 NOTE: We can not place Xtpipes.class and xtpipes.class at the same
280 directory because MS Windows get confused between the two.
281
282
283 \<xtpipes.java\><<<
284 /* xtpipes.java (`version), generated from `jobname.tex
285 Copyright (C) 2009-2010 TeX Users Group
286 Copyright (C) `CopyYear.2002. Eitan M. Gurari
287 `<TeX4ht copyright`> */
288 import xtpipes.*;
289 public class xtpipes {
290 public static void main(String [] args) throws Exception {
291 Xtpipes.main(args);
292 } }
293 >>>
294
295
296 \<static String execute( node, xml )\><<<
297 public static String execute( Node node, String xml )
298 throws Exception {
299 String name = ".";
300 String old = (String) map.get(name);
301 map.put( name, (Object) xml );
302 execute( node.getFirstChild() );
303 String s = (String) map.get(name);
304 if( old != null ){ map.put( name, (Object) old ); }
305 return s;
306 }
307 >>>
308
309
310
311
312
313
314
315 \<xtpipes fields\><<<
316 private static HashMap <String,Object> map;
317 private static boolean needScript;
318 >>>
319
320
321 The members of xtpipes need to be initiated each time the methods of
322 the program are invoked from external point. That can happen multiple
323 times for a given run. Hence, the fields are not initiated in the
324 declaration points, but within the main method. All the external
325 calls go directly or indirectly through that method.
326
327
328 \<init fields\><<<
329 map = new HashMap <String,Object> ();
330 needScript = true;
331 >>>
332
333
334 \<xtpipes imports\><<<
335 // import xtpipes.util.InputObject;
336 // import xtpipes.util.FileInfo;
337 import xtpipes.XtpipesPrintWriter;
338 import java.net.URLConnection;
339 import java.io.*;
340 import java.lang.reflect.*;
341 import java.util.HashMap;
342 import java.util.Stack;
343 import javax.xml.parsers.*;
344 import javax.xml.transform.*;
345 import javax.xml.transform.dom.DOMSource;
346 import javax.xml.transform.stream.*;
347 import org.w3c.dom.*;
348 import org.xml.sax.*;
349 import org.xml.sax.helpers.*;
350 import java.net.URL;
351 >>>
352
353 %%%%%%%%%%%%%
354 \subsection{Invocation Interfaces}
355 %%%%%%%%%%%%%
356
357 \<static void main(String [])\><<<
358 public static void main(String args[]) throws Exception {
359 `<init fields`>
360 mainMethod(args);
361 }
362 >>>
363
364
365
366
367 \<static void xtpipes(String [], OutputStream, PrintWriter)\><<<
368 public static void xtpipes(String [] args,
369 OutputStream out,
370 PrintWriter log)
371 throws Exception {
372 `<init fields`>
373 outPrintWriter = new XtpipesPrintWriter( out, true );
374 logWriter = (log==null)? (new PrintWriter( System.err )) : log;
375 mainMethod(args);
376 outPrintWriter.flush();
377 }
378 >>>
379
380
381
382 \<static void xtpipes(String [], OutputStreamWriter, PrintWriter)\><<<
383 public static void xtpipes(String [] args,
384 OutputStreamWriter out,
385 PrintWriter log)
386 throws Exception {
387 `<init fields`>
388 outPrintWriter = new XtpipesPrintWriter( out );
389 logWriter = (log==null)? (new PrintWriter( System.err )) : log;
390 mainMethod(args);
391 outPrintWriter.flush();
392 }
393 >>>
394
395 \<static void xtpipes(String [], XtpipesPrintWriter, PrintWriter)\><<<
396 public static void xtpipes(String [] args,
397 XtpipesPrintWriter out,
398 PrintWriter log)
399 throws Exception {
400 `<init fields`>
401 outPrintWriter = out;
402 logWriter = (log==null)? (new PrintWriter( System.err )) : log;
403 mainMethod(args);
404 outPrintWriter.flush();
405 }
406 >>>
407
408
409 \<xtpipes fields\><<<
410 private static boolean returnDom;
411 private static String result;
412 >>>
413
414 \<init fields\><<<
415 returnDom = false;
416 result = null;
417 >>>
418
419
420 \<static Document getDOM(...)\><<<
421 public static Document getDOM(String args[])
422 throws Exception {
423 `<init fields`>
424 returnDom = true;
425 mainMethod(args);
426 Document dom = null;
427 if( result == null ){
428 System.err.println(
429 "--- xtpipes warning --- getDOM without <return name=\"...\"> from 4xt file: "
430 + scriptFile );
431 } else {
432 try{
433 byte [] bytes = result.getBytes("UTF-8");
434 InputStream is = new ByteArrayInputStream( bytes );
435 dom = domBuilder.parse (is);
436 } catch ( org.xml.sax.SAXParseException e ){
437 if( Xtpipes.trace ){
438 Xtpipes.logWriter.println(
439 "\n---------------------------------------------------\n"
440 + result +
441 "\n---------------------------------------------------\n" );
442 }
443 String s = "";
444 `<s += input file name within args`>
445 if( scriptFile != null ){ s += " script file: " + scriptFile; }
446 instructionErr( null,
447 "parsing error: " + e.getMessage() +s, 21 );
448 } catch ( Exception e ){
449 instructionErr( null, e.toString(), 5 );
450 }
451 `<close ml2xml files`>
452 }
453 return dom;
454 }
455 >>>
456
457 \<static Document getDOM(...)\><<<
458 public static Document getDOM(String s, String args[])
459 throws Exception {
460 `<init fields`>
461 returnDom = true;
462 inData = s;
463 mainMethod(args);
464 Document dom = null;
465 if( result == null ){
466 System.err.println(
467 "--- xtpipes warning --- getDOM without"
468 + " <return name=\"...\"> from 4xt file: "
469 + scriptFile );
470 } else {
471 try{
472 byte [] bytes = result.getBytes("UTF-8");
473 InputStream is = new ByteArrayInputStream( bytes );
474 dom = domBuilder.parse (is);
475 } catch ( org.xml.sax.SAXParseException e ){
476 instructionErr( null, "improper xml: " + e.getMessage()
477 + "\n code starts with: "
478 + result.substring(0, Math.min(100,result.length()))
479 , 17 );
480 } catch ( Exception e ){
481 instructionErr( null, e.toString(), 6 );
482 }
483 `<close ml2xml files`>
484 }
485 return dom;
486 }
487 >>>
488
489
490 \<static Document getDOM(...)\><<<
491 public static Document getDOM(String args[], PrintWriter log)
492 throws Exception {
493 logWriter = (log==null)? new PrintWriter( System.err ) : log;
494 return getDOM(args);
495 }
496 >>>
497
498 \<static Document getDOM(...)\><<<
499 public static Document getDOM(String s, String args[], PrintWriter log)
500 throws Exception {
501 logWriter = (log==null)? (new PrintWriter( System.err )) : log;
502 return getDOM(s, args);
503 }
504 >>>
505
506
507
508
509 \<xtpipes fields\><<<
510 static PrintWriter logWriter = new PrintWriter( System.err );
511 >>>
512
513
514
515
516 %%%%%%%%%%%%%
517 \subsection{Core Entry Code}
518 %%%%%%%%%%%%%
519 g
520
521 \<static void mainMethod(String [])\><<<
522 private static void mainMethod(String args[]) throws Exception {
523 try{
524 `<command line vars`>
525 `<process command line`>
526 } catch (Exception e){
527 instructionErr( null, e.getMessage(), e.getStackTrace(), 31 );
528 }
529 try {
530 DocumentBuilderFactory domFactory =
531 DocumentBuilderFactory.newInstance();
532 domFactory.setValidating(true);
533 DocumentBuilder validatingDomBuilder =
534 domFactory.newDocumentBuilder();
535 validatingDomBuilder.setEntityResolver(`<new EntityResolver()`>);
536 validatingDomBuilder.setErrorHandler(`<new ErrorHandler()`>);
537 `<xtpipes initialization`>
538 `<scriptFile := entry script file name`>
539 while( needScript ){
540 if( scriptFile == null ){
541 instructionErr( null, "Missing 4xt script file name", 32 );
542 }
543 `<search script file`>
544 Document script = validatingDomBuilder.parse(scriptFile);
545 `<trace open script`>
546 execute( script.getFirstChild() );
547 }
548 `<close output file`>
549 Xtpipes.logWriter.flush();
550 } catch( org.xml.sax.SAXParseException e ){
551 String s = "Improper file " + scriptFile + ": " + e.getMessage();
552 instructionErr( null, s, 2 );
553 } catch( java.io.FileNotFoundException e ){
554 String s;
555 if( scriptFile.equals( e.getMessage() ) ){
556 s = "Could not find file: " + scriptFile;
557 } else {
558 s = "Problem at script " + scriptFile + ": Could not find file "
559 + e.getMessage();
560 }
561 instructionErr( null, s, 3 );
562 } catch( Exception e ){
563 String s = "Problems at file: " + scriptFile + "\n " + e;
564 instructionErr( null, s, 4 );
565 } }
566 >>>
567
568
569
570
571
572
573 %%%%%%%%%%%%%
574 \subsection{Locate the Script File}
575 %%%%%%%%%%%%%
576
577
578
579
580 \<search script file\><<<
581 String f = FileInfo.searchFile( scriptFile );
582 if( f == null ){
583 throw new java.io.FileNotFoundException( scriptFile );
584 } else {
585 scriptFile = f;
586 }
587 >>>
588
589
590
591 [\HPage{System Properties}
592
593 \<sys.java\><<<
594 // `version
595 import java.util.*;
596 class sys{
597 public static void main( String [] args ) {
598 java.util.Properties p = System.getProperties();
599 java.util.Enumeration keys = p.keys();
600 while( keys.hasMoreElements() ) {
601 String name = (String) keys.nextElement();
602 String value = System.getProperty( name );
603 logWriter.println( name + " : " + value );
604 } } }
605 >>>
606 \EndHPage{}]
607
608
609 %%%%%%%%%%%%%
610 \subsection{Flow of Control}
611 %%%%%%%%%%%%%
612
613
614 \<static void execute( node )\><<<
615 private static void execute( Node node ) throws Exception {
616 while( node != null ){
617 if( node.getNodeType()==Node.ELEMENT_NODE ){
618 String instruction = node.getNodeName();
619 `<trace element`>
620 if( instruction.equals( "xtpipes" ) ){
621 `<execute xtpipes`>
622 } else if( instruction.equals( "set" ) ){
623 `<execute set`>
624 } else if( instruction.equals( "get" ) ){
625 `<execute get`>
626 } else if( instruction.equals( "print" ) ){
627 `<execute print`>
628 } else if( instruction.equals( "return" ) ){
629 `<execute return`>
630 } else if( instruction.equals( "if" ) ){
631 `<execute if`>
632 } else if( instruction.equals( "xslt" ) ){
633 `<execute xslt`>
634 } else if( instruction.equals( "dom" ) ){
635 `<execute dom`>
636 } else if( instruction.equals( "sax" ) ){
637 `<execute sax`>
638 } else {
639 instructionErr( node, "Improper instruction: " + instruction, 11 );
640 } }
641 node = node.getNextSibling();
642 } }
643 >>>
644
645
646
647 %%%%%%%%%%%%%
648 \subsection{Comamnd Line Options: Outline}
649 %%%%%%%%%%%%%
650
651
652
653 \<get args[n]\><<<
654 if( args[n] == null ){}
655 else if( args[n].equals("") ){}
656 else if( args[n].charAt(0)!='-' ){ inFile = args[n]; }
657 else if( args[n].equals("-m") ){
658 messages = true;
659 `<output system info`>
660 }
661 else if( args[n].equals("-s") ){
662 `<scan script file name`>
663 }
664 else if( args[n].equals("-S") ){
665 `<scan script map file name`>
666 }
667 else if( args[n].equals("-i") ){
668 `<scan script dir name`>
669 }
670 else if( args[n].equals("-o") ){
671 `<scan output file name`>
672 }
673 else if( args[n].startsWith("-x") ){
674 `<scan ml2xml argument`>
675 }
676 else if( args[n].equals("-E") ){
677 exceptionErrs = true;
678 }
679 else if( args[n].equals("-d") ){
680 `<scan input data`>
681 }
682 else if( args[n].equals("-trace") ){ trace=true; }
683 else if( args[n].equals("-help") ){ help=true; }
684 else { `<improper args[n]`> }
685 >>>
686
687
688 \<display command line syntax\><<<
689 System.err.println( xtpipes_call );
690 >>>
691
692 \<command line vars\><<<
693 String xtpipes_call =
694 " xtpipes (`version)"
695 + "\n Command line options: "
696 + "\n java xtpipes [-trace] [-help] [-m] [-E] [-s script_file]"
697 + " [-S script_map]"
698 + "\n [-i script_dir] [-o out_file] "
699 + "\n [-x...ml2xml_arg...] "
700 + "(-d in_data | in_file)"
701 + "\n -m messages printing mode"
702 + "\n -E error messages into exception calls"
703 + "\n in_data XML data directly into the command line\n"
704 ;
705 >>>
706
707
708
709 At least one `-x' command line option is required for ml2xml
710 to be called. An empty postfix is also fine.
711
712
713
714 \<s += input file name within args\><<<
715 for( int n=0; n<args.length; n++ ){
716 if( args[n].charAt(0)!='-' ){
717 s += " input file: " + args[n] + "."; break;
718 }
719 else if( args[n].equals("-s")
720 || args[n].equals("-S")
721 || args[n].equals("-i")
722 || args[n].equals("-o")
723 || args[n].equals("-d") ){ n++; }
724 }
725 >>>
726
727 %%%%%%%%%%%%%
728 \subsection{Comamnd Line Options: Processing}
729 %%%%%%%%%%%%%
730
731
732
733 \<process command line\><<<
734 boolean help=false;
735 for( int n=0; n<args.length; n++ ){
736 `<get args[n]`>
737 }
738 `<default stdio output`>
739 `<help message and stop on improper args in batch mode`>
740 new FileInfo(logWriter, i_scriptDir, trace);
741 if( inFile != null ){
742 inputObject = new InputObject( inFile, logWriter );
743 if( inputObject.getInputStream() == null ){
744 instructionErr( null, "Could not find or open file: " + inFile, 28 );
745 }
746 inFile = inputObject.getFilename();
747 } else {
748 inputObject = new InputObject( inData.getBytes("UTF-8"), logWriter );
749 }
750 inputObject.buildProfile( trace );
751 >>>
752
753 \<help message and stop on improper args in batch mode\><<<
754 if( !returnDom ){
755 if( help || ((inFile == null) && (inData == null)) ){
756 `<display command line syntax`>
757 if( (inFile == null) && (inData == null) ){
758 System.exit(0);
759 } } }
760 >>>
761
762 \<improper args[n]\><<<
763 if( !exceptionErrs ){
764 for(int i=n+1; i<args.length; i++ ){
765 if( args[i].equals("-E") ){ exceptionErrs = true; }
766 } }
767 instructionErr( null,
768 "Improper argument: " + args[n] + "\n" + xtpipes_call, 26 );
769 >>>
770
771
772
773
774 \<scan input data\><<<
775 n++;
776 if( n < args.length ){
777 inData = args[n];
778 } else {
779 System.err.println(
780 "--- Error --- Missing field for -d argument" );
781 inFile = null; inData = null; break;
782 }
783 >>>
784
785
786
787
788
789
790 \<xtpipes fields\><<<
791 private static String inFile,
792 inData;
793 private static boolean exceptionErrs, messages;
794 public static InputObject inputObject;
795 >>>
796
797
798 \<init fields\><<<
799 inFile = null;
800 inData = null;
801 exceptionErrs = false;
802 messages = false;
803 >>>
804
805
806 %%%%%%%%%%%%%
807 \subsection{Output File}
808 %%%%%%%%%%%%%
809
810
811 The output file name mentioned in the input command line `-o file.out' is
812 employed in the following cases.
813
814 \begin{itemize}
815 \item
816 Within sax commands without `name' argument
817
818 \item Within the return instruction, if none of the sax commands wrote
819 into the file. The returnToFile field is used for book keeping of
820 whether a sax command used the file earlier for an output target.
821
822
823 NOTE: check the case of `cond copy input preamble' ??
824 \end{itemize}
825
826
827 \<scan output file name\><<<
828 n++;
829 if( n < args.length ){
830 outFileName = args[n];
831 } else {
832 System.err.println(
833 "--- Error --- Missing field for -o argument" );
834 inFile = null; inData = null; break;
835 }
836 >>>
837
838
839 \<xtpipes fields\><<<
840 private static String outFileName;
841 private static PrintWriter outPrintWriter;
842 private static boolean returnToFile = false;
843 >>>
844
845 \<init fields\><<<
846 outFileName = null;
847 outPrintWriter = null;
848 >>>
849
850
851
852 \<open output file\><<<
853 if( outFileName != null ){
854 try {
855 FileWriter fw = new FileWriter( outFileName );
856 outPrintWriter = new XtpipesPrintWriter( fw );
857 returnToFile = true;
858 } catch(Exception e){
859 instructionErr( null, e.toString(), 12 );
860 } }
861 >>>
862
863 \<close output file\><<<
864 if( outFileName != null ){
865 outPrintWriter.close();
866 }
867 >>>
868
869 \<default stdio output\><<<
870 if( outPrintWriter == null ){
871 outPrintWriter = new XtpipesPrintWriter(System.out,true);
872 }
873 >>>
874
875 %
876 \AtEndDocument{
877 \OutputCodE\<XtpipesPrintWriter.java\>
878 }
879 \AddFile{XtpipesPrintWriter.java}{xtpipes}
880
881 \<XtpipesPrintWriter.java\><<<
882 package xtpipes;
883 /* XtpipesPrintWriter.java (`version), generated from `jobname.tex
884 Copyright (C) 2009-2010 TeX Users Group
885 Copyright (C) `CopyYear.2002. Eitan M. Gurari
886 `<TeX4ht copyright`> */
887 import java.io.*;
888 public class XtpipesPrintWriter extends PrintWriter {
889 public XtpipesPrintWriter() {
890 super(System.out, true);
891 }
892 public XtpipesPrintWriter (PrintStream ps, boolean b){
893 super(ps, b);
894 }
895 public XtpipesPrintWriter (OutputStream ps, boolean b){
896 super(ps, b);
897 }
898 public XtpipesPrintWriter (FileWriter fw){
899 super(fw);
900 }
901 public XtpipesPrintWriter (Writer wr){
902 super(wr);
903 }
904 public void print(String str) {
905 super.print( XtpipesUni.toUni(str, "") );
906 }
907 public void println(String str) {
908 super.println( XtpipesUni.toUni(str, "") );
909 } }
910 >>>
911
912
913
914
915
916 %%%%%%%%%%%%%%%%%%
917 \section{The xtpipes Script}
918 %%%%%%%%%%%%%%%%%%
919
920
921 The translation of a file is driven by a script that determines the
922 transformations to be applied to the diffrent fragments of the input
923 data. The name of the script may be found in different locations.
924
925 \begin{itemize}
926 \item
927 A xtpipes processing instruction within the input
928 \item
929 Command line option `-s'
930 \item
931 A .map file that checks the data characteristics to determine the
932 script. Currently available only to input files, not to input strings.
933 \end{itemize}
934
935
936
937 %%%%%%%%%%%%%
938 \subsection{Command Line Options}
939 %%%%%%%%%%%%%
940
941
942 A script should satisfy the rules of `xtpipes.dtd',
943 and a map should satisfy the rules of `xtpipes-map.dtd'.
944
945
946
947
948 \<scan script file name\><<<
949 n++;
950 if( n < args.length ){ scriptFile=args[n]; }
951 else {
952 System.err.println(
953 "--- Error --- Missing field for -s argument" );
954 inFile = null; inData = null; break;
955 }
956 >>>
957
958
959 \<scan script map file name\><<<
960 n++;
961 if( n < args.length ){ scriptMap=args[n]; }
962 else {
963 System.err.println(
964 "--- Error --- Missing field for -S argument" );
965 inFile = null; inData = null; break;
966 }
967 >>>
968
969
970 \<scan script dir name\><<<
971 n++;
972 if( n < args.length ){
973 i_scriptDir=args[n];
974 } else {
975 System.err.println(
976 "--- Error --- Missing field for -i argument" );
977 inFile = null; inData = null; break;
978 }
979 >>>
980
981
982
983
984 \<xtpipes fields\><<<
985 public static String scriptFile;
986 private static String scriptMap;
987 static String i_scriptDir;
988 >>>
989
990
991 \<init fields\><<<
992 scriptFile = null;
993 i_scriptDir = null;
994 scriptMap = null;
995 >>>
996
997
998
999
1000 %%%%%%%%%%%%%
1001 \subsection{Getting the Start Up Script}
1002 %%%%%%%%%%%%%
1003
1004 The command line arguments may provide a pointer to
1005 a `scriptFile' and a pointer to an algorithm `scriptMap'
1006 for getting the script file name.
1007
1008 With and without ml2xml
1009
1010 \<scriptFile := entry script file name\><<<
1011 if( scriptMap != null ){
1012 try{
1013 String f = FileInfo.searchFile( scriptMap );
1014 if( f == null ){
1015 throw new java.io.FileNotFoundException( scriptMap );
1016 } else {
1017 scriptMap = f;
1018 }
1019 `<get sax reader`>
1020 saxReader.setContentHandler( new DefaultHandler(){
1021 `<process script map`>
1022 } );
1023 InputStream inputStream =
1024 (InputStream) (new File(scriptMap).toURI().toURL().openStream());
1025 saxReader.parse( new InputSource(inputStream) );
1026 saxReaderStack.push( saxReader );
1027 } catch( java.io.FileNotFoundException e ){
1028 instructionErr( null,
1029 "File not found: " + e.getMessage()
1030 + "; command line option -i",
1031 33 );
1032 } catch( Exception e ){
1033 instructionErr( null, e.toString(), e.getStackTrace(), 27 );
1034 }
1035 }
1036 if( scriptFile == null ){
1037 scriptFile = "xtpipes-default.4xt";
1038 }
1039 >>>
1040
1041
1042 \<process script map\><<<
1043 private Stack <Boolean> condition = new Stack <Boolean> ();
1044 >>>
1045
1046 \<process script map\><<<
1047 public void startDocument () {
1048 condition.push( Boolean.valueOf(true) );
1049 }
1050 >>>
1051
1052 \<process script map\><<<
1053 public void startElement(String ns, String sName,
1054 String qName, Attributes atts) {
1055 if( condition == null ){ return; }
1056 `<trace start map element`>
1057 boolean cond = ((Boolean) condition.peek()).booleanValue();
1058 if( qName.equals("when") ){
1059 if( cond ){ `<cond := when ...`> }
1060 }
1061 else
1062 if( qName.equals("command-line") ){
1063 if( scriptFile != null ){
1064 `<trace found script in map`>
1065 condition = null;
1066 return;
1067 } }
1068 else
1069 if( qName.equals("processing-instruction") ){
1070 if( cond ){
1071 String s = inputObject.getXtpipes();
1072 if( s != null ){
1073 Xtpipes.scriptFile = s;
1074 `<trace found script in map`>
1075 condition = null;
1076 return;
1077 } } }
1078 else
1079 if( qName.equals("select") ){
1080 if( cond ){
1081 Xtpipes.scriptFile = atts.getValue("name");
1082 `<trace found script in map`>
1083 condition = null;
1084 return;
1085 } }
1086 condition.push( Boolean.valueOf(cond) );
1087 }
1088 >>>
1089
1090
1091
1092
1093 \<process script map\><<<
1094 public void endElement(String ns, String sName, String qName) {
1095 if( condition == null ){ return; }
1096 `<trace end map element`>
1097 condition.pop();
1098 }
1099 >>>
1100
1101
1102
1103 \<cond := when ...\><<<
1104 String name = atts.getValue("name");
1105 String value = atts.getValue("value");
1106 if( name.equals("system-id") ){
1107 cond = value.equals(inputObject.getSystemId());
1108 }
1109 else
1110 if( name.equals("public-id") ){
1111 cond = value.equals(inputObject.getPublicId());
1112 }
1113 else
1114 if( name.equals("dtd-root") ){
1115 cond = value.equals(inputObject.getDtdRoot());
1116 }
1117 else
1118 if( name.equals("root") ){
1119 cond = value.equals(inputObject.getRoot());
1120 }
1121 else
1122 if( name.equals("ext") ){
1123 cond = inputObject.getFilename().endsWith("." + value);
1124 }
1125 else
1126 if( name.equals("prefix") ){
1127 name = inputObject.getFilename();
1128 if( name != null ){
1129 int i = name.lastIndexOf('/');
1130 if( (i != -1) && ((i+1) < name.length()) ){
1131 name = name.substring(i+1);
1132 }
1133 i = name.lastIndexOf('\\');
1134 if( (i != -1) && ((i+1) < name.length()) ){
1135 name = name.substring(i+1);
1136 }
1137 cond = name.startsWith(value);
1138 } }
1139 else
1140 if( name.equals("meta-type") ){
1141 cond = value.equals(inputObject.getMetaType());
1142 }
1143 else
1144 if( name.equals("content-type") ){
1145 cond = value.equals(inputObject.getContentType());
1146 }
1147 >>>
1148
1149
1150
1151
1152
1153
1154
1155 \<trace found script in map\><<<
1156 if( trace ){
1157 Xtpipes.logWriter.println( " Found script file in map: "
1158 + Xtpipes.scriptFile );
1159 }
1160 >>>
1161
1162
1163 \<trace start map element\><<<
1164 if( Xtpipes.trace ){
1165 String s = "<" + qName + "\n";
1166 for(int i=0; i<atts.getLength(); i++ ){
1167 String name = atts.getQName(i);
1168 s += " " + name + "=\"" + atts.getValue(i) + "\"";
1169 }
1170 s += ">" ;
1171 Xtpipes.logWriter.println( s );
1172 }
1173 >>>
1174
1175 \<trace end map element\><<<
1176 if( Xtpipes.trace ){
1177 String s = "</" + qName + ">";
1178 Xtpipes.logWriter.println( s );
1179 }
1180 >>>
1181
1182
1183
1184 %%%%%%%%%%%%%
1185 \subsection{DTDs}
1186 %%%%%%%%%%%%%
1187
1188
1189
1190 %%%%%%%%%%%%%
1191 \immediate\openin15=xtpipes.dtd
1192 \ifeof15 \else
1193 \immediate\closein15
1194 [\HPage{xtpipes.dtd}
1195 \verbatiminput{xtpipes.dtd}
1196 \EndHPage{}]
1197 \fi
1198 %%%%%%%%%%%%%
1199 %
1200 %%%%%%%%%%%%%
1201 \immediate\openin15=xtpipes-map.dtd
1202 \ifeof15 \else
1203 \immediate\closein15
1204 [\HPage{xtpipes-map.dtd}
1205 \verbatiminput{xtpipes-map.dtd}
1206 \EndHPage{}]
1207 \fi
1208 %%%%%%%%%%%%%
1209
1210 \begin{verbatim}
1211 <xtpipes> ... </xtpipes>
1212 \end{verbatim}
1213
1214 \<xtpipes.dtd\><<<
1215 <!-- xtpipes.dtd (`version), generated from `jobname.tex
1216 Copyright (C) 2009-2010 TeX Users Group
1217 Copyright (C) `CopyYear.2002. Eitan M. Gurari
1218 `<TeX4ht copyright`> -->
1219 <!ELEMENT xtpipes (#PCDATA `<xtpipes entries`>)* >
1220 <!ATTLIST xtpipes
1221 preamble CDATA #IMPLIED DEFAULT (yes | no) "no"
1222 signature CDATA #IMPLIED >
1223 >>>
1224
1225
1226 %
1227 \AtEndDocument{
1228 \OutputCodE\<xtpipes-map.dtd\>
1229 }
1230
1231 \expandafter\AddFile\BIN{xtpipes-map.dtd}{xtpipes\Slash lib}
1232
1233 \<xtpipes-map.dtd\><<<
1234 <!-- xtpipes-map.dtd (`version), generated from `jobname.tex
1235 Copyright (C) 2009-2010 TeX Users Group
1236 Copyright (C) `CopyYear.2002. Eitan M. Gurari
1237 `<TeX4ht copyright`> -->
1238 <!ELEMENT xtpipes-map (when | processing-instruction
1239 | select
1240 | command-line)* >
1241 <!ELEMENT when (when | select
1242 | processing-instruction
1243 | command-line )* >
1244 <!ELEMENT select EMPTY >
1245 <!ELEMENT processing-instruction EMPTY >
1246 <!ELEMENT command-line EMPTY >
1247 <!ATTLIST xtpipes-map
1248 signature CDATA #IMPLIED
1249 >
1250 <!ATTLIST when
1251 name (
1252 system-id
1253 | public-id
1254 | dtd-root
1255 | root
1256 | ext
1257 | meta-type
1258 | content-type
1259 | prefix ) "public-id"
1260 value CDATA #IMPLIED
1261 case-sensitive (yes|no) "no"
1262 >
1263 <!ATTLIST select
1264 name CDATA #REQUIRED
1265 >
1266 >>>
1267
1268
1269 %%%%%%%%%%%%%
1270 \subsection{Indirect Scripts}
1271 %%%%%%%%%%%%%
1272
1273
1274
1275 If the root xtpipes element has no children, the input file is
1276 searched for an alternative script within a processing instruction of
1277 the form \verb+<?xtpipes file="..." ?>+.
1278
1279 \<script := xtpipes processing instruction\><<<
1280 if( inData == null ){
1281 `<search file for xtpipes instruction`>
1282 } else {
1283 `<search string for xtpipes instruction`>
1284 }
1285 >>>
1286
1287
1288 %%%%%%%%%%%%%
1289 \subsection{Search File}
1290 %%%%%%%%%%%%%
1291
1292
1293
1294
1295 \<search file for xtpipes instruction\><<<
1296 /*
1297 errMsg = "Searching <?xtpipes file=\"...\"?> in "
1298 + inFile + ": ";
1299 */
1300 scriptFile = inputObject.getXtpipes();
1301 rootName = inputObject.getRoot();
1302 needScript = true;
1303 >>>
1304
1305 \<search file for xtpipes instructionOLD\><<<
1306 errMsg = "Searching <?xtpipes file=\"...\"?> in "
1307 + inFile + ": ";
1308 `<get sax reader`>
1309 saxReader.setContentHandler( new XtPipesSearch() );
1310 try{
1311 saxReader.parse( new File(inFile).toURI().toURL().toString() );
1312 } catch ( java.io.FileNotFoundException ioe ){
1313 try{
1314 saxReader.parse( new InputSource(
1315 new URL(inFile) . openStream() ));
1316 } catch ( java.io.FileNotFoundException fnf ){
1317 saxReader.parse( new File(inFile).toURI().toURL().toString() );
1318 } }
1319 saxReaderStack.push( saxReader );
1320 >>>
1321
1322 %%%%%%%%%%%%%
1323 \subsection{Copy Preamble}
1324 %%%%%%%%%%%%%
1325
1326
1327 Copy into th eoutput the code preceeding the root. Note: assumes proper
1328 XML file as it doesn't use ml2xml. NEEDS FIXING.
1329 Example:
1330
1331 \begin{verbatim}
1332 ----> <?xml version="1.0" encoding="UTF-8"?>
1333 ----> <!DOCTYPE math:math PUBLIC "-//W3C//DTD MathML 2.0//EN" "math.dtd">
1334 ----> <?xtpipes file="oo-math.4xt" ?>
1335 ----> <!-- try-m12 by TeX4ht from try.tex line 69 2007-01-09-11:20
1336 ----> (http://www.cse.ohio-state.edu/~gurari/TeX4ht/) -->
1337 \end{verbatim}
1338
1339
1340
1341 \<cond copy input preamble\><<<
1342 if( node.hasAttributes() ){
1343 Node attr = node.getAttributes()
1344 .getNamedItem( "signature" );
1345 `<preamble output into log`>
1346 attr = node.getAttributes()
1347 .getNamedItem( "preamble" );
1348 if( (attr != null)
1349 && attr.getNodeValue().equals( "yes" ) ){
1350 `<get src preamble`>
1351 } }
1352 >>>
1353
1354
1355 \<get src preamble\><<<
1356 // BufferedReader br = null;
1357 try {
1358 String s;
1359 boolean front = true;
1360 rootName = "<" + ((rootName==null)? inputObject.getRoot() : rootName);
1361 if( inData == null ){
1362 `<get src preamble from file`>
1363 } else {
1364 `<get src preamble from string`>
1365 }
1366 } catch (Exception e) {
1367 System.err.println(
1368 "--- Error --- Couldn't copy preamble: " + e);
1369 }
1370 >>>
1371
1372
1373
1374
1375 \<get src preamble from file\><<<
1376 // FileReader fr = new FileReader(inFile);
1377 // BufferedReader in = new BufferedReader(fr);
1378 `<BufferedReader in := inFile`>
1379 while ( ((s = in.readLine()) != null) && front ) {
1380 int i = s.indexOf( rootName );
1381 if( i > -1 ){
1382 front = false;
1383 s = s.substring(0,i);
1384 }
1385 outPrintWriter.println(s);
1386 returnToFile = false;
1387 }
1388 in.close();
1389 >>>
1390
1391 \<BufferedReader in := inFile\><<<
1392 URLConnection connection =
1393 new URL(inFile).openConnection();
1394 connection.setRequestProperty("User-Agent",
1395 "["
1396 + System.getProperty("os.name")
1397 + " / "
1398 + System.getProperty("os.arch")
1399 + "]"
1400 + "["
1401 + System.getProperty("java.version")
1402 + " - "
1403 + System.getProperty("java.vendor")
1404 + "]"
1405 );
1406 InputStream inputStream = connection.getInputStream();
1407 BufferedReader in = new BufferedReader (
1408 new InputStreamReader ( inputStream ) );
1409 >>>
1410
1411
1412
1413
1414
1415
1416 \<get src preamble from string\><<<
1417 int i = inData.indexOf( rootName );
1418 if( i > -1 ){
1419 front = false;
1420 s = inData.substring(0,i);
1421 } else { s = ""; }
1422 outPrintWriter.println(s);
1423 returnToFile = false;
1424 >>>
1425
1426
1427
1428
1429 %%%%%%%%%%%%%%%%%%
1430 \section{The Instructions}
1431 %%%%%%%%%%%%%%%%%%
1432
1433
1434
1435 %%%%%%%%%%%%%
1436 \subsection{XtPipes}
1437 %%%%%%%%%%%%%
1438
1439 The xtpipes element is the root of the script file through which
1440 the transformation starts.
1441
1442 \<execute xtpipes\><<<
1443 // String errMsg = "";
1444 needScript = false;
1445 if( node.hasChildNodes() ){
1446 `<open output file`>
1447 `<cond copy input preamble`>
1448 execute( node.getFirstChild() );
1449 } else {
1450 `<script := xtpipes processing instruction`>
1451 }
1452 >>>
1453
1454
1455
1456
1457
1458
1459 If the root xtpipes element has no children, the input file is
1460 searched for an alternative script within a processing instruction of
1461 the form \verb+<?xtpipes file="..." ?>+.
1462
1463
1464
1465
1466
1467 %%%%%%%%%%%%%
1468 \subsection{Handle Set}
1469 %%%%%%%%%%%%%
1470
1471 Associate a name to the given enclosed code.
1472
1473 \begin{verbatim}
1474 <set name="...">
1475 <![CDATA[
1476 ...
1477 ]]>
1478 </set>
1479 \end{verbatim}
1480
1481 \<xtpipes entries\><<<
1482 | set
1483 >>>
1484
1485 \<xtpipes.dtd\><<<
1486 <!ELEMENT set (#PCDATA) >
1487 <!ATTLIST set
1488 name CDATA #REQUIRED >
1489 >>>
1490
1491
1492
1493
1494
1495 \<execute set\><<<
1496 String name = node.getAttributes().getNamedItem( "name" )
1497 .getNodeValue();
1498 Node cdata = node.getFirstChild();
1499 while( cdata.getNodeType() != Node.CDATA_SECTION_NODE ){
1500 cdata = cdata.getNextSibling();
1501 }
1502 String code = cdata.getNodeValue().trim();
1503 map.put( name, (Object) code );
1504 >>>
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514 %%%%%%%%%%%%%
1515 \subsection{Handle Get XML Code}
1516 %%%%%%%%%%%%%
1517
1518 Stores a XML file content under the given name.
1519
1520 \begin{verbatim}
1521 <get name="..." file="..." />
1522 \end{verbatim}
1523
1524
1525 \<xtpipes entries\><<<
1526 | get
1527 >>>
1528
1529
1530 \<xtpipes.dtd\><<<
1531 <!ELEMENT get EMPTY >
1532 <!ATTLIST get
1533 name CDATA #REQUIRED
1534 file CDATA #REQUIRED
1535 >
1536 >>>
1537
1538
1539 \<execute get\><<<
1540 try {
1541 String name = node.getAttributes()
1542 .getNamedItem( "name" ).getNodeValue();
1543 String file = node.getAttributes()
1544 .getNamedItem( "file" ).getNodeValue();
1545 StreamSource in = new StreamSource( new File(file) );
1546 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1547 identityTransformer.transform( in, new StreamResult(baos) );
1548 byte [] bytes = baos.toByteArray();
1549 map.put( name, (Object) new String(bytes) );
1550 } catch( Exception e ){
1551 instructionErr( node, e.toString(), 14 );
1552 }
1553 >>>
1554
1555
1556
1557 \<xtpipes initialization\><<<
1558 fc = TransformerFactory.newInstance();
1559 identityTransformer = fc.newTransformer();
1560 identityTransformer.setErrorListener(
1561 `<identity transformer XML error listener`> );
1562 >>>
1563
1564 \<xtpipes fields\><<<
1565 private static TransformerFactory fc;
1566 private static Transformer identityTransformer;
1567 >>>
1568
1569
1570
1571 %%%%%%%%%%%%%
1572 \subsection{Print Named XML Code}
1573 %%%%%%%%%%%%%
1574
1575 Prints the content of the named XML code. If a file name is not
1576 provided in the `file' attribute,
1577 the stderr is assumed.
1578 % the file name from the command line
1579 % is assumed. If a file name is not provided in both places, the stdio
1580 % is assumed.
1581 % outPrintWriter.println( xml );
1582
1583 \begin{verbatim}
1584 <print name="..." file="..." />
1585 \end{verbatim}
1586
1587
1588
1589 \<xtpipes entries\><<<
1590 | print
1591 >>>
1592
1593
1594 \<xtpipes.dtd\><<<
1595 <!ELEMENT print EMPTY >
1596 <!ATTLIST print
1597 name CDATA #REQUIRED
1598 file CDATA #IMPLIED
1599 >
1600 >>>
1601
1602
1603
1604 \<execute print\><<<
1605 String name = node.getAttributes()
1606 .getNamedItem( "name" ).getNodeValue();
1607 String xml = (String) map.get(name);
1608 if( node.getAttributes().getNamedItem( "file" )==null ){
1609 if( !Xtpipes.trace ){
1610 logWriter.println( "[##] = xtpipes => print: " + scriptFile );
1611 }
1612 logWriter.println( XtpipesUni.toUni(xml, "") );
1613 } else {
1614 String file = node.getAttributes()
1615 .getNamedItem( "file" ).getNodeValue();
1616 try{
1617 FileWriter fw = new FileWriter( file );
1618 XtpipesPrintWriter out = new XtpipesPrintWriter( fw );
1619 out.println( xml );
1620 out.close();
1621 } catch(Exception e){
1622 instructionErr( node, e.toString(),15 );
1623 } }
1624 >>>
1625
1626
1627
1628
1629 %%%%%%%%%%%%%
1630 \subsection{Result for Returned Value}
1631 %%%%%%%%%%%%%
1632
1633 A call to getDOM uses the data for its returned value.
1634
1635 \begin{verbatim}
1636 <return name="..." />
1637 \end{verbatim}
1638
1639
1640
1641 \<xtpipes entries\><<<
1642 | return
1643 >>>
1644
1645
1646 \<xtpipes.dtd\><<<
1647 <!ELEMENT return EMPTY >
1648 <!ATTLIST return
1649 name CDATA #REQUIRED
1650 >
1651 >>>
1652
1653
1654
1655 \<execute return\><<<
1656 String name = node.getAttributes()
1657 .getNamedItem( "name" ).getNodeValue();
1658 result = (String) map.get(name);
1659 if( returnToFile ){
1660 outPrintWriter.println(result);
1661 }
1662 >>>
1663
1664
1665
1666
1667 %%%%%%%%%%%%%
1668 \subsection{Conditional `if' statements}
1669 %%%%%%%%%%%%%
1670
1671 Execute the enclosed instructions provided the named XML code
1672 satisfied the named DTD conditions.
1673
1674 \begin{verbatim}
1675 <if xml="..." dtd="..." root="..." >
1676 ...
1677 </if>
1678 \end{verbatim}
1679
1680
1681 \<xtpipes entries\><<<
1682 | if
1683 >>>
1684
1685
1686 \<xtpipes.dtd\><<<
1687 <!ELEMENT if (#PCDATA `<xtpipes entries`>)* >
1688 <!ATTLIST if
1689 xml CDATA #REQUIRED
1690 dtd CDATA #REQUIRED
1691 root CDATA #REQUIRED
1692 >
1693 >>>
1694
1695 \<execute if\><<<
1696 try{
1697 `<doc = dtd + xml`>
1698 byte [] bytes = doc.getBytes("UTF-8");
1699 ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
1700 InputSource in = new InputSource( bais );
1701 SAXParser saxParser = saxFactory.newSAXParser();
1702 XMLReader xmlReader = saxParser.getXMLReader();
1703 xmlReader.parse( in );
1704 `<trace if true`>
1705 execute( node.getFirstChild() );
1706 } catch ( Exception e ){ `<trace if false`> }
1707 >>>
1708
1709
1710 \<doc = dtd + xml\><<<
1711 String xml = node.getAttributes()
1712 .getNamedItem( "xml" ).getNodeValue();
1713 String dtd = node.getAttributes()
1714 .getNamedItem( "dtd" ).getNodeValue();
1715 // String root = node.getAttributes()
1716 // .getNamedItem( "root" ).getNodeValue();
1717 String doc = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
1718 + "<!DOCTYPE doc [\n"
1719 + (String) map.get(dtd)
1720 + "\n]>\n"
1721 + (String) map.get(xml) ;
1722 >>>
1723
1724
1725
1726 \<xtpipes initialization\><<<
1727 saxFactory = SAXParserFactory.newInstance();
1728 saxFactory.setValidating(true);
1729 >>>
1730
1731
1732 \<xtpipes fields\><<<
1733 private static SAXParserFactory saxFactory;
1734 >>>
1735
1736
1737 %%%%%%%%%%%%%
1738 \subsection{Handle XSLT}
1739 %%%%%%%%%%%%%
1740
1741 %%%%%%%%%%%%%
1742 \subsubsection{Outline}
1743 %%%%%%%%%%%%%
1744
1745 Associate a name to the result of applying the named XSLT
1746 transformation on the named XML code. If the name is omitted, the
1747 outcome is sent to the output file named in the command line. If such
1748 file name is not provided, the standard I/O stream is assumed.
1749
1750
1751 \begin{verbatim}
1752 <xslt name="..." xml="..." xsl="..." />
1753 \end{verbatim}
1754
1755 Note that XSLT is just a restricted kind of XML code.
1756
1757
1758
1759 \<xtpipes entries\><<<
1760 | xslt
1761 >>>
1762
1763
1764 \<xtpipes.dtd\><<<
1765 <!ELEMENT xslt EMPTY >
1766 <!ATTLIST xslt
1767 name CDATA #IMPLIED
1768 xml CDATA #REQUIRED
1769 xsl CDATA #REQUIRED
1770 >
1771 >>>
1772
1773 \<execute xslt\><<<
1774 try{
1775 `<StreamSource inDoc = ...`>
1776 `<StreamSource inXslt = ...`>
1777 `<StreamResult outDoc = ...`>
1778 errMssg = null;
1779 fc.setErrorListener( `<transformer factory XSLT error listener`> );
1780 Transformer transformer = fc.newTransformer( inXslt );
1781 transformer.setErrorListener( `<transformer XML error listener`> );
1782 transformer.transform(inDoc, outDoc );
1783 `<store xslt outcome`>
1784 } catch ( javax.xml.transform.TransformerException e ){
1785 if( Xtpipes.trace ){ e.printStackTrace(); }
1786 instructionErr( node,
1787 e.getMessage()
1788 +
1789 ((errMssg==null)? "" : ("; " +errMssg))
1790 , 37);
1791 } catch ( Exception e ){
1792 if( Xtpipes.trace ){ e.printStackTrace(); }
1793 instructionErr( node, (errMssg==null)? e.toString()
1794 : e.toString() + "; " + errMssg
1795 , 16 );
1796 }
1797 >>>
1798
1799
1800
1801
1802
1803
1804
1805 %%%%%%%%%%%%%
1806 \subsubsection{Input}
1807 %%%%%%%%%%%%%
1808
1809 \<StreamSource inDoc = ...\><<<
1810 Node xmlNode = node.getAttributes().getNamedItem( "xml" );
1811 StreamSource inDoc = null;
1812 String xml;
1813 if( xmlNode == null ){
1814 `<inDoc = input stream source`>
1815 } else {
1816 xml = xmlNode.getNodeValue();
1817 String doc = (String) map.get(xml);
1818 if( doc!=null ){
1819 byte [] bytes = doc.getBytes("UTF-8");
1820 ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
1821 inDoc = new StreamSource( bais );
1822 } }
1823 >>>
1824
1825
1826
1827
1828 \<inDoc = input stream source\><<<
1829 if( inData == null ){
1830 inDoc = new StreamSource( new File(inFile) );
1831 } else {
1832 byte [] bytes = inData.getBytes("UTF-8");
1833 ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
1834 inDoc = new StreamSource( bais );
1835 }
1836 >>>
1837
1838
1839
1840 %%%%%%%%%%%%%
1841 \subsubsection{XSLT}
1842 %%%%%%%%%%%%%
1843
1844 \<StreamSource inXslt = ...\><<<
1845 String xslt = node.getAttributes()
1846 .getNamedItem( "xsl" ).getNodeValue();
1847 String templates = (String) map.get(xslt);
1848 byte [] bytes = templates.getBytes("UTF-8");
1849 ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
1850 StreamSource inXslt = new StreamSource( bais );
1851 >>>
1852
1853
1854 %%%%%%%%%%%%%
1855 \subsubsection{Output}
1856 %%%%%%%%%%%%%
1857
1858
1859
1860 \<StreamResult outDoc = ...\><<<
1861 Node nameNode = node.getAttributes().getNamedItem("name");
1862 StreamResult outDoc;
1863 CharArrayWriter caos = null;
1864 if( nameNode == null ){
1865 outDoc = new StreamResult(outPrintWriter);
1866 returnToFile = false;
1867 } else {
1868 caos = new CharArrayWriter();
1869 outDoc = new StreamResult(caos);
1870 }
1871 >>>
1872
1873
1874 \<store xslt outcome\><<<
1875 `<store chars into map`>
1876 >>>
1877
1878
1879
1880
1881
1882 \<NO\><<<
1883 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1884 StreamResult outDoc = new StreamResult(baos);
1885 >>>
1886
1887
1888 \<NO\><<<
1889 String name = node.getAttributes()
1890 .getNamedItem( "name" ).getNodeValue();
1891 bytes = baos.toByteArray();
1892 map.put( name, (Object) new String(bytes) );
1893 >>>
1894
1895
1896 %%%%%%%%%%%%%
1897 \subsection{DOM}
1898 %%%%%%%%%%%%%
1899
1900
1901 %%%%%%%%%%%%%
1902 \subsubsection{Outline}
1903 %%%%%%%%%%%%%
1904
1905
1906 Associate a name to the result of applying the named method on the DOM
1907 of the named XML code. The method should have an interface similar to
1908 \verb+public static void m( Node dom )+.
1909
1910 \begin{verbatim}
1911 <dom name="..." xml="..." method="..." class="..." />
1912 \end{verbatim}
1913
1914
1915 \<xtpipes entries\><<<
1916 | dom
1917 >>>
1918
1919
1920 \<xtpipes.dtd\><<<
1921 <!ELEMENT dom EMPTY >
1922 <!ATTLIST dom
1923 name CDATA #REQUIRED
1924 xml CDATA #REQUIRED
1925 method CDATA #REQUIRED
1926 class CDATA #REQUIRED
1927 dcl CDATA #IMPLIED DEFAULT (yes | no) "no"
1928 >
1929 >>>
1930
1931
1932
1933 \<execute dom\><<<
1934 try{
1935 `<load xml into dom`>
1936 `<transform dom`>
1937 `<store dom into map`>
1938 } catch ( NoSuchMethodException e ){
1939 instructionErr( node,
1940 "could not find method: " + e.getMessage(), 18 );
1941 } catch ( java.lang.reflect.InvocationTargetException e ){
1942 if( Xtpipes.trace ){ e.printStackTrace(); }
1943 instructionErr( node, e.getCause().toString(), 36);
1944 } catch ( Exception e ){
1945 if( Xtpipes.trace ){ e.printStackTrace(); }
1946 instructionErr( node, e.toString(), 20 );
1947 }
1948 >>>
1949
1950
1951
1952 %%%%%%%%%%%%%
1953 \subsubsection{Transform}
1954 %%%%%%%%%%%%%
1955
1956
1957 \<transform dom\><<<
1958 String className = node.getAttributes()
1959 .getNamedItem( "class" ).getNodeValue();
1960 String methodName = node.getAttributes()
1961 .getNamedItem( "method" ).getNodeValue();
1962 Class <?> cls = Class.forName( className );
1963 Class<?> [] argTypes = { Node.class };
1964 Method m = cls.getMethod( methodName, argTypes );
1965 Object parmValues[] = new Object[1];
1966 parmValues[0] = dom;
1967 m.invoke( null, parmValues );
1968 >>>
1969
1970 \<xtpipes initialization\><<<
1971 domFactory.setValidating(false);
1972 domBuilder = domFactory.newDocumentBuilder();
1973 >>>
1974
1975 \<xtpipes fields\><<<
1976 private static DocumentBuilder domBuilder;
1977 >>>
1978
1979
1980
1981 %%%%%%%%%%%%%
1982 \subsubsection{Input Stream}
1983 %%%%%%%%%%%%%
1984
1985
1986 \<load xml into dom\><<<
1987 Node xmlNode = node.getAttributes().getNamedItem( "xml" );
1988 Document dom;
1989 if( xmlNode == null ){
1990 `<dom = parse input`>
1991 } else {
1992 String xml = xmlNode.getNodeValue();
1993 String doc = (String) map.get(xml);
1994 if( doc == null ){
1995 instructionErr( node, "improper xml attribute value", 18 );
1996 }
1997 byte [] bytes = doc.getBytes("UTF-8");
1998 InputStream is = new ByteArrayInputStream( bytes );
1999 dom = domBuilder.parse (is);
2000 }
2001 >>>
2002
2003 \<dom = parse input\><<<
2004 if( inData == null ){
2005 dom = domBuilder.parse( new File(inFile) );
2006 } else {
2007 byte [] bytes = inData.getBytes("UTF-8");
2008 InputStream is = new ByteArrayInputStream( bytes );
2009 dom = domBuilder.parse (is);}
2010 >>>
2011
2012
2013
2014 %%%%%%%%%%%%%
2015 \subsubsection{Output Stream}
2016 %%%%%%%%%%%%%
2017
2018
2019 \<store dom into map\><<<
2020 `<StreamResult outDoc = ...`>
2021 cleanXmlns(dom);
2022 DOMSource domSource = new DOMSource(dom);
2023 try{
2024 identityTransformer.transform( domSource, outDoc );
2025 } catch ( javax.xml.transform.TransformerException e ){
2026 String s = Xtpipes.trace?
2027 (
2028 "\n------------------------ xml code ------------------------\n"
2029 + serialize( dom )
2030 + "\n----------------------------------------------------------\n"
2031 )
2032 : "";
2033 instructionErr( node, e.getMessage() + s, 35 );
2034 }
2035 if( nameNode != null ){
2036 String name = nameNode.getNodeValue();
2037 char [] chars = caos.toCharArray() ;
2038 String domString = new String(chars);
2039 `<remove dom dcl`>
2040 map.put( name, (Object) domString );
2041 }
2042 >>>
2043
2044
2045 \<remove dom dcl\><<<
2046 Node dcl = node.getAttributes().getNamedItem( "dcl" );
2047 if( ((dcl == null) || (dcl.getNodeValue().equals("no") ))
2048 &&
2049 (domString.length() > 7)
2050 &&
2051 domString.startsWith("<?xml")
2052 &&
2053 !Character.isLetterOrDigit( domString.charAt(5) )
2054 ){
2055 domString = domString.substring( domString.indexOf("?>") + 2 );
2056 }
2057 >>>
2058
2059
2060
2061
2062
2063
2064 \<NO\><<<
2065 String name = node.getAttributes()
2066 .getNamedItem( "name" ).getNodeValue();
2067 ByteArrayOutputStream baos = new ByteArrayOutputStream();
2068 identityTransformer.transform( new DOMSource(dom),
2069 new StreamResult(baos) );
2070 bytes = baos.toByteArray();
2071 map.put( name, (Object) new String(bytes) );
2072 >>>
2073
2074
2075
2076 %%%%%%%%%%%%%
2077 \subsection{Handle SAX}
2078 %%%%%%%%%%%%%
2079
2080
2081 %%%%%%%%%%%%%
2082 \subsubsection{outline}
2083 %%%%%%%%%%%%%
2084
2085 Apply the specified content-handler and filters on the XML
2086 content.
2087
2088 \begin{verbatim}
2089 <sax name="..." xml="..." content-handler="..."
2090 lexical-handler="..." >
2091 <script element="..." > ... </script>
2092 ...
2093 <script element="..." > ... </script>
2094 </sax>
2095 \end{verbatim}
2096
2097
2098 If provided, the {\bf name attribute} is associated to the outcome.
2099 If omitted, the output file name from the command line is assumed. If
2100 such file name is not provided, the standard I/O stream is assumed.
2101
2102 If the {\bf xml attribute} is not internally defined (within the hash
2103 table), a file name is assumed. If not provided, it stands for the
2104 input file name provided in the command line.
2105
2106 The \verb+content-handler+ attribute gets a comma seperated list of
2107 classes names. The first argument refers to a content handler, the
2108 other arguments refer to filters. A content handler gets five
2109 arguments: output stream, an HashMap refering to the different scripts
2110 enclosed by the sax instruction, a method, log stream, and a boolean
2111 trace indicator. A filter and a lexical-constractor gets three
2112 arguments: output stream, log stream, and a boolean trace indicator.
2113
2114 The sax instruction applies the filters and the content handler on the
2115 provided xml string. The script elements offer definitions of scripts
2116 delivered to the content handler. The ScriptsManager content handler
2117 of the distribution (Section~\ref{ScriptsManager}), for instance,
2118 invokes these scripts when their corresponding named elemets are
2119 encountered.
2120
2121
2122 \<xtpipes entries\><<<
2123 | sax
2124 >>>
2125
2126
2127 \<xtpipes.dtd\><<<
2128 <!ELEMENT sax (#PCDATA | script)* >
2129 <!ELEMENT script (#PCDATA `<xtpipes entries`> )* >
2130 <!ATTLIST sax
2131 name CDATA #IMPLIED
2132 xml CDATA #IMPLIED
2133 content-handler CDATA #REQUIRED
2134 lexical-handler CDATA #IMPLIED
2135 >
2136 <!ATTLIST script
2137 element CDATA #REQUIRED
2138 >
2139 >>>
2140
2141 \<execute sax\><<<
2142 String errMsg = "";
2143 try{
2144 `<load xml into input source`>
2145 `<String [] className = ...`>
2146 `<ch := content handler`>
2147 `<get sax reader`>
2148 XMLReader reader = saxReader;
2149 `<insert sax filters`>
2150 errMsg = "setContentHandler( "
2151 + className[0].trim() + " )";
2152 saxReader.setContentHandler( (org.xml.sax.ContentHandler) ch );
2153 `<saxReader += lexical handler`>
2154 `<saxReader := ignore DOCTYPE statement`>
2155 if( inputSource==null ){
2156 `<open sax input file`>
2157 } else {
2158 errMsg = "xtpipes sax parsing error";
2159 saxReader.parse( inputSource );
2160 }
2161 `<store chars into map`>
2162 saxReaderStack.push( reader );
2163 } catch ( java.io.FileNotFoundException e ){
2164 instructionErr( node, errMsg
2165 + "could not find file: " + e.getMessage(), 19 );
2166 } catch ( ClassNotFoundException e ){
2167 instructionErr( node, errMsg
2168 + " class not found: "
2169 + e.getMessage() + "\n classpath = "
2170 + System.getProperty("java.class.path")
2171 + " ---", 22 );
2172 } catch ( java.lang.reflect.InvocationTargetException e ){
2173 instructionErr( node, errMsg + ": " + e.getCause(), 23 );
2174 } catch ( Exception e ){
2175 Xtpipes.logWriter.flush();
2176 e.printStackTrace();
2177 instructionErr( node, errMsg + ": " + e.toString(), 29 );
2178 }
2179 >>>
2180
2181 \<open sax input file\><<<
2182 errMsg = "While parsing file " + xml + ": ";
2183 InputStream inputStream = null;
2184 if( Xtpipes.ml2xml == null ){
2185 if( Xtpipes.trace ){
2186 Xtpipes.logWriter.println(
2187 "No request for ml2xml configuration (command line option -x)" );
2188 }
2189 `<inputStream := ml2xml-less imput`>
2190 } else {
2191 `<inputStream := (InputStream) new Ml2xml(filename, "foo.m2x")`>
2192 }
2193 saxReader.parse( new InputSource(inputStream) );
2194 `<Ml2xml close files`>
2195 >>>
2196
2197 \<inputStream := ml2xml-less imput\><<<
2198 try{
2199 inputStream = (InputStream) (new File(xml).toURI().toURL().openStream());
2200 } catch ( java.io.FileNotFoundException ioe ){
2201 try{
2202 URL url = null;
2203 try {
2204 url = new URL(xml);
2205 } catch ( java.net.MalformedURLException fnf ){
2206 url = new File(xml).toURI().toURL();
2207 }
2208 inputStream = (InputStream) (url.openStream());
2209 } catch ( java.io.FileNotFoundException fnf ){
2210 inputStream = (InputStream)
2211 (
2212 new File( new File(xml).toURI().toURL().toString() )
2213 . toURI().toURL()
2214 . openStream()
2215 );
2216 } }
2217 >>>
2218
2219
2220
2221
2222
2223 %%%%%%%%%%%%%
2224 \subsubsection{SAX Reader}
2225 %%%%%%%%%%%%%
2226
2227 The sax reader is pushed into the stack when its job is done, for
2228 use in other sax instructions. The stack is needed because nested sax
2229 instructions need unspecified number of readers. The filters may
2230 change the sax readers, so the readers need saving for later storing
2231 them in the stacks.
2232
2233 \<get sax reader\><<<
2234 XMLReader saxReader;
2235 if( saxReaderStack.empty() ){
2236 SAXParser saxParser = saxFactory.newSAXParser();
2237 saxReader = saxParser.getXMLReader();
2238 `<saxReader := ignore DOCTYPE statement`>
2239 } else {
2240 saxReader = (XMLReader) saxReaderStack.pop();
2241 }
2242 >>>
2243
2244
2245
2246
2247 \<xtpipes initialization\><<<
2248 saxFactory = SAXParserFactory.newInstance();
2249 saxFactory.setValidating(false);
2250 >>>
2251
2252 \<xtpipes fields\><<<
2253 private static Stack <XMLReader> saxReaderStack;
2254 >>>
2255
2256
2257 \<init fields\><<<
2258 saxReaderStack = new Stack <XMLReader> ();
2259 >>>
2260
2261 %%%%%%%%%%%%%
2262 \subsection{Handling DOCTYPE Statements}
2263 %%%%%%%%%%%%%
2264
2265
2266 The following code hides the DOCTYPE entry when searching the xtpipes
2267 processing instruction and when loading an input file.
2268
2269 \<saxReader := ignore DOCTYPE statement\><<<
2270 saxReader.setEntityResolver(new org.xml.sax.EntityResolver() {
2271 public InputSource resolveEntity(
2272 String publicId, String systemId) {
2273 if( (new File(systemId)).exists() ){
2274 return new org.xml.sax.InputSource( systemId );
2275 }
2276 StringReader strReader = new StringReader("");
2277 return new org.xml.sax.InputSource(strReader);
2278 }
2279 });
2280 >>>
2281
2282 The default SAX behavior observes the DOCTYPE statement and assumes
2283 the following setup.
2284
2285 \begin{verbatim}
2286 saxReader.setEntityResolver(new org.xml.sax.EntityResolver() {
2287 public InputSource resolveEntity(
2288 String publicId, String systemId) {
2289 return null;
2290 }
2291 });
2292 \end{verbatim}
2293
2294
2295
2296
2297 %%%%%%%%%%%%%
2298 \subsubsection{Input}
2299 %%%%%%%%%%%%%
2300
2301
2302 \<load xml into input source\><<<
2303 Node xmlNode = node.getAttributes().getNamedItem( "xml" );
2304 InputSource inputSource=null;
2305 String xml = null;
2306 if( xmlNode == null ){
2307 `<load xml from input`>
2308 } else {
2309 xml = xmlNode.getNodeValue();
2310 String doc = (String) map.get(xml);
2311 if( doc!=null ){
2312 byte [] bytes = doc.getBytes("UTF-8");
2313 ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
2314 inputSource = new InputSource( bais );
2315 } }
2316 >>>
2317
2318
2319 \<load xml from input\><<<
2320 if( inData == null ){
2321 xml = inFile;
2322 } else {
2323 byte [] bytes = inData.getBytes("UTF-8");
2324 ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
2325 inputSource = new InputSource( bais );
2326 }
2327 >>>
2328
2329
2330 %%%%%%%%%%%%%
2331 \subsubsection{Output Stream}
2332 %%%%%%%%%%%%%
2333
2334
2335 \<output stream for sax\><<<
2336 Node nameNode = node.getAttributes().getNamedItem("name");
2337 PrintWriter out;
2338 CharArrayWriter caos = null;
2339 if( nameNode == null ){
2340 out = outPrintWriter;
2341 returnToFile = false;
2342 } else {
2343 caos = new CharArrayWriter();
2344 out = new PrintWriter( caos );
2345 }
2346 >>>
2347
2348 \<store chars into map\><<<
2349 if( nameNode != null ){
2350 String name = nameNode.getNodeValue();
2351 char [] chars = caos.toCharArray() ;
2352 map.put( name, (Object) new String(chars) );
2353 }
2354 >>>
2355
2356 Note: Characters are prefered over bytes as they support
2357 unicode.
2358
2359 %%%%%%%%%%%%%
2360 \subsection{Get Content Handler for SAX}
2361 %%%%%%%%%%%%%
2362
2363 \<String [] className = ...\><<<
2364 String [] className = node.getAttributes()
2365 .getNamedItem( "content-handler" )
2366 .getNodeValue()
2367 .split(",");
2368 >>>
2369
2370
2371
2372
2373 The constructor of a content handler is provided five arguments:
2374
2375 \begin{itemize}
2376 \item
2377 An output stream
2378 \item
2379 A hash map containing the enclosed defdinitions of scripts
2380 \item A method name
2381 \item A log stream
2382 \item A trace flag
2383 \end{itemize}
2384
2385
2386 \<ch := content handler\><<<
2387 Class<?> [] argTypes = {
2388 PrintWriter.class, HashMap.class, Method.class,
2389 PrintWriter.class, boolean.class };
2390 `<output stream for sax`>
2391 Object parmValues[] = new Object[5];
2392 parmValues[0] = out;
2393 `<sax scripts`> parmValues[1] = scripts;
2394 parmValues[2] = method;
2395 parmValues[3] = Xtpipes.logWriter;
2396 parmValues[4] = (Object) Xtpipes.trace;
2397 Class<?> cls = Class.forName( className[0].trim() );
2398 Constructor<?> c = cls.getConstructor( argTypes );
2399 Object ch = (Object) c.newInstance( parmValues );
2400 >>>
2401
2402 \<sax scripts\><<<
2403 HashMap <String,Object> scripts = new HashMap <String,Object> ();
2404 Node script = node.getFirstChild();
2405 while( script != null ){
2406 if( script.getNodeType()==Node.ELEMENT_NODE ){
2407 String element = script.getAttributes().getNamedItem( "element" )
2408 .getNodeValue();
2409 if( scripts.containsKey(element) ){
2410 System.err.println(
2411 "--- Warning --- redfining script: " + element );
2412 }
2413 scripts.put( element, (Object) script );
2414 }
2415 script = script.getNextSibling();
2416 }
2417 >>>
2418
2419 \<xtpipes initialization\><<<
2420 Class <?> cls = Xtpipes.class;
2421 Class<?> [] argTypes = { Node.class, String.class };
2422 method = cls.getMethod( "execute", argTypes );
2423 >>>
2424
2425 \<xtpipes fields\><<<
2426 private static Method method;
2427 >>>
2428
2429 %%%%%%%%%%%%%
2430 \subsection{Get Filters}
2431 %%%%%%%%%%%%%
2432
2433
2434
2435 \<insert sax filters\><<<
2436 for( int i=1; i<className.length; i++ ){
2437 argTypes = new Class [3];
2438 argTypes[0] = PrintWriter.class;
2439 argTypes[1] = PrintWriter.class;
2440 argTypes[2] = boolean.class;
2441 parmValues = new Object[3];
2442 parmValues[0] = out;
2443 parmValues[1] = Xtpipes.logWriter;
2444 parmValues[2] = (Object) Xtpipes.trace;
2445 errMsg = "Class.forName( " + className[i].trim() + ") " ;
2446 cls = Class.forName( className[i].trim() );
2447 errMsg = "get-constructor "
2448 + className[i].trim()
2449 + "( PrintWriter, PrintWriter, boolean ) " ;
2450 c = cls.getConstructor( argTypes );
2451 errMsg = "get-object "
2452 + className[i].trim()
2453 + "( PrintWriter, PrintWriter, boolean ) " ;
2454 if( (cls.getModifiers() % 2) != 1 ){
2455 errMsg += "; class not defined to be public. ";
2456 }
2457 XMLFilter filter = (XMLFilter) c.newInstance( parmValues );
2458 errMsg = "set-parent "
2459 + className[i].trim()
2460 + "( PrintWriter, PrintWriter, boolean ) " ;
2461 filter.setParent(saxReader);
2462 saxReader = filter;
2463 }
2464 >>>
2465
2466
2467 The filters are assumed to have a tri-parameter constructors which
2468 get an output stream for first arguments, log stream for second argument, and
2469 a trace boolean value for third argument.
2470
2471
2472
2473 %%%%%%%%%%%%%
2474 \subsection{Get Lexical Handler for SAX}
2475 %%%%%%%%%%%%%
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485 The constructor of a lexical handler is provided the
2486 content handler as an argument.
2487
2488
2489
2490 \<saxReader += lexical handler\><<<
2491 Node lexAttr = node.getAttributes()
2492 .getNamedItem( "lexical-handler" );
2493 if( lexAttr != null ){
2494 String lexName = lexAttr.getNodeValue();
2495 argTypes = new Class[3];
2496 argTypes[0] = Class.forName( className[0].trim() );
2497 argTypes[1] = PrintWriter.class;
2498 argTypes[2] = boolean.class;
2499 parmValues = new Object[3];
2500 parmValues[0] = ch;
2501 parmValues[1] = Xtpipes.logWriter;
2502 parmValues[2] = (Object) Xtpipes.trace;
2503 errMsg = "Class.forName( " + lexName.trim() + ") " ;
2504 cls = Class.forName( lexName.trim() );
2505 errMsg = "get-constructor " +
2506 lexName.trim() +
2507 "( " + className[0].trim() + " ) " ;
2508 c = cls.getConstructor( argTypes );
2509 errMsg = "get-object " +
2510 lexName.trim() + "( ... ) " ;
2511 Object xh = (Object) c.newInstance( parmValues );
2512 errMsg = "set lexical handler " + lexName.trim() + " ";
2513 saxReader.setProperty(
2514 "http://xml.org/sax/properties/lexical-handler",
2515 (org.xml.sax.ext.LexicalHandler) xh
2516 );
2517 }
2518 >>>
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529 %%%%%%%%%%%%%%%%%%
2530 \section{Entity Resolver}
2531 %%%%%%%%%%%%%%%%%%
2532
2533
2534 %%%%%%%%%%%%%
2535 \subsection{Interface}
2536 %%%%%%%%%%%%%
2537
2538
2539
2540
2541 \<new EntityResolver()\><<<
2542 new XtpipesEntityResolver()
2543 >>>
2544
2545 \<class XtpipesEntityResolver\><<<
2546 class XtpipesEntityResolver implements org.xml.sax.EntityResolver {
2547 `<InputSource resolveEntity(publicID, systemId)`>
2548 }
2549 >>>
2550
2551
2552 %%%%%%%%%%%%%
2553 \subsection{Implementation}
2554 %%%%%%%%%%%%%
2555
2556
2557
2558 \<InputSource resolveEntity(publicID, systemId)\><<<
2559 public InputSource resolveEntity(String publicID, String systemID)
2560 throws SAXException {
2561 if( Xtpipes.trace ){
2562 Xtpipes.logWriter.println( "Resolving: publicID = \" " + publicID
2563 + "\" systemID = \"" + systemID + "\"" );
2564 }
2565 String file = FileInfo.searchFile( systemID );
2566 if( file != null ){
2567 try{
2568 file = new File(file).toURI().toURL().toString();
2569 return new InputSource( file );
2570 } catch( java.net.MalformedURLException mfe){
2571 throw new SAXException(
2572 "--- xtpipes error 30 --- improper file name: " + file );
2573 } }
2574 return null;
2575 }
2576 >>>
2577
2578
2579
2580 %%%%%%%%%%%%%%%%%%
2581 \section{File Information}
2582 %%%%%%%%%%%%%%%%%%
2583
2584
2585 %%%%%%%%%%%%%
2586 \subsection{Outline}
2587 %%%%%%%%%%%%%
2588
2589
2590
2591
2592 %
2593 \AtEndDocument{
2594 \OutputCodE\<FileInfo.java\>
2595 }
2596
2597 \AddFile{FileInfo.java}{xtpipes}
2598
2599 \<FileInfo.java\><<<
2600 package xtpipes;
2601 /* FileInfo.java (`version), generated from `jobname.tex
2602 Copyright (C) 2009-2010 TeX Users Group
2603 Copyright (C) `CopyYear.2002. Eitan M. Gurari
2604 `<TeX4ht copyright`> */
2605 `<FileInfo imports`>
2606 public class FileInfo{
2607 `<FileInfo fields`>
2608 public FileInfo(PrintWriter log, String iii_scriptDir, boolean trace) {
2609 FileInfo.log = log;
2610 FileInfo.ii_scriptDir = iii_scriptDir;
2611 FileInfo.trace = trace;
2612 `<classPaths[] := ...`>
2613 `<scriptPaths[] := ...`>
2614 }
2615 `<static String searchFile( file )`>
2616 `<static String [] getPaths( dirs )`>
2617 `<static String cleanPath( path )`>
2618 `<static String searchDirectory(dir, file)`>
2619 }
2620 >>>
2621
2622 \<FileInfo fields\><<<
2623 static String [] classPaths = null;
2624 static String [] scriptPaths = null;
2625 static java.util.HashMap <String,String> registry =
2626 new java.util.HashMap <String,String>();
2627 static String slash = System.getProperty("file.separator");
2628 static String ii_scriptDir;
2629 static PrintWriter log;
2630 static boolean trace;
2631 >>>
2632
2633
2634 \<FileInfo imports\><<<
2635 import java.io.File;
2636 import java.io.PrintWriter;
2637 >>>
2638
2639 %%%%%%%%%%%%%
2640 \subsection{Search Engine}
2641 %%%%%%%%%%%%%
2642
2643
2644
2645
2646 \<static String searchFile( file )\><<<
2647 public static String searchFile( String file ){
2648 String key = ((ii_scriptDir == null)? "" : ii_scriptDir )
2649 + "!" + file;
2650 String result = (String) registry.get( key );
2651 if( result == null ){
2652 for(int i=0; i<2; i++){
2653 if( trace ){
2654 log.println( "Searching: " + file );
2655 }
2656 if( (new File(file)).exists() ){
2657 result = ( file.indexOf(slash) == -1 )?
2658 (System.getProperty("user.dir") + slash + file)
2659 :
2660 file;
2661 }
2662 else {
2663 if( ii_scriptDir != null ){
2664 `<search file in script directories`>
2665 }
2666 if( result == null ){
2667 `<search file in classpath/xtpipes/lib`>
2668 } }
2669 if( result != null ){ break; }
2670 file = new File(file).getName();
2671 }
2672 if( result != null ){
2673 result = FileInfo.cleanPath(result);
2674 registry.put(key, result);
2675 }
2676 }
2677 if( trace ){
2678 if( result == null ){
2679 log.println(
2680 "Directory paths from xtpipes command line option -i: "
2681 + ii_scriptDir );
2682 } else { log.println( "Found: " + result + "\n" ); }
2683 log.flush();
2684 }
2685 return result;
2686 }
2687 >>>
2688
2689
2690
2691 \<search file in script directories\><<<
2692 int k = scriptPaths.length;
2693 while( k>0 ){
2694 k--;
2695 if( trace ){
2696 log.println( "Searching: " + file
2697 + ", recursively in directory: " + scriptPaths[k] );
2698 }
2699 result = searchDirectory( new File(scriptPaths[k]), file);
2700 if( result != null ){ break; }
2701 }
2702 String s = ii_scriptDir + file;
2703 if( (new File( s )).exists() ){ result = s; }
2704 >>>
2705
2706
2707 \<search file in classpath/xtpipes/lib\><<<
2708 int k = classPaths.length;
2709 String toFile = "xtpipes" + slash + "lib" + slash + file;
2710 while( k>0 ){
2711 k--;
2712 String s = classPaths[k] + toFile;
2713 if( trace ){ log.println( "Searching: " + s ); }
2714 if( new File(s).exists() ){ result = s; break; }
2715 }
2716 >>>
2717
2718
2719 \<static String searchDirectory(dir, file)\><<<
2720 static String searchDirectory(File dir, String file) {
2721 String result = null;
2722 if( dir.isDirectory() ){
2723 String [] children = dir.list();
2724 for (int i=0; i<children.length; i++) {
2725 result = searchDirectory( new File(dir,children[i]), file);
2726 if( result != null ) { break; }
2727 }
2728 } else {
2729 String s = dir.toString();
2730 if( s.equals(file) || s.endsWith(slash + file) ){
2731 result = s;
2732 }
2733 }
2734 return result;
2735 }
2736 >>>
2737
2738
2739
2740 %%%%%%%%%%%%%
2741 \subsection{Class Paths}
2742 %%%%%%%%%%%%%
2743
2744
2745
2746
2747 \<classPaths[] := ...\><<<
2748 classPaths = FileInfo.getPaths( System.getProperty("java.class.path") );
2749 >>>
2750
2751 Script paths are to be encoded in a similar manner as class paths.
2752
2753 \<classPaths[] := ...\><<<
2754 if( iii_scriptDir != null ){
2755 scriptPaths = FileInfo.getPaths( iii_scriptDir );
2756 }
2757 >>>
2758
2759 \<static String [] getPaths( dirs )\><<<
2760 static String [] getPaths( String dirs ){
2761 String [] paths = null;
2762 paths = dirs.split( System.getProperty("path.separator") );
2763 int k = paths.length;
2764 while( k>0 ){
2765 k--;
2766 `<set full path`>
2767 int len = paths[k].length();
2768 if( (len>1) && (paths[k].lastIndexOf(slash + ".") == (len-1)) ){
2769 paths[k] = paths[k].substring(0,len-1);
2770 } else if( (len>0) && ((len-1) != paths[k].lastIndexOf( slash )) ){
2771 paths[k] += slash;
2772 } }
2773 return paths;
2774 }
2775 >>>
2776
2777
2778
2779 \<set full path\><<<
2780 paths[k] = cleanPath( paths[k] );
2781 >>>
2782
2783 \<\><<<
2784 if( (paths[k].length() > 0) && (paths[k].charAt(0) == '~') ){
2785 if( (paths[k].length() == 1)|| (paths[k].charAt(1) != '~') ){
2786 paths[k] = System.getProperty( "user.home" ) + paths[k].substring(1);
2787 } }
2788 if( paths[k].charAt(0) == '.' ){
2789 paths[k] = System.getProperty( "user.dir" ) + slash + paths[k];
2790 }
2791 >>>
2792
2793
2794 %%%%%%%%%%%%%%%%%%
2795 \section{Input Objects for XML Files}
2796 %%%%%%%%%%%%%%%%%%
2797
2798 The XML files my contain faults as a brute force approach is applied in
2799 which the file is scanned directly without trying to build an XML object.
2800
2801 %%%%%%%%%%%%%
2802 \subsection{Outline}
2803 %%%%%%%%%%%%%
2804
2805 %
2806 \AtEndDocument{
2807 \OutputCodE\<InputObject.java\>
2808 }
2809
2810 \AddFile{InputObject.java}{xtpipes}
2811
2812
2813 \<InputObject.java\><<<
2814 package xtpipes;
2815 /* InputObject.java (`version), generated from `jobname.tex
2816 Copyright (C) 2009-2010 TeX Users Group
2817 Copyright (C) `CopyYear.2002. Eitan M. Gurari
2818 `<TeX4ht copyright`> */
2819 `<InputObject imports`>
2820
2821 public class InputObject{
2822 `<InputObject fields`>
2823 `<public InputObject(...)`>
2824 `<java.io.InputStream getInputStream( filename )`>
2825 `<java.io.InputStream getInputStream( url )`>
2826 `<void buildProfile( boolean trace )`>
2827 public InputStream getInputStream(){ return inputStream; }
2828 public String getFilename(){
2829 return (url == null)?
2830 ( (connection == null)? filename
2831 :
2832 connection . getURL() . toString()
2833 )
2834 : url;
2835 }
2836 public String getContentType(){ return contentType; }
2837 public String getMetaType(){ return metaType; }
2838 public String getPublicId(){ return publicId; }
2839 public String getSystemId(){ return systemId; }
2840 public String getXtpipes(){ return xtpipes; }
2841 public String getRoot(){ return root; }
2842 public String getDtdRoot(){ return dtdRoot; }
2843 }
2844 >>>
2845
2846 \<InputObject fields\><<<
2847 InputStream inputStream = null;
2848 URLConnection connection = null;
2849 String filename = null;
2850 static PrintWriter log;
2851 >>>
2852
2853 \<InputObject imports\><<<
2854 import java.io.PrintWriter;
2855 import java.net.URL;
2856 import java.net.URLConnection;
2857 import java.io.ByteArrayInputStream;
2858 import java.io.File;
2859 import java.io.InputStream;
2860 >>>
2861
2862 %%%%%%%%%%%%%
2863 \subsection{Constructor}
2864 %%%%%%%%%%%%%
2865
2866
2867
2868
2869 \<public InputObject(...)\><<<
2870 public InputObject( String filename, PrintWriter log ){
2871 InputObject.log = log;
2872 filename = filename.trim();
2873 try{
2874 inputStream = getInputStream(filename);
2875 } catch (Exception exp0){
2876 if( !filename.startsWith( "http://" ) ){
2877 try{
2878 String name = "http://" + filename;
2879 inputStream = getInputStream( name );
2880 filename = name;
2881 } catch (Exception exp1){
2882 try{
2883 String name = FileInfo.cleanPath(filename);
2884 inputStream = getInputStream( name );
2885 filename = name;
2886 } catch (Exception exp2){ inputStream = null; }
2887 } } }
2888 this.filename = filename;
2889 }
2890 >>>
2891
2892 \<public InputObject(...)\><<<
2893 public InputObject( byte [] bytes, PrintWriter log ){
2894 InputObject.log = log;
2895 inputStream = new ByteArrayInputStream( bytes );
2896 }
2897 >>>
2898
2899
2900
2901 %%%%%%%%%%%%%
2902 \subsection{Stream from a File Name}
2903 %%%%%%%%%%%%%
2904
2905
2906
2907 \<java.io.InputStream getInputStream( filename )\><<<
2908 private java.io.InputStream getInputStream(
2909 String filename )
2910 throws java.io.IOException{
2911 if( filename == null ){ return null; }
2912 URL url;
2913 java.io.InputStream inputStream = null;
2914 // String loadingError = "Failed to get requested file.";
2915 try {
2916 url = new File(filename).toURI().toURL();
2917 inputStream = getInputStream( url );
2918 } catch (Exception ie) {
2919 try {
2920 url = new URL(filename);
2921 inputStream = getInputStream( url );
2922 } catch (java.io.FileNotFoundException ife) {
2923 throw new java.io.IOException(
2924 "File not found: " + filename);
2925 } catch (Exception ife) {
2926 throw new java.io.IOException(ife + "\n" + ie);
2927 } }
2928 return inputStream;
2929 }
2930 >>>
2931
2932
2933 %%%%%%%%%%%%%
2934 \subsection{Stream from a URL}
2935 %%%%%%%%%%%%%
2936
2937 \<java.io.InputStream getInputStream( url )\><<<
2938 private java.io.InputStream getInputStream( URL url )
2939 throws java.io.FileNotFoundException,
2940 java.io.IOException {
2941 java.io.InputStream inputStream = null;
2942 String errMssg = "";
2943 try{
2944 connection = null;
2945 connection = url.openConnection();
2946 connection.setRequestProperty("User-Agent",
2947 "["
2948 + System.getProperty("os.name")
2949 + " / "
2950 + System.getProperty("os.arch")
2951 + "]"
2952 + "["
2953 + System.getProperty("java.version")
2954 + " - "
2955 + System.getProperty("java.vendor")
2956 + "]"
2957
2958 );
2959 inputStream = connection.getInputStream();
2960 } catch(java.io.FileNotFoundException ve){
2961 errMssg = "File not found: " + url;
2962 throw new java.io.FileNotFoundException(
2963 "--- Ml2xml input error --- " + errMssg );
2964 } catch (javax.net.ssl.SSLHandshakeException ve){
2965 errMssg = "SSL Handshake Exception: " + ve.getMessage();
2966 throw new javax.net.ssl.SSLHandshakeException(
2967 "--- Ml2xml input error --- " + errMssg );
2968 } catch (java.net.UnknownHostException ve){
2969 errMssg = "Unknown Host Exception: " + ve.getMessage();
2970 throw new java.net.UnknownHostException(
2971 "--- Ml2xml input error --- " + errMssg );
2972 }
2973 return inputStream;
2974 }
2975 >>>
2976
2977
2978
2979 %%%%%%%%%%%%%
2980 \subsection{Clean Path}
2981 %%%%%%%%%%%%%
2982
2983
2984
2985 \<static String cleanPath( path )\><<<
2986 public static String cleanPath( String path ){
2987 String slash = System.getProperty("file.separator");
2988 String userDir = System.getProperty( "user.dir" );
2989 `<clean leading wigle`>
2990 `<clean leading dots`>
2991 `<clean internal dots`>
2992 return path;
2993 }
2994 >>>
2995
2996 \<clean leading wigle\><<<
2997 if( (path.length() > 0) && (path.charAt(0) == '~') ){
2998 if( (path.length() == 1) || (path.charAt(1) != '~') ){
2999 path = System.getProperty( "user.home" )
3000 + path.substring(1);
3001 } }
3002 >>>
3003
3004 \<clean leading dots\><<<
3005 if( path.startsWith("..") ){
3006 path = userDir.substring(0,
3007 Math.max(0,Math.max(
3008 userDir.lastIndexOf("/")
3009 ,
3010 userDir.lastIndexOf("\\")
3011 )))
3012 + path.substring(2);
3013 }
3014 if( path.startsWith(".") ){
3015 path = userDir + slash + path.substring(1);
3016 }
3017 >>>
3018
3019 \<clean internal dots\><<<
3020 int i;
3021 while(
3022 ((i=path.indexOf("/..")) != -1)
3023 ||
3024 ((i=path.indexOf("\\..")) != -1)
3025 ){
3026 String s = path.substring(0,i);
3027 int j = Math.max(s.lastIndexOf("/"), s.lastIndexOf("\\"));
3028 path = path.substring(0,j) + path.substring(i+3);
3029 }
3030 while(
3031 ((i=path.indexOf("/.")) != -1)
3032 ||
3033 ((i=path.indexOf("\\.")) != -1)
3034 ){
3035 String s = path.substring(0,i);
3036 int j = Math.max(s.indexOf("/"), s.indexOf("\\"));
3037 path = path.substring(0,j) + path.substring(i+2);
3038 }
3039 >>>
3040
3041
3042
3043 %%%%%%%%%%%%%
3044 \subsection{Profile: Connecting and Reading the Input File}
3045 %%%%%%%%%%%%%
3046
3047 \<void buildProfile( boolean trace )\><<<
3048 public void buildProfile( boolean trace ){
3049 if( trace ){
3050 log.println(
3051 "xtpipes (`version)"
3052 + "\n java.version: " + System.getProperty("java.version")
3053 + "\n java.class.path: " + System.getProperty("java.class.path")
3054 + "\n os.name: " + System.getProperty("os.name")
3055 + "\n user.home: " + System.getProperty("user.home")
3056 + "\n user.dir: " + System.getProperty("user.dir")
3057 );
3058 }
3059 if( connection != null ){
3060 `<profile info from connection`>
3061 }
3062 `<profile from preamble of file`>
3063 if( trace ){
3064 log.println(
3065 " url = " + url
3066 + "\n contentType = " + contentType
3067 + "\n publicId = " + publicId
3068 + "\n systemId = " + systemId
3069 + "\n xtpipes = " + xtpipes
3070 + "\n root = " + root
3071 + "\n dtdRoot = " + dtdRoot
3072 );
3073 } }
3074 >>>
3075
3076
3077 \<profile info from connection\><<<
3078 contentType = connection . getContentType();
3079 url = connection . getURL() . toString();
3080 >>>
3081
3082
3083
3084 \<profile from preamble of file\><<<
3085 int max = 8192;
3086 int buffSize = 4096;
3087 byte [] buff = new byte [ buffSize ];
3088 int m = 0;
3089 int length = 0;
3090 int ch;
3091 int type = `<undef type`>;
3092 String token = null;
3093 while( m < max ){
3094 try{
3095 int k = Math.min( max - m, buffSize );
3096 length = inputStream.read( buff, 0, k );
3097 if( length == -1 ){ break; }
3098 if( length == 0 ){ continue; }
3099 } catch (java.io.IOException e){
3100 System.err.println( "--- xtpipes error --- : " + e );
3101 break;
3102 }
3103 for(int i = 0 ; i < length; i++ ){
3104 `<search preamble info`>
3105 m++;
3106 } }
3107 >>>
3108
3109
3110 %%%%%%%%%%%%%
3111 \subsection{Profile: Scanning the Different Cases}
3112 %%%%%%%%%%%%%
3113
3114
3115
3116
3117 \<search preamble info\><<<
3118 switch( ch = buff[i] ){
3119 case '<': token = "";
3120 type = `<new tok`>;
3121 break;
3122 case '>': if( token != null ){
3123 token = token . replaceAll( "\\s+", " ");
3124 `<at token end`>
3125 token = null;
3126 }
3127 break;
3128 case '\n':
3129 case ' ': if( token != null ){
3130 `<at token space`>
3131 }
3132 break;
3133 case '"':
3134 case '\'': if( token == null ){ break; }
3135 `<public and system ids`>
3136 default: if( token != null ){
3137 if( type == `<pre doctype`> ){
3138 if( ch == 'D' ){
3139 type = `<doctype`>;
3140 token += (char) ch;
3141 } else { token = null; type = `<undef type`>; }
3142 }
3143 else
3144 if( token.equals("") && (type == `<new tok`>) ){
3145 `<get token type`>
3146 } else { token += (char) ch; }
3147 } }
3148 >>>
3149
3150
3151 \<public and system ids\><<<
3152 if( !token.trim().equals("") ){
3153 if( token.trim().charAt(0) == ch ){
3154 if( type == `<public id`> ){
3155 publicId = token.trim().substring(1);
3156 type = `<system id`>;
3157 token = "";
3158 break;
3159 }
3160 else if( type == `<system id`> ){
3161 systemId = token.trim().substring(1);
3162 token = null;
3163 break;
3164 }
3165 } }
3166 >>>
3167
3168
3169 \<get token type\><<<
3170 switch( ch ){
3171 case '!': type = `<pre doctype`>;
3172 break;
3173 case '?': type = `<proc instruction`> ;
3174 break;
3175 default: if( Character.isLetter(ch)
3176 && ((root == null) || (metaType == null)) ){
3177 type = `<root or meta`>;
3178 token += (char) ch;
3179 } else { token = null; }
3180 }
3181 >>>
3182
3183 \<at token end\><<<
3184 if( type == `<proc instruction`> ){
3185 if( xtpipes == null ){
3186 int n = token.length();
3187 if( (n > 1) && (token.charAt( n - 1 ) == '?')
3188 && (token.startsWith("xtpipes") ) ){
3189 String s = token . substring(7,n-1) . replaceAll( "\\s+", "");
3190 n = s.length();
3191 if( (n>6) && (s.startsWith("file="))
3192 && (s.charAt(5) == s.charAt(n-1)) ){
3193 xtpipes = s.substring(6,n-1);
3194 } } }
3195 } else if( type == `<meta`> ){
3196 if( metaType == null ){
3197 token = token . replaceAll( "\\s+", "");
3198 int k = token.indexOf("http-equiv");
3199 int n = token.indexOf("content");
3200 if( (k != -1) && (n != -1) ){
3201 if( token.length() > (Math.max(k,n)+3) ){
3202 if( token.substring(k+12).startsWith("Content-Type") ){
3203 token = token.substring(n+9);
3204 n = token.indexOf(";");
3205 if( n !=-1 ){ metaType = token.substring(0,n); }
3206 } } } }
3207 } else if( (type == `<root or meta`>) && (root == null) ){
3208 root = token;
3209 }
3210 >>>
3211
3212 \<at token space\><<<
3213 if( type == `<root or meta`> ){
3214 if( token.equals("meta") ){
3215 if( metaType == null ){
3216 type = `<meta`>;
3217 token = " ";
3218 } else {
3219 token = null;
3220 }
3221 } else {
3222 if( root == null ){
3223 root = token;
3224 }
3225 token = null;
3226 }
3227 } else if( type == `<doctype`> ){
3228 if( token.equals("DOCTYPE") ){
3229 type = `<doctype root`>;
3230 token = " ";
3231 } else { token = null; }
3232 } else if( type == `<doctype root`> ){
3233 if( !token.trim().equals("") ){
3234 dtdRoot = token.trim();
3235 token = " ";
3236 type = `<doctype id`>;
3237 } else { token = null; }
3238 } else if( type == `<doctype id`> ){
3239 if( !token.trim().equals("") ){
3240 token = token.trim();
3241 if( token.equals("PUBLIC") ){
3242 type = `<public id`>;
3243 token = "";
3244 } else if( token.equals("SYSTEM") ){
3245 type = `<system id`>;
3246 token = "";
3247 } else { token = null; }
3248 }
3249 } else { token += ' '; }
3250 >>>
3251
3252
3253 \<InputObject fields\><<<
3254 String dtdRoot = null,
3255 publicId = null,
3256 systemId = null,
3257 xtpipes = null,
3258 url = null,
3259 metaType = null,
3260 contentType = null,
3261 root = null;
3262 >>>
3263
3264 \OP{undef type}
3265 \OP{new tok}
3266 \OP{root or meta}
3267 \OP{pre doctype}
3268 \OP{doctype}
3269 \OP{doctype root}
3270 \OP{doctype id}
3271 \OP{public id}
3272 \OP{system id}
3273 \OP{proc instruction}
3274 \OP{proc root}
3275 \OP{meta}
3276
3277
3278 %%%%%%%%%%%%%%%%%%
3279 \section{Input Objects for XML Strings}
3280 %%%%%%%%%%%%%%%%%%
3281
3282
3283
3284 %%%%%%%%%%%%%
3285 \subsection{Search String for Indirection}
3286 %%%%%%%%%%%%%
3287
3288
3289 \<search string for xtpipes instruction\><<<
3290 scriptFile = inputObject.getXtpipes();
3291 rootName = inputObject.getRoot();
3292 needScript = true;
3293 >>>
3294
3295
3296 Remove XtPipesSearch!!!!!!!!!!!!!!
3297
3298 \<\><<<
3299 try{
3300 `<get sax reader`>
3301 saxReader.setContentHandler( new XtPipesSearch() );
3302 `<body of search string for xtpipes instruction`>
3303 saxReaderStack.push( saxReader );
3304 } catch(Exception e){
3305 e.printStackTrace();
3306 instructionErr( node, errMsg + e.toString(), 13 );
3307 }
3308 >>>
3309
3310 \<body of search string for xtpipes instruction\><<<
3311 errMsg = "Searching <?xtpipes file=\"...\"?> in "
3312 + inData.substring(0, Math.min(70,inData.length()))
3313 + "... : ";
3314 byte [] bytes = inData.getBytes("UTF-8");
3315 ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
3316 InputSource is = new InputSource( bais );
3317 saxReader.parse(is);
3318 >>>
3319
3320 %%%%%%%%%%%%%
3321 \subsection{The Search Engine}
3322 %%%%%%%%%%%%%
3323
3324
3325
3326 \<xtpipes fields DELETED\><<<
3327 private static class XtPipesSearch extends DefaultHandler {
3328 public void endElement(String uri,
3329 String localName, String qName){
3330 `<extract root element name`>
3331 }
3332 public void processingInstruction(String target, String attrs) {
3333 if( !needScript && target.equals("xtpipes") ){
3334 `<extract script file name`>
3335 } } }
3336 >>>
3337
3338
3339 The input file is
3340 searched for an alternative script within a processing instruction of
3341 the form \verb+<?xtpipes file="..." ?>+.
3342
3343
3344 \<extract root element name\><<<
3345 rootName = qName;
3346 >>>
3347
3348
3349 \<extract script file name\><<<
3350 try {
3351 `<get sax reader`>
3352 saxReader.setContentHandler(new DefaultHandler() {
3353 public void startElement(String uri, String localName,
3354 String qName, Attributes atts) {
3355 String filename = atts.getValue("file");
3356 if( filename != null ){
3357 scriptFile = filename;
3358 `<show script file name in log file`>
3359 needScript = true;
3360 } }
3361 });
3362 String str = "<xtpipes " + attrs + "/>";
3363 StringReader reader = new StringReader(str);
3364 InputSource in = new InputSource(reader);
3365 saxReader.parse(in);
3366 saxReaderStack.push( saxReader );
3367 } catch(Exception e){
3368 System.err.println( "--- Error 10 --- " + e );
3369 }
3370 >>>
3371
3372
3373
3374
3375
3376
3377
3378 \<xtpipes fields\><<<
3379 private static String rootName;
3380 >>>
3381
3382
3383 \<init fields\><<<
3384 rootName = null;
3385 >>>
3386
3387
3388
3389
3390 %%%%%%%%%%%%%%%%%%
3391 \section{Information About the Transformation}
3392 %%%%%%%%%%%%%%%%%%
3393
3394 %%%%%%%%%%%%%
3395 \subsection{User's System}
3396 %%%%%%%%%%%%%
3397
3398
3399
3400 \<output system info\><<<
3401 logWriter.println(
3402 "xtpipes (`version)"
3403 + "\n java.version: " + System.getProperty("java.version")
3404 + "\n java.class.path: " + System.getProperty("java.class.path")
3405 + "\n os.name: " + System.getProperty("os.name")
3406 + "\n user.home: " + System.getProperty("user.home")
3407 + "\n user.dir: " + System.getProperty("user.dir")
3408 );
3409 for( int k=0; k<args.length; k++ ){
3410 logWriter.println( " " + args[k] );
3411 }
3412 >>>
3413
3414 %%%%%%%%%%%%%
3415 \subsection{Script to be Used}
3416 %%%%%%%%%%%%%
3417
3418
3419 \<show script file name in log file\><<<
3420 if( messages ){
3421 logWriter.println(
3422 "Requesting XtPipes script file: "
3423 + filename );
3424 }
3425 >>>
3426
3427
3428 %%%%%%%%%%%%%
3429 \subsection{Preamble Attribute}
3430 %%%%%%%%%%%%%
3431
3432 \<preamble output into log\><<<
3433 if ( (attr != null) && messages ) {
3434 logWriter.println( attr.getNodeValue() );
3435 }
3436 >>>
3437
3438
3439
3440 %%%%%%%%%%%%%
3441 \subsection{Tracing}
3442 %%%%%%%%%%%%%
3443
3444
3445 \<xtpipes fields\><<<
3446 static boolean trace;
3447 >>>
3448
3449 \<init fields\><<<
3450 trace = false;
3451 >>>
3452
3453
3454
3455 \<trace element\><<<
3456 if( trace ){
3457 logWriter.print( "[##] = xtpipes => " + instruction );
3458 if( node.hasAttributes() ){
3459 NamedNodeMap attributes = node.getAttributes();
3460 for(int i=0; i < attributes.getLength(); i++ ){
3461 Node attr = attributes.item(i);
3462 logWriter.print( " " + attr.getNodeName()
3463 + "=\"" + attr.getNodeValue() + "\"" );
3464 } }
3465 logWriter.println(); logWriter.flush();
3466 }
3467 >>>
3468
3469 \<trace if true\><<<
3470 if( trace ){
3471 logWriter.print( "--> true" );
3472 }
3473 >>>
3474
3475 \<trace if false\><<<
3476 if( trace ){
3477 logWriter.print( "--> true" );
3478 }
3479 >>>
3480
3481
3482 \<trace open script\><<<
3483 if( trace ){
3484 logWriter.println( "(" + scriptFile + ")" );
3485 }
3486 >>>
3487
3488
3489
3490 %%%%%%%%%%%%%%%%%%
3491 \section{loose Ends}
3492 %%%%%%%%%%%%%%%%%%
3493
3494 %%%%%%%%%%%%%%%%%%
3495 \subsection{Fix XML Defaults}
3496 %%%%%%%%%%%%%%%%%%
3497
3498 \<xtpipes fields\><<<
3499 private static String [] ml2xml = null;
3500 static Class<?> ml2xmlClassObj = null;
3501 >>>
3502
3503 \<scan ml2xml argument\><<<
3504 if( args[n].substring(2).equals("") ){
3505 if( ml2xml == null ){ ml2xml = new String[0]; }
3506 } else {
3507 if( ml2xml == null ){
3508 ml2xml = new String[1];
3509 } else {
3510 String [] m2x = new String [ml2xml.length + 1];
3511 for(int cnt=0; cnt < ml2xml.length; cnt++){
3512 m2x[cnt] = ml2xml[cnt];
3513 }
3514 ml2xml = m2x;
3515 }
3516 ml2xml[ ml2xml.length - 1 ] = args[n].substring(2);
3517 }
3518 >>>
3519
3520
3521 \<inputStream := (InputStream) new Ml2xml(filename, "foo.m2x")\><<<
3522 try{
3523 ml2xmlClassObj = Class.forName( "ml2xml.Ml2xml" );
3524 } catch (java.lang.ClassNotFoundException cnf ){
3525 instructionErr( null, "Class not found: ml2xml.Ml2xml", 25 );
3526 }
3527 Class<?> [] argTyp = { String.class, String[].class };
3528 Constructor<?> con = ml2xmlClassObj.getConstructor( argTyp );
3529 try{
3530 `<trace call to ml2xml`>
3531 inputStream = (InputStream) con.newInstance(
3532 new Object[]{xml, ml2xml}
3533 );
3534 } catch(java.lang.reflect.InvocationTargetException ite){
3535 String s = "Problem at: ml2xml.Ml2xml(" + xml + ","
3536 + "new String[]{" ;
3537 for(int i=0; i < Xtpipes.ml2xml.length; i++){
3538 s += ((i==0)? "\"" : ", \"") + Xtpipes.ml2xml[i] + "\"";
3539 }
3540 s += "})";
3541 instructionErr( null, s + "; " + ite.getCause(), 38);
3542 }
3543 >>>
3544
3545 ite.getTargetException().printStackTrace();
3546
3547
3548 \<Ml2xml close files\><<<
3549 if( Xtpipes.ml2xml != null ){
3550 Class<?> [] argTyp = {};
3551 Method m = ml2xmlClassObj . getMethod( "closeFiles", argTyp );
3552 m.invoke( null, new Object[0] );
3553 }
3554 >>>
3555
3556 \<trace call to ml2xml\><<<
3557 if( Xtpipes.trace ){
3558 String s = "Calling: ml2xml.Ml2xml(inputStream,"
3559 + "new String[]{" ;
3560 for(int i=0; i < Xtpipes.ml2xml.length; i++){
3561 s += ((i==0)? "\"" : ", \"") + Xtpipes.ml2xml[i] + "\"";
3562 }
3563 s += "})";
3564 Xtpipes.logWriter.println( s );
3565 }
3566 >>>
3567
3568
3569 \<close ml2xml files\><<<
3570 if( ml2xmlClassObj != null ){
3571 Class<?> [] argTypes = { };
3572 Method m = ml2xmlClassObj.getMethod( "closeFiles", argTypes );
3573 Object parmValues[] = new Object[0];
3574 m.invoke( null, parmValues );
3575 }
3576 >>>
3577
3578
3579 \<xtpipes imports\><<<
3580 import java.lang.reflect.Constructor;
3581 >>>
3582
3583 Ml2xml is referenced through reflection instead of directly so that xtpipes can
3584 be delivered also without that utility, e.g., for tex4ht where no treatment of faulty
3585 XML file is to be done. In fact, this approach can be generalized to offer
3586 arbitrary filter for the input.
3587
3588
3589
3590
3591 %%%%%%%%%%%%%%%%%%
3592 \subsection{Unicode Filter}
3593 %%%%%%%%%%%%%%%%%%
3594
3595 Non-ASCII characters are translated into unicode hexadecimal entities.
3596 The same holds for ascii characters listed within the filter.
3597
3598 \AtEndDocument{
3599 \OutputCodE\<XtpipesUni.java\>
3600 }
3601 \AddFile{XtpipesUni.java}{xtpipes}
3602
3603
3604 \<XtpipesUni.java\><<<
3605 /* XtpipesUni.java (`version), generated from `jobname.tex
3606 Copyright (C) 2009-2010 TeX Users Group
3607 Copyright (C) `CopyYear.2002. Eitan M. Gurari
3608 `<TeX4ht copyright`> */
3609 package xtpipes;
3610 public class XtpipesUni{
3611 `<String toUni( char[], start, length, filter )`>
3612 `<String toUni( String, filter )`>
3613 }
3614 >>>
3615
3616 \<String toUni( char[], start, length, filter )\><<<
3617 private static int D800 = Integer.parseInt("D800", 16);
3618 private static int DFFF = Integer.parseInt("DFFF", 16);
3619 private static int DC00 = Integer.parseInt("DC00", 16);
3620 private static int X400 = Integer.parseInt("400",16);
3621 private static int X10000 = Integer.parseInt("10000",16);
3622
3623
3624 public static String toUni( char[] ch, int start, int length,
3625 String filter ){
3626 StringBuffer buf = new StringBuffer(length);
3627 for (int i = 0; i < length; i++) {
3628 int chr = ch[ start + i ];
3629 boolean ascii = (chr == '\n')
3630 || (chr > 31) && (chr < 127) ;
3631 if( filter.indexOf(chr) > -1 ){ ascii = false; }
3632
3633 if( (chr >= D800) && (chr<= DFFF) ){
3634 chr = ((ch[i] - D800) * X400 + (ch[++i] - DC00)) + X10000;
3635 }
3636
3637
3638 buf.append(
3639 ascii ? Character.toString((char) chr)
3640 : ("&#x"
3641 + Integer.toHexString(chr).toUpperCase()
3642 + ";" ) );
3643 }
3644 return new String(buf);
3645 }
3646 >>>
3647
3648 \<String toUni( String, filter )\><<<
3649 public static String toUni( String s, String filter ){
3650 char [] ch = s.toCharArray();
3651 int length = ch.length;
3652 return toUni(ch, 0, length, filter);
3653 }
3654 >>>
3655
3656
3657
3658
3659
3660
3661
3662 %%%%%%%%%%%%%
3663 \subsection{Error Messagesg}
3664 %%%%%%%%%%%%%
3665
3666
3667
3668
3669
3670
3671 \<static void instructionErr(...)\><<<
3672 private static void instructionErr( Node node, String e, int num )
3673 throws Exception {
3674 String err = "--- xtpipes error " + num + " --- ";
3675 if( node != null ){
3676 err += "At <" + node.getNodeName();
3677 NamedNodeMap attr = node.getAttributes();
3678 for(int i=0; i<attr.getLength(); i++){
3679 Node nd = attr.item(i);
3680 err += " " +
3681 nd.getNodeName() + "=\"" +
3682 nd.getNodeValue() + "\"" ;
3683 }
3684 err += " > : " ;
3685 }
3686 err += e;
3687 `<close ml2xml files`>
3688 Xtpipes.logWriter.flush();
3689 if( exceptionErrs ) { throw new Exception( err ); }
3690 else {
3691 System.err.println( err );
3692 System.exit(1);
3693 }
3694 }
3695 >>>
3696
3697
3698
3699 \<static void instructionErr(...)\><<<
3700 private static void instructionErr( Node node, String e,
3701 StackTraceElement[] st, int num )
3702 throws Exception {
3703 Xtpipes.logWriter.println(
3704 "--- xtpipes error " + num + " --- " + e
3705 );
3706 for(int i=st.length-1; i>=0; i-- ){
3707 Xtpipes.logWriter.println( st[i].toString() );
3708 }
3709 instructionErr( node, e, num );
3710 }
3711 >>>
3712
3713
3714
3715
3716 \<new ErrorHandler()\><<<
3717 new ErrorHandler() {
3718 public void warning(SAXParseException e) throws SAXParseException {
3719 showSpecifics("warning",e);
3720 }
3721 public void error(SAXParseException e) throws SAXParseException {
3722 showSpecifics("error",e);
3723 }
3724 public void fatalError(SAXParseException e) throws SAXParseException {
3725 showSpecifics("fatal error",e);
3726 }
3727 public void showSpecifics(String s, SAXParseException e)
3728 throws SAXParseException {
3729 String err = "--- xtpipes " + s + " 24 --- " + e.getSystemId()
3730 + " line " + e.getLineNumber()
3731 + " col " + e.getColumnNumber()
3732 + " : " + e.getMessage() ;
3733 if( exceptionErrs ) { throw new SAXParseException(
3734 err, (org.xml.sax.Locator) null ); }
3735 else {
3736 System.err.println( err );
3737 System.exit(1);
3738 } } }
3739 >>>
3740
3741
3742
3743
3744
3745 The follower listeners catch errors but their messages are not
3746 delivered through the call to the new exceptions (why?). The field
3747 errMssg is used so that error 16 will produce the same error messages.
3748
3749 \begin{description}
3750 \item[Catches errors in the XSLT file]
3751
3752
3753
3754 \<transformer factory XSLT error listener\><<<
3755 new ErrorListener() {
3756 public void warning(TransformerException e) throws TransformerException {
3757 showSpecifics(e);
3758 }
3759 public void error(TransformerException e) throws TransformerException {
3760 showSpecifics(e);
3761 }
3762 public void fatalError(TransformerException e) throws TransformerException {
3763 showSpecifics(e);
3764 }
3765 void showSpecifics(TransformerException e)
3766 throws TransformerException{
3767 String err = e.getMessage() ;
3768 String loc = e.getLocationAsString();
3769 if( loc != null ){ err = loc + ": " + err; }
3770 err = "XSL stylesheet problem: " + err;
3771 if( errMssg == null ){ errMssg = err; }
3772 throw new TransformerException(err);
3773 } }
3774 >>>
3775
3776
3777 \item [Catches errors in the XML file]
3778
3779 \<transformer XML error listener\><<<
3780 new ErrorListener() {
3781 public void warning(TransformerException e) throws TransformerException {
3782 showSpecifics(e);
3783 }
3784 public void error(TransformerException e) throws TransformerException {
3785 showSpecifics(e);
3786 }
3787 public void fatalError(TransformerException e) throws TransformerException {
3788 showSpecifics(e);
3789 }
3790 void showSpecifics(TransformerException e)
3791 throws TransformerException{
3792 String err = e.getMessage() ;
3793 String loc = e.getLocationAsString();
3794 if( loc != null ){ err = loc + ": " + err; }
3795 if( errMssg == null ){ errMssg = err; }
3796 err = "XML document prblem: " + err;
3797 throw new TransformerException(err);
3798 } }
3799 >>>
3800
3801
3802 \<identity transformer XML error listener\><<<
3803 new ErrorListener() {
3804 public void warning(TransformerException e) throws TransformerException {
3805 showSpecifics(e);
3806 }
3807 public void error(TransformerException e) throws TransformerException {
3808 showSpecifics(e);
3809 }
3810 public void fatalError(TransformerException e) throws TransformerException {
3811 showSpecifics(e);
3812 }
3813 void showSpecifics(TransformerException e)
3814 throws TransformerException{
3815 String err = e.getMessage() ;
3816 String loc = e.getLocationAsString();
3817 if( loc != null ){ err = loc + ": " + err; }
3818 throw new TransformerException(err);
3819 } }
3820 >>>
3821
3822
3823
3824 \end{description}
3825
3826
3827 \<xtpipes fields\><<<
3828 public static String errMssg;
3829 >>>
3830
3831 %%%%%%%%%%%%%%%%%%
3832 \section{Serialize Dom}
3833 %%%%%%%%%%%%%%%%%%
3834
3835
3836 \<static String serialize( dom )\><<<
3837 static String serialize( Node root ){
3838 if( root.getNodeType() == Node.TEXT_NODE) {
3839 return root.getNodeValue();
3840 }
3841 if( root.getNodeType() == Node.ELEMENT_NODE) {
3842 String ser = "";
3843 String tagName = root.getNodeName();
3844 ser += "<" + tagName;
3845 `<res += serialize attributes`>
3846 ser += "\n>";
3847 `<res += serialize children`>
3848 ser += "</" + tagName + ">";
3849 return ser;
3850 }
3851 if( root.getNodeType() == Node.DOCUMENT_NODE) {
3852 String ser = "";
3853 `<res += serialize children`>
3854 return ser;
3855 }
3856 if( root == null ){ return "null"; }
3857 return "";
3858 }
3859 >>>
3860
3861 \<res += serialize children\><<<
3862 NodeList children = root.getChildNodes();
3863 if(children.getLength() > 0) {
3864 for(int i = 0; i < children.getLength(); i++) {
3865 ser += serialize(children.item(i));
3866 } }
3867 >>>
3868
3869 \<res += serialize attributes\><<<
3870 NamedNodeMap attributes = root.getAttributes();
3871 for(int i = 0; i < attributes.getLength(); i++) {
3872 Attr attribute = (Attr) attributes.item(i);
3873 ser += "\n" + attribute.getName() + "=\""
3874 + attribute.getValue() + "\" ";
3875 }
3876 >>>
3877
3878
3879
3880
3881 %%%%%%%%%%%%%
3882 \subsection{Clean Xmlns}
3883 %%%%%%%%%%%%%
3884
3885
3886 \<static void cleanXmlns( dom )\><<<
3887 static ArrayList<String> nsName, nsValue;
3888 static void cleanXmlns( Node root ){
3889 if( root.getNodeType() == Node.ELEMENT_NODE) {
3890 int top = nsName.size();
3891 `<clean xmlns attributes`>
3892 `<clean xmlns in children`>
3893 for(int i=nsName.size(); i>top; ){
3894 i--;
3895 nsName.remove(i);
3896 nsValue.remove(i);
3897 }
3898 } else if( root.getNodeType() == Node.DOCUMENT_NODE) {
3899 nsName = new ArrayList<String>();
3900 nsValue = new ArrayList<String>();
3901 `<clean xmlns in children`>
3902 nsName = null;
3903 nsValue = null;
3904 } }
3905 >>>
3906
3907
3908
3909 \<clean xmlns in children\><<<
3910 NodeList children = root.getChildNodes();
3911 if(children.getLength() > 0) {
3912 for(int i = 0; i < children.getLength(); i++) {
3913 cleanXmlns(children.item(i));
3914 } }
3915 >>>
3916
3917 \<clean xmlns attributes\><<<
3918 ArrayList<Attr> remove = new ArrayList<Attr>();
3919 NamedNodeMap attributes = root.getAttributes();
3920 for(int i = 0; i < attributes.getLength(); i++) {
3921 Attr attribute = (Attr) attributes.item(i);
3922 String name = attribute.getName();
3923 if( name.startsWith("xmlns") ){
3924 if( (name.length() == 5) || (name.charAt(5) == ':') ){
3925 String value = attribute.getValue();
3926 `<bool := xmlns active?`>
3927 if( bool ){ remove.add(attribute);
3928 } else { nsName.add(name); nsValue.add(value); }
3929 } } }
3930 for(int i=remove.size(); i>0; ){
3931 i--;
3932 ((Element) root).removeAttributeNode( (Attr) remove.get(i) );
3933 }
3934 remove = null;
3935 >>>
3936
3937 \<bool := xmlns active?\><<<
3938 boolean bool = false;
3939 for(int k=nsName.size(); k>0; ){
3940 k--;
3941 if( ((String) nsName.get(k)) . equals(name) ){
3942 bool = ((String) nsValue.get(k)) . equals(value);
3943 break;
3944 } }
3945 >>>
3946
3947 \<xtpipes imports\><<<
3948 import java.util.ArrayList;
3949 >>>
3950
3951
3952
3953 %%%%%%%%%%%%%%%%%%
3954 \subsection{Default Script}
3955 %%%%%%%%%%%%%%%%%%
3956
3957 \AtEndDocument{
3958 \OutputCodE\<xtpipes-default.4xt\>
3959 }
3960 \expandafter\AddFile\BIN{xtpipes-default.4xt}{xtpipes\Slash lib}
3961
3962 \<xtpipes-default.4xt\><<<
3963 <?xml version="1.0" encoding="UTF-8" ?>
3964 <!DOCTYPE xtpipes PUBLIC "-//GURARI//DTD xtpipes//EN" "xtpipes.dtd" >
3965 <!-- xtpipes-default.4xt (`version), generated from `jobname.tex
3966 Copyright (C) 2009-2010 TeX Users Group
3967 Copyright (C) `CopyYear.2002. Eitan M. Gurari
3968 `<TeX4ht copyright`> -->
3969 <xtpipes />
3970 >>>
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983 %%%%%%%%%%%%%%%%%%
3984 \part{Useful Pre Fabricated Modules}
3985 %%%%%%%%%%%%%%%%%%
3986
3987
3988
3989
3990 %%%%%%%%%%%%%
3991 \section{ScriptsManager: A Content Handler}
3992 %%%%%%%%%%%%%
3993
3994 \label{ScriptsManager}
3995
3996
3997 %%%%%%%%%%%%%
3998 \subsection{Outline}
3999 %%%%%%%%%%%%%
4000
4001 \AtEndDocument{
4002 \OutputCodE\<ScriptsManager.java\>
4003 }
4004 \AddFile{ScriptsManager.java}{xtpipes\Slash util}
4005
4006 \<ScriptsManager.java\><<<
4007 /* ScriptsManager.java (`version), generated from `jobname.tex
4008 Copyright (C) 2009-2010 TeX Users Group
4009 Copyright (C) `CopyYear.2002. Eitan M. Gurari
4010 `<TeX4ht copyright`> */
4011 package xtpipes.util;
4012 `<ScriptsManager imports`>
4013 public class ScriptsManager extends DefaultHandler {
4014 `<ScriptsManager fields`>
4015 PrintWriter out = null, log = null;
4016 HashMap<String,Object> scripts = null;
4017 Method method = null;
4018 boolean savemode=false;
4019 String code="", match = null;
4020 Stack<Object[]> stack = new Stack<Object[]>();
4021 public ScriptsManager( PrintWriter out,
4022 HashMap<String,Object> scripts,
4023 Method method,
4024 PrintWriter log, boolean trace ){
4025 this.out = out;
4026 this.log = (log==null)? new PrintWriter( System.err ) : log;
4027 this.scripts = scripts;
4028 this.method = method;
4029 }
4030 public void characters(char[] ch, int start, int length){
4031 add( XtpipesUni.toUni(ch, start, length, "<>&") );
4032 }
4033 `<ScriptsManager: void startElement(ns, sName, qName, atts)`>
4034 `<ScriptsManager: void endElement(ns, sName, qName)`>
4035 protected void add(String s){
4036 if( savemode ){ code+=s; }
4037 else { out.print(s); }
4038 } }
4039 >>>
4040
4041
4042 \<ScriptsManager imports\><<<
4043 import org.xml.sax.helpers.DefaultHandler;
4044 import org.xml.sax.*;
4045 import java.io.*;
4046 import java.lang.reflect.*;
4047 import java.util.HashMap;
4048 import java.util.Stack;
4049 >>>
4050
4051 %%%%%%%%%%%%%
4052 \subsection{Start Elements}
4053 %%%%%%%%%%%%%
4054
4055
4056
4057
4058 \<ScriptsManager: void startElement(ns, sName, qName, atts)\><<<
4059 public void startElement(String ns, String sName,
4060 String qName, Attributes atts) {
4061 `<save status of xmlns above element`>
4062 `<flag := start new save?`>
4063 inBody = true;
4064 String s = "<" + qName + "\n";
4065 for(int i=0; i<atts.getLength(); i++ ){
4066 String name = atts.getQName(i),
4067 value = atts.getValue(i);
4068 `<record xmlns`>
4069 s += " " + name + "=\"" +
4070 XtpipesUni.toUni(value, "<>&\"") + "\"";
4071 }
4072 if( flag ){ `<add missing xmlns attributes`> }
4073 s += ">" ;
4074 `<set start element`>
4075 }
4076 >>>
4077
4078
4079 \<ScriptsManager fields\><<<
4080 boolean inBody = false;
4081 >>>
4082
4083
4084 \<flag := start new save?\><<<
4085 String key = (atts==null)?
4086 null
4087 : (qName + "::" + atts.getValue("class"));
4088 boolean flag = (key != null) && scripts.containsKey(key);
4089
4090 if( !flag ){
4091 key = qName;
4092 flag = scripts.containsKey(key);
4093 }
4094 >>>
4095
4096 \<set start element\><<<
4097 if( flag ){
4098 Object [] state = { Boolean.valueOf(savemode), code, match };
4099 stack.push( state );
4100 savemode=true; code=""; match= key;
4101 } else {
4102 Object [] state = { Boolean.valueOf(savemode), null, null };
4103 stack.push( state );
4104 }
4105 add( s );
4106 >>>
4107
4108 The parsing of an XML string is similar to that of done by a
4109 left-to-right bottom up parser of a programming language.
4110 Specifically, the token are read and send on to the output stream,
4111 until an element whose name appears in the hash table of scripts is
4112 encountered. When such an element is encountered, its body is
4113 assembled and the corresponding script is applied on the body. The
4114 processing might be recursive, in the sense that enclosed elements
4115 might also have scripts to process them.
4116
4117 The above applies also to an element name concatenated with its class
4118 attribute value, with the substring `::' as a separator.
4119
4120 %%%%%%%%%%%%%
4121 \subsection{End Elements}
4122 %%%%%%%%%%%%%
4123
4124
4125
4126 \<ScriptsManager: void endElement(ns, sName, qName)\><<<
4127 public void endElement(String ns, String sName, String qName){
4128 String s = "</" + qName + ">";
4129 add( s );
4130 Object [] state = (Object []) stack.pop();
4131 if( (String) state[1] != null ){
4132 `<s := invoke script`>
4133 `<set end element`>
4134 `<recall status of xmlns above element`>
4135 if( !s.equals("") ){
4136 `<remove xmlns attributes supported from above`>
4137 add( s );
4138 }
4139 } else { `<recall status of xmlns above element`> }
4140 }
4141 >>>
4142
4143
4144
4145
4146
4147
4148
4149 \<s := invoke script\><<<
4150 Object parmValues[] = new Object[2];
4151 parmValues[0] = scripts.get( match );
4152 parmValues[1] = code;
4153 try {
4154 s = (String) method.invoke( null, parmValues );
4155 } catch(java.lang.reflect.InvocationTargetException e){
4156 log.println("--- ScriptsManager Error 1 --- " + e.getCause() );
4157 log.flush();
4158 } catch (Exception e){
4159 log.println("--- ScriptsManager Error 2 --- " + e );
4160 log.flush();
4161 }
4162 >>>
4163
4164
4165 Can't invoke exception above.
4166
4167 \<set end element\><<<
4168 savemode = ((Boolean) state[0]).booleanValue();
4169 code = (String) state[1];
4170 match = (String) state[2];
4171 >>>
4172
4173
4174
4175
4176 %%%%%%%%%%%%%
4177 \subsection{Name Spaces at Start of Elements}
4178 %%%%%%%%%%%%%
4179
4180 \<record xmlns\><<<
4181 if( name.startsWith("xmlns") ){
4182 if( (name.length() == 5) || (name.charAt(5) == ':') ){
4183 `<bool := xmlns active?`>
4184 if( !bool ){
4185 nsName.add(name); nsValue.add(value);
4186 } } }
4187 >>>
4188
4189
4190
4191
4192
4193 \<add missing xmlns attributes\><<<
4194 HashSet<String> registry = new HashSet<String>();
4195 for(int i=nsName.size(); i>top; ){
4196 i--;
4197 registry.add( (String) nsName.get(i) );
4198 }
4199 for(int i=top; i>0; ){
4200 i--;
4201 String nm = (String) nsName.get(i);
4202 if( ! registry.contains(nm) ){
4203 registry.add( nm );
4204 s += " " + nm + "=\"" +
4205 XtpipesUni.toUni( (String) nsValue.get(i), "<>&\"") + "\"";
4206 } }
4207 >>>
4208
4209
4210
4211
4212 \<ScriptsManager fields\><<<
4213 ArrayList<String> nsName = new ArrayList<String>(),
4214 nsValue = new ArrayList<String>();
4215 Stack<Integer> nsStack = new Stack<Integer>();
4216 >>>
4217
4218 \<ScriptsManager imports\><<<
4219 import java.util.ArrayList;
4220 import java.util.HashSet;
4221 import xtpipes.XtpipesUni;
4222 >>>
4223
4224
4225 %%%%%%%%%%%%%
4226 \subsection{Name Spaces at End of Elements}
4227 %%%%%%%%%%%%%
4228
4229
4230 \<remove xmlns attributes supported from above\><<<
4231 int m = s.indexOf('>');
4232 char [] attrs = s.substring(0,m).toCharArray();
4233 int result = qName.length()+1,
4234 mark = result,
4235 from=-1,
4236 control = `<xmlns name`>;
4237 char delimiter = ' ';
4238 String name="";
4239 for(int i=result; i<m; i++ ){
4240 attrs[result++] = attrs[i];
4241 switch( control ){
4242 case `<xmlns name`>: { `<insert attribute name`> break; }
4243 case `<xmlns quote`>: { `<insert attribute quote`> break; }
4244 case `<xmlns value`>: { `<insert attribute value`> break; }
4245 } }
4246 s = (new String(attrs,0, Math.min(result,attrs.length)))
4247 + s.substring(m);
4248 >>>
4249
4250
4251
4252 \<insert attribute name\><<<
4253 if( attrs[i] == '=' ){
4254 name = (new String(attrs,mark,result-mark-1)).trim();
4255 control = `<xmlns quote`>;
4256 }
4257 >>>
4258
4259 \<insert attribute quote\><<<
4260 if( (attrs[i] == '"') || (attrs[i] == '\'') ){
4261 delimiter = attrs[i];
4262 control = `<xmlns value`>;
4263 from = result;
4264 }
4265 >>>
4266
4267 \<insert attribute value\><<<
4268 if( attrs[i] == delimiter ){
4269 if( name.startsWith("xmlns")
4270 && ((name.length() == 5) || (name.charAt(5) == ':')) ){
4271 String value = (new String(attrs,from,result-from-1)).trim();
4272 `<bool := xmlns active?`>
4273 if( bool ){ result = mark; }
4274 }
4275 mark = result;
4276 control = `<xmlns name`>;
4277 }
4278 >>>
4279
4280
4281
4282 %%%%%%%%%%%%%
4283 \subsection{Name Spaces Inheritence}
4284 %%%%%%%%%%%%%
4285
4286
4287
4288
4289
4290 \<save status of xmlns above element\><<<
4291 int top = nsName.size();
4292 nsStack.push( Integer.valueOf(top) );
4293 >>>
4294
4295 \<recall status of xmlns above element\><<<
4296 int top = ((Integer) nsStack.pop()) . intValue();
4297 for(int i=nsName.size(); i>top; ){
4298 i--;
4299 nsName.remove(i);
4300 nsValue.remove(i);
4301 }
4302 >>>
4303
4304
4305
4306
4307
4308 \OP{xmlns name}
4309 \OP{xmlns quote}
4310 \OP{xmlns value}
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323 %%%%%%%%%%%%%%%%%%
4324 \section{ScriptsManagerLH: A Lexical Handler}
4325 %%%%%%%%%%%%%%%%%%
4326
4327 \label{ScriptsManagerLH}
4328
4329 The lexical handler sends its strings to the content hadler.
4330
4331 \AtEndDocument{
4332 \OutputCodE\<ScriptsManagerLH.java\>
4333 }
4334 \AddFile{ScriptsManagerLH.java}{xtpipes\Slash util}
4335
4336 \<ScriptsManagerLH.java\><<<
4337 /* ScriptsManagerLH.java (`version), generated from `jobname.tex
4338 Copyright (C) 2009-2010 TeX Users Group
4339 Copyright (C) `CopyYear.2002. Eitan M. Gurari
4340 `<TeX4ht copyright`> */
4341 package xtpipes.util;
4342 import org.xml.sax.ext.LexicalHandler;
4343 // import org.xml.sax.ContentHandler;
4344 import java.io.PrintWriter;
4345 public class ScriptsManagerLH implements LexicalHandler {
4346 ScriptsManager contentHandler;
4347 PrintWriter log;
4348 public ScriptsManagerLH( ScriptsManager contentHandler,
4349 PrintWriter log, boolean trace ){
4350 this.contentHandler = contentHandler;
4351 this.log = (log==null)? new PrintWriter( System.err ) : log;
4352 }
4353 public void comment(char[] ch, int start, int length){
4354 if( contentHandler.inBody ){
4355 String s = new String(ch, start, length);
4356 contentHandler.add( "<!--" + s + "\n-->");
4357 } }
4358 public void startEntity(String x){}
4359 public void endEntity(String x){}
4360 public void startCDATA(){}
4361 public void endCDATA(){}
4362 public void startDTD(String x, String y, String z){}
4363 public void endDTD(){}
4364 }
4365 >>>
4366
4367 \begin{itemize}
4368 \item
4369 The line breaks in the comments are to avoid sequences of comments
4370 loosing their intermediate line breaks and as a result causing
4371 overflow of buffers.
4372
4373 \item The comments in the preamble are included through the
4374 preamble pattribute of xtpipes.
4375 \end{itemize}
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387 %%%%%%%%%%%%%%%%%%%%%%%
4388 \begin{thebibliography}{10}
4389 \bibitem{ref}
4390 {\sl The Reflection API},
4391 Tutorial, Sun Microsystems,
4392 \url{http://java.sun.com/docs/books/tutorial/reflect/TOC.html}.
4393 \end{thebibliography}
4394
4395
4396
4397
4398 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4399
4400 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4401 \ifOption{win}
4402 {
4403 \AtEndDocument{
4404 \OutputCodE\<dodoc.bat\>
4405 \Needs{"dodoc"}
4406 }
4407 }
4408 { \ifOption{doc}{
4409 \AtEndDocument{\Needs{"
4410 mkdir -p doc.dir
4411 ;
4412 cd doc.dir
4413 ;
4414 java
4415 -classpath
4416 ..:../cgjsapi.jar:../../../jldir.dir:../../../jldir.dir/jldoc.jar:../../../ml2xml.dir/ml2xml.dir/bin/ml2xml.jar
4417 jldoc.Jldoc
4418 -title "Xtpipes APIs"
4419 ../work.dir
4420 ;
4421 cd ..
4422 ;
4423 /usr/bin/rm -r doc.dir
4424 "}}}{}
4425 }
4426
4427
4428
4429
4430 \<dodoc.bat\><<<
4431 cd work.dir
4432 if NOT EXIST bin mkdir bin
4433 javac -Xlint:unchecked -d bin xtpipes/*.java
4434 javac -Xlint:unchecked -d bin xtpipes/util/*.java
4435 javac -Xlint:unchecked -d bin *.java
4436 cd bin
4437 jar cf xtpipes.jar *
4438 cd ..
4439 cd xtpipes
4440 if NOT EXIST bin mkdir bin
4441 move ..\bin\xtpipes.jar bin\.
4442 cd ..
4443 cd ..
4444 >>>
4445
4446 \ifOption{win}{
4447 \immediate\write16{......... work.dir\string \xtpipes\string \lib\string \*}
4448 \immediate\write16{......... work.dir\string \xtpipes\string \bin\string \xtpipes.jar}
4449 }{}
4450
4451
4452 \ifOption{doc}{\let\DOC\def}{}
4453
4454
4455
4456 \ifx\DOC\def
4457 %%%%%%%%%%%%%%%%%%%%%%%
4458 \<dodoc.bat\><<<
4459 if NOT EXIST doc.dir mkdir doc.dir
4460 cd doc.dir
4461 java -classpath ../../jldoc.dir;../../jldoc.dir/jldoc.jar;../../ml2xml.dir/ml2xml.dir/bin/ml2xml.jar jldoc.Jldoc -title "Xtpipes APIs" ../work.dir/xtpipes
4462 cd ..
4463 rmdir /s /q doc.dir
4464 >>>
4465 %%%%%%%%%%%%%%%
4466
4467 \fi
4468 \
4469
4470
4471
4472
4473 ../../..;..;../../jldoc;../../xtpipes/cgjsapi.jar;../../xtpipes/xtpipes.jar;../../jldoc/jldoc.jar;../../ml2xml.dir/ml2xml.dir/bin/ml2xml.jar
4474
4475 \ifdojava
4476 \ifOption{win} {}{
4477 \AtEndDocument{\Needs{%
4478 "pushd \XTPIPES || exit 1
4479 ;
4480 jar cf xtpipes.jar *
4481 ;
4482 popd
4483 ;
4484 mkdir -p \LIB || exit 1
4485 ;
4486 mv \XTPIPES xtpipes.jar \LIB
4487 ;
4488 mkdir -p \HOME texmf/tex4ht/xtpipes/. || exit 1
4489 ;
4490 cp \XTPIPES xtpipes/lib/*
4491 \HOME texmf/tex4ht/xtpipes/.
4492 "}}
4493 }
4494 \fi
4495
4496
4497
4498 \ifdojava
4499 \ifOption{win} {}{
4500 \AtEndDocument{\Needs{"
4501 mkdir -p \LIB\space || exit 1
4502 ;
4503 find \WORK\space -type f -iname '*.java' -print0
4504 | xargs -0 javac -d \XTPIPES\space -sourcepath \WORK
4505 ;
4506 pushd \XTPIPES || exit 1
4507 ;
4508 jar cf xtpipes.jar *
4509 ;
4510 popd
4511 ;
4512 mv \XTPIPES xtpipes.jar \LIB
4513 ;
4514 "}}}
4515 \fi
4516
4517
4518 \end{document}