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