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
|
/**
* @file
* @author 2012-2013 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#include "uscxml/config.h"
#include "uscxml/Common.h"
#include "uscxml/Interpreter.h"
#include "uscxml/URL.h"
#include "uscxml/UUID.h"
#include "uscxml/DOMUtils.h"
#include "uscxml/transform/FlatStateIdentifier.h"
#include "uscxml/transform/ChartToFSM.h" // only for testing
#include "getopt.h"
#include "uscxml/plugins/invoker/http/HTTPServletInvoker.h"
#include "uscxml/server/InterpreterServlet.h"
#include "uscxml/concurrency/DelayedEventQueue.h"
#include <DOM/Simple/DOMImplementation.hpp>
#include <SAX/helpers/InputSourceResolver.hpp>
#include <DOM/io/Stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <glog/logging.h>
#include <iostream>
#include <io/uri.hpp>
#include <assert.h>
#include <algorithm>
#include "uscxml/Factory.h"
#if 0
# define INTERPRETER_IMPL InterpreterDraft6
# include "uscxml/interpreter/InterpreterDraft6.h"
#else
# define INTERPRETER_IMPL InterpreterRC
# include "uscxml/interpreter/InterpreterRC.h"
#endif
#define VERBOSE 0
/// valid interpreter state transitions
#define VALID_FROM_INSTANTIATED(newState) ( \
newState == USCXML_MICROSTEPPED || \
newState == USCXML_DESTROYED\
)
#define VALID_FROM_FAULTED(newState) ( \
newState == USCXML_DESTROYED\
)
#define VALID_FROM_INITIALIZED(newState) ( \
newState == USCXML_MICROSTEPPED || \
newState == USCXML_FINISHED \
)
#define VALID_FROM_MICROSTEPPED(newState) ( \
newState == USCXML_DESTROYED || \
newState == USCXML_MACROSTEPPED || \
newState == USCXML_MICROSTEPPED || \
newState == USCXML_FINISHED \
)
#define VALID_FROM_MACROSTEPPED(newState) ( \
newState == USCXML_DESTROYED || \
newState == USCXML_MICROSTEPPED || \
newState == USCXML_MACROSTEPPED || \
newState == USCXML_IDLE || \
newState == USCXML_FINISHED \
)
#define VALID_FROM_IDLE(newState) ( \
newState == USCXML_DESTROYED || \
newState == USCXML_MICROSTEPPED || \
newState == USCXML_MACROSTEPPED \
)
#define VALID_FROM_FINISHED(newState) ( \
newState == USCXML_DESTROYED || \
newState == USCXML_INSTANTIATED \
)
/// macro to catch exceptions in executeContent
#define CATCH_AND_DISTRIBUTE(msg) \
catch (Event e) {\
if (rethrow) {\
throw(e);\
} else {\
LOG(ERROR) << msg << std::endl << e << std::endl;\
e.name = "error.execution";\
e.data.compound["cause"] = uscxml::Data(msg, uscxml::Data::VERBATIM); \
e.eventType = Event::PLATFORM;\
receiveInternal(e);\
}\
}
#define CATCH_AND_DISTRIBUTE2(msg, node) \
catch (Event e) {\
std::string xpathPos = DOMUtils::xPathForNode(node); \
if (rethrow) {\
throw(e);\
} else {\
LOG(ERROR) << msg << " " << xpathPos << ":" << std::endl << e << std::endl;\
e.name = "error.execution";\
e.data.compound["cause"] = uscxml::Data(msg, uscxml::Data::VERBATIM); \
e.data.compound["xpath"] = uscxml::Data(xpathPos, uscxml::Data::VERBATIM); \
e.eventType = Event::PLATFORM;\
e.dom = node;\
receiveInternal(e);\
}\
}
namespace uscxml {
using namespace Arabica::XPath;
using namespace Arabica::DOM;
void InterpreterOptions::printUsageAndExit(const char* progName) {
// remove path from program name
std::string progStr(progName);
if (progStr.find_last_of(PATH_SEPERATOR) != std::string::npos) {
progStr = progStr.substr(progStr.find_last_of(PATH_SEPERATOR) + 1, progStr.length() - (progStr.find_last_of(PATH_SEPERATOR) + 1));
}
printf("%s version " USCXML_VERSION " (" CMAKE_BUILD_TYPE " build - " CMAKE_COMPILER_STRING ")\n", progStr.c_str());
printf("Usage\n");
printf("\t%s", progStr.c_str());
printf(" [-v] [-d] [-lN]");
#ifdef BUILD_AS_PLUGINS
printf(" [-p pluginPath]");
#endif
printf(" [-tN]");
#ifdef EVENT_SSL_FOUND
printf(" [-sN] [--certificate=FILE | --private-key=FILE --public-key=FILE] ");
#endif
printf(" \\\n\t\t URL1 [--disable-http] [--option1=value1 --option2=value2]");
printf(" \\\n\t\t[URL2 [--disable-http] [--option3=value3 --option4=value4]]");
printf(" \\\n\t\t[URLN [--disable-http] [--optionN=valueN --optionM=valueM]]");
printf("\n");
printf("Options\n");
#ifdef BUILD_AS_PLUGINS
printf("\t-p : path to the uSCXML plugins (or export USCXML_PLUGIN_PATH)\n");
#endif
printf("\t-v : be verbose\n");
printf("\t-c : perform some sanity checks on the state-chart\n");
printf("\t-d : enable debugging via HTTP\n");
printf("\t-lN : set loglevel to N\n");
printf("\t-tN : port for HTTP server\n");
printf("\t-sN : port for HTTPS server\n");
printf("\t-wN : port for WebSocket server\n");
printf("\n");
exit(1);
}
unsigned int InterpreterOptions::getCapabilities() {
unsigned int capabilities = CAN_NOTHING;
if (withHTTP)
capabilities = capabilities | CAN_GENERIC_HTTP | CAN_BASIC_HTTP;
return capabilities;
}
InterpreterOptions InterpreterOptions::fromCmdLine(int argc, char** argv) {
InterpreterOptions options;
optind = 0;
struct option longOptions[] = {
{"check", no_argument, 0, 'c'},
{"verbose", no_argument, 0, 'v'},
{"debug", no_argument, 0, 'd'},
{"port", required_argument, 0, 't'},
{"ssl-port", required_argument, 0, 's'},
{"ws-port", required_argument, 0, 'w'},
{"certificate", required_argument, 0, 0},
{"private-key", required_argument, 0, 0},
{"public-key", required_argument, 0, 0},
{"plugin-path", required_argument, 0, 'p'},
{"loglevel", required_argument, 0, 'l'},
{"disable-http", no_argument, 0, 0},
{0, 0, 0, 0}
};
opterr = 0;
InterpreterOptions* currOptions = &options;
// parse global options
int optionInd = 0;
int option;
for (;;) {
option = getopt_long_only(argc, argv, "+vcdt:s:w:p:l:", longOptions, &optionInd);
if (option == -1) {
if (optind == argc)
// we are done with parsing
goto DONE_PARSING_CMD;
std::string url = argv[optind];
options.interpreters.push_back(std::make_pair(url, new InterpreterOptions()));
currOptions = options.interpreters.back().second;
argc -= optind;
argv += optind;
optind = 0;
if (argc <= 1)
goto DONE_PARSING_CMD;
}
switch(option) {
// cases without short option
case 0: {
if (boost::equals(longOptions[optionInd].name, "disable-http")) {
currOptions->withHTTP = false;
} else if (boost::equals(longOptions[optionInd].name, "private-key")) {
currOptions->privateKey = optarg;
} else if (boost::equals(longOptions[optionInd].name, "certificate")) {
currOptions->certificate = optarg;
} else if (boost::equals(longOptions[optionInd].name, "public-key")) {
currOptions->publicKey = optarg;
}
break;
}
// cases with short-hand options
case 'l':
currOptions->logLevel = strTo<unsigned int>(optarg);
break;
case 'p':
currOptions->pluginPath = optarg;
break;
case 'd':
currOptions->withDebugger = true;
break;
case 'c':
currOptions->checking = true;
break;
case 't':
currOptions->httpPort = strTo<unsigned short>(optarg);
break;
case 's':
currOptions->httpsPort = strTo<unsigned short>(optarg);
break;
case 'w':
currOptions->wsPort = strTo<unsigned short>(optarg);
break;
case 'v':
currOptions->verbose = true;
break;
case '?': {
std::string param = argv[optind - 1];
if (boost::starts_with(param, "--")) {
param = param.substr(2, param.length() - 2);
} else if (boost::starts_with(param, "-")) {
param = param.substr(1, param.length() - 1);
} else {
break;
}
boost::trim(param);
size_t equalPos = param.find("=");
if (equalPos != std::string::npos) {
std::string key = param.substr(0, equalPos);
std::string value = param.substr(equalPos + 1, param.length() - (equalPos + 1));
currOptions->additionalParameters[key] = value;
} else {
currOptions->additionalParameters[param] = "";
}
break;
}
default:
break;
}
}
DONE_PARSING_CMD:
if (options.interpreters.size() == 0 && !options.withDebugger)
options.error = "No SCXML document to evaluate";
return options;
}
void NameSpaceInfo::init(const std::map<std::string, std::string>& namespaceInfo) {
nsInfo = namespaceInfo;
nsURL = "";
if (nsContext)
delete nsContext;
nsContext = new Arabica::XPath::StandardNamespaceContext<std::string>();
std::map<std::string, std::string>::const_iterator nsIter = namespaceInfo.begin();
while(nsIter != namespaceInfo.end()) {
std::string uri = nsIter->first;
std::string prefix = nsIter->second;
if (iequals(uri, "http://www.w3.org/2005/07/scxml")) {
nsURL = uri;
if (prefix.size() == 0) {
xpathPrefix = "scxml:";
nsContext->addNamespaceDeclaration(uri, "scxml");
} else {
xpathPrefix = prefix + ":";
xmlNSPrefix = xpathPrefix;
nsContext->addNamespaceDeclaration(uri, prefix);
nsToPrefix[uri] = prefix;
}
} else {
nsContext->addNamespaceDeclaration(uri, prefix);
nsToPrefix[uri] = prefix;
}
nsIter++;
}
}
std::map<std::string, boost::weak_ptr<InterpreterImpl> > Interpreter::_instances;
tthread::recursive_mutex Interpreter::_instanceMutex;
std::map<std::string, boost::weak_ptr<InterpreterImpl> > Interpreter::getInstances() {
tthread::lock_guard<tthread::recursive_mutex> lock(_instanceMutex);
std::map<std::string, boost::weak_ptr<InterpreterImpl> >::iterator instIter = _instances.begin();
while(instIter != _instances.end()) {
if (!instIter->second.lock()) {
_instances.erase(instIter++);
} else {
instIter++;
}
}
return _instances;
}
InterpreterImpl::InterpreterImpl() {
_state = USCXML_INSTANTIATED;
_lastRunOnMainThread = 0;
_thread = NULL;
_isStarted = false;
_isRunning = false;
_sendQueue = NULL;
_parentQueue = NULL;
_topLevelFinalReached = false;
_stable = false;
_isInitialized = false;
_userSuppliedDataModel = false;
_domIsSetup = false;
_httpServlet = NULL;
_factory = NULL;
_sessionId = UUID::getUUID();
_capabilities = CAN_BASIC_HTTP | CAN_GENERIC_HTTP;
_domEventListener._interpreter = this;
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
}
Interpreter Interpreter::fromDOM(const Arabica::DOM::Document<std::string>& dom, const NameSpaceInfo& nameSpaceInfo) {
tthread::lock_guard<tthread::recursive_mutex> lock(_instanceMutex);
boost::shared_ptr<INTERPRETER_IMPL> interpreterImpl = boost::shared_ptr<INTERPRETER_IMPL>(new INTERPRETER_IMPL);
Interpreter interpreter(interpreterImpl);
// *copy* the given DOM to get rid of event listeners
DOMImplementation<std::string> domFactory = Arabica::SimpleDOM::DOMImplementation<std::string>::getDOMImplementation();
interpreterImpl->_document = domFactory.createDocument(dom.getNamespaceURI(), "", 0);
Node<std::string> child = dom.getFirstChild();
while (child) {
Node<std::string> newNode = interpreterImpl->_document.importNode(child, true);
interpreterImpl->_document.appendChild(newNode);
child = child.getNextSibling();
}
interpreterImpl->setNameSpaceInfo(nameSpaceInfo);
interpreterImpl->setupDOM();
// interpreterImpl->init();
_instances[interpreterImpl->getSessionId()] = interpreterImpl;
return interpreter;
}
Interpreter Interpreter::fromXML(const std::string& xml) {
std::stringstream* ss = new std::stringstream();
(*ss) << xml;
// we need an auto_ptr for arabica to assume ownership
std::auto_ptr<std::istream> ssPtr(ss);
Arabica::SAX::InputSource<std::string> inputSource;
inputSource.setByteStream(ssPtr);
return fromInputSource(inputSource);
}
Interpreter Interpreter::fromURI(const std::string& uri) {
URL absUrl(uri);
if (!absUrl.isAbsolute()) {
if (!absUrl.toAbsoluteCwd()) {
ERROR_COMMUNICATION_THROW("URL is not absolute or does not have file schema");
}
}
Interpreter interpreter;
if (iequals(absUrl.scheme(), "file")) {
Arabica::SAX::InputSource<std::string> inputSource;
inputSource.setSystemId(absUrl.asString());
interpreter = fromInputSource(inputSource);
} else {
// use curl for everything !file - even for http as arabica won't follow redirects
std::stringstream ss;
ss << absUrl;
if (absUrl.downloadFailed()) {
ERROR_COMMUNICATION_THROW("Downloading SCXML document from '" + absUrl.asString() + "' failed");
}
interpreter = fromXML(ss.str());
}
// try to establish URI root for relative src attributes in document
if (interpreter) {
interpreter._impl->_baseURI = URL::asBaseURL(absUrl);
interpreter._impl->_sourceURI = absUrl;
} else {
ERROR_PLATFORM_THROW("Cannot create interpreter from URI '" + absUrl.asString() + "'");
}
return interpreter;
}
Interpreter Interpreter::fromInputSource(Arabica::SAX::InputSource<std::string>& source) {
tthread::lock_guard<tthread::recursive_mutex> lock(_instanceMutex);
// remove old instances
std::map<std::string, boost::weak_ptr<InterpreterImpl> >::iterator instIter = _instances.begin();
while(instIter != _instances.end()) {
if (!instIter->second.lock()) {
_instances.erase(instIter++);
} else {
instIter++;
}
}
boost::shared_ptr<INTERPRETER_IMPL> interpreterImpl = boost::shared_ptr<INTERPRETER_IMPL>(new INTERPRETER_IMPL);
Interpreter interpreter(interpreterImpl);
_instances[interpreterImpl->getSessionId()] = interpreterImpl;
NameSpacingParser parser;
if (parser.parse(source) && parser.getDocument() && parser.getDocument().hasChildNodes()) {
interpreterImpl->setNameSpaceInfo(parser.nameSpace);
interpreterImpl->_document = parser.getDocument();
interpreterImpl->setupDOM();
} else {
if (parser.errorsReported()) {
ERROR_PLATFORM_THROW(parser.errors())
} else {
ERROR_PLATFORM_THROW("Failed to create interpreter");
// interpreterImpl->setInterpreterState(USCXML_FAULTED, parser.errors());
}
}
return interpreter;
}
Interpreter Interpreter::fromClone(const Interpreter& other) {
tthread::lock_guard<tthread::recursive_mutex> lock(_instanceMutex);
boost::shared_ptr<INTERPRETER_IMPL> interpreterImpl = boost::shared_ptr<INTERPRETER_IMPL>(new INTERPRETER_IMPL);
interpreterImpl->cloneFrom(other.getImpl());
Interpreter interpreter(interpreterImpl);
_instances[interpreterImpl->getSessionId()] = interpreterImpl;
return interpreter;
}
void InterpreterImpl::writeTo(std::ostream& stream) {
stream << getDocument();
}
void InterpreterImpl::cloneFrom(InterpreterImpl* other) {
if (other->getDocument()) {
const Arabica::DOM::Document<std::string>& otherDoc = other->_document;
DOMImplementation<std::string> domFactory = Arabica::SimpleDOM::DOMImplementation<std::string>::getDOMImplementation();
_document = domFactory.createDocument(otherDoc.getNamespaceURI(), "", 0);
Node<std::string> child = otherDoc.getFirstChild();
while (child) {
Node<std::string> newNode = _document.importNode(child, true);
_document.appendChild(newNode);
child = child.getNextSibling();
}
setNameSpaceInfo(other->_nsInfo);
_baseURI = other->_baseURI;
_sourceURI = other->_sourceURI;
setupDOM();
}
}
void InterpreterImpl::cloneFrom(boost::shared_ptr<InterpreterImpl> other) {
cloneFrom(other.get());
}
void InterpreterImpl::setName(const std::string& name) {
_name = name;
}
InterpreterImpl::~InterpreterImpl() {
{
// make sure we are done with setting up with early abort
tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);
stop(); // unset started bit
}
// std::cout << "stopped " << this << std::endl;
// tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);
if (_thread) {
if (_thread->get_id() != tthread::this_thread::get_id()) {
// unblock event queue
Event event;
event.name = "unblock.and.die";
receive(event);
} else {
// this can happen with a shared_from_this at an interpretermonitor
setInterpreterState(USCXML_DESTROYED);
}
_thread->join();
delete(_thread);
}
if (_sendQueue)
delete _sendQueue;
}
void InterpreterImpl::start() {
_isStarted = true;
_thread = new tthread::thread(InterpreterImpl::run, this);
}
void InterpreterImpl::stop() {
_isStarted = false;
}
void InterpreterImpl::join() {
stop();
if (_thread != NULL) _thread->join();
};
bool InterpreterImpl::isRunning() {
return _isRunning && !_topLevelFinalReached;
}
void InterpreterImpl::run(void* instance) {
InterpreterImpl* interpreter = ((InterpreterImpl*)instance);
interpreter->_isRunning = true;
try {
InterpreterState state;
while(interpreter->_isStarted) {
state = interpreter->step(-1);
switch (state) {
case uscxml::USCXML_FINISHED:
case uscxml::USCXML_DESTROYED:
// return as we finished
goto DONE_THREAD;
default:
break;
}
}
} catch (Event e) {
LOG(ERROR) << e;
} catch(std::exception e) {
LOG(ERROR) << "InterpreterImpl::run catched an exception: " << e.what() << std::endl << "Unclean shutdown";
} catch (...) {
LOG(ERROR) << "InterpreterImpl::run catched unknown exception";
}
DONE_THREAD:
((InterpreterImpl*)instance)->_isRunning = false;
((InterpreterImpl*)instance)->_isStarted = false;
}
void InterpreterImpl::exitInterpreter() {
NodeSet<std::string> statesToExit = _configuration;
statesToExit.forward(false);
statesToExit.sort();
for (int i = 0; i < statesToExit.size(); i++) {
Arabica::XPath::NodeSet<std::string> onExitElems = filterChildElements(_nsInfo.xmlNSPrefix + "onexit", statesToExit[i]);
for (int j = 0; j < onExitElems.size(); j++) {
executeContent(Element<std::string>(onExitElems[j]));
}
Arabica::XPath::NodeSet<std::string> invokeElems = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", statesToExit[i]);
// TODO: we ought to cancel all remaining invokers just to be sure with the persist extension
for (int j = 0; j < invokeElems.size(); j++) {
cancelInvoke(Element<std::string>(invokeElems[j]));
}
Element<std::string> stateElem(statesToExit[i]);
if (isFinal(stateElem) && parentIsScxmlState(stateElem)) {
returnDoneEvent(statesToExit[i]);
}
}
_configuration = NodeSet<std::string>();
}
InterpreterState InterpreterImpl::interpret() {
InterpreterState state;
while(true) {
state = step(-1);
switch (state) {
case uscxml::USCXML_FINISHED:
case uscxml::USCXML_DESTROYED:
// return as we finished
return state;
default:
// process invokers on main thread
if(_thread == NULL) {
runOnMainThread(200);
}
// process next step
break;
}
}
return state;
}
// setup / fetch the documents initial transitions
NodeSet<std::string> InterpreterImpl::getDocumentInitialTransitions() {
NodeSet<std::string> initialTransitions;
if (_startConfiguration.size() > 0) {
// we emulate entering a given configuration by creating a pseudo deep history
Element<std::string> initHistory = _document.createElementNS(_nsInfo.nsURL, "history");
_nsInfo.setPrefix(initHistory);
initHistory.setAttribute("id", UUID::getUUID());
initHistory.setAttribute("type", "deep");
_scxml.insertBefore(initHistory, _scxml.getFirstChild());
std::string histId = ATTR(initHistory, "id");
NodeSet<std::string> histStates;
for (std::list<std::string>::const_iterator stateIter = _startConfiguration.begin(); stateIter != _startConfiguration.end(); stateIter++) {
histStates.push_back(getState(*stateIter));
}
_historyValue[histId] = histStates;
Element<std::string> initialElem = _document.createElementNS(_nsInfo.nsURL, "initial");
_nsInfo.setPrefix(initialElem);
initialElem.setAttribute("generated", "true");
Element<std::string> transitionElem = _document.createElementNS(_nsInfo.nsURL, "transition");
_nsInfo.setPrefix(transitionElem);
transitionElem.setAttribute("target", histId);
initialElem.appendChild(transitionElem);
_scxml.appendChild(initialElem);
initialTransitions.push_back(transitionElem);
} else {
// try to get initial transition from initial element
initialTransitions = _xpath.evaluate("/" + _nsInfo.xpathPrefix + "initial/" + _nsInfo.xpathPrefix + "transition", _scxml).asNodeSet();
if (initialTransitions.size() == 0) {
Arabica::XPath::NodeSet<std::string> initialStates;
// fetch per draft
initialStates = getInitialStates();
assert(initialStates.size() > 0);
for (int i = 0; i < initialStates.size(); i++) {
Element<std::string> initialElem = _document.createElementNS(_nsInfo.nsURL, "initial");
_nsInfo.setPrefix(initialElem);
initialElem.setAttribute("generated", "true");
Element<std::string> transitionElem = _document.createElementNS(_nsInfo.nsURL, "transition");
_nsInfo.setPrefix(transitionElem);
transitionElem.setAttribute("target", ATTR_CAST(initialStates[i], "id"));
initialElem.appendChild(transitionElem);
_scxml.appendChild(initialElem);
initialTransitions.push_back(transitionElem);
}
}
}
return initialTransitions;
}
InterpreterState InterpreterImpl::step(int waitForMS) {
try {
tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);
if (_state == USCXML_FINISHED || _state == USCXML_DESTROYED) {
return _state;
}
NodeSet<std::string> enabledTransitions;
// setup document and interpreter
if (!_isInitialized) {
init(); // will throw
}
if (_configuration.size() == 0) {
// goto initial configuration
NodeSet<std::string> initialTransitions = getDocumentInitialTransitions();
assert(initialTransitions.size() > 0);
#if VERBOSE
std::cout << _name << ": initialTransitions: " << std::endl;
for (int i = 0; i < initialTransitions.size(); i++) {
std::cout << initialTransitions[i] << std::endl;
}
std::cout << std::endl;
#endif
enterStates(initialTransitions);
setInterpreterState(USCXML_MICROSTEPPED);
}
assert(isLegalConfiguration(_configuration));
// are there spontaneous transitions?
if (!_stable) {
enabledTransitions = selectEventlessTransitions();
if (!enabledTransitions.empty()) {
// test 403b
enabledTransitions.to_document_order();
microstep(enabledTransitions);
setInterpreterState(USCXML_MICROSTEPPED);
// check whether we run in cycles
FlatStateIdentifier flat(_configuration, _alreadyEntered, _historyValue);
if (_microstepConfigurations.find(flat.getStateId()) != _microstepConfigurations.end()) {
USCXML_MONITOR_CALLBACK2(reportIssue,
InterpreterIssue("Reentering during microstep " + flat.getFlatActive() + " - possible endless loop",
Arabica::DOM::Node<std::string>(),
InterpreterIssue::USCXML_ISSUE_WARNING));
}
_microstepConfigurations.insert(flat.getStateId());
return _state;
}
_stable = true;
}
// test415
if (_topLevelFinalReached)
goto EXIT_INTERPRETER;
// process internal event
if (!_internalQueue.empty()) {
_currEvent = _internalQueue.front();
_internalQueue.pop_front();
_stable = false;
USCXML_MONITOR_CALLBACK2(beforeProcessingEvent, _currEvent)
_dataModel.setEvent(_currEvent);
enabledTransitions = selectTransitions(_currEvent.name);
if (!enabledTransitions.empty()) {
// test 403b
enabledTransitions.to_document_order();
microstep(enabledTransitions);
}
// test 319 - even if we do not enable transitions, consider it a microstep
setInterpreterState(USCXML_MICROSTEPPED);
return _state;
} else {
_stable = true;
_microstepConfigurations.clear();
}
if (_state != USCXML_MACROSTEPPED && _state != USCXML_IDLE)
USCXML_MONITOR_CALLBACK(onStableConfiguration)
setInterpreterState(USCXML_MACROSTEPPED);
if (_topLevelFinalReached)
goto EXIT_INTERPRETER;
// when we reach a stable configuration, invoke
for (unsigned int i = 0; i < _statesToInvoke.size(); i++) {
NodeSet<std::string> invokes = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", _statesToInvoke[i]);
for (unsigned int j = 0; j < invokes.size(); j++) {
Element<std::string> invokeElem = Element<std::string>(invokes[j]);
if (!HAS_ATTR(invokeElem, "persist") || !DOMUtils::attributeIsTrue(ATTR(invokeElem, "persist"))) {
invoke(invokeElem);
}
}
}
_statesToInvoke = NodeSet<std::string>();
if (_externalQueue.isEmpty()) {
setInterpreterState(USCXML_IDLE);
if (waitForMS < 0) {
// wait blockingly for an event forever
while(_externalQueue.isEmpty()) {
_condVar.wait(_mutex);
}
}
if (waitForMS > 0) {
// wait given number of milliseconds max
uint64_t now = tthread::chrono::system_clock::now();
uint64_t then = now + waitForMS;
while(_externalQueue.isEmpty() && now < then) {
_condVar.wait_for(_mutex, then - now);
now = tthread::chrono::system_clock::now();
}
}
if (_externalQueue.isEmpty()) {
return _state;
}
setInterpreterState(USCXML_MACROSTEPPED);
}
_currEvent = _externalQueue.pop();
_currEvent.eventType = Event::EXTERNAL; // make sure it is set to external
_stable = false;
if (_topLevelFinalReached)
goto EXIT_INTERPRETER;
USCXML_MONITOR_CALLBACK2(beforeProcessingEvent, _currEvent)
if (iequals(_currEvent.name, "cancel.invoke." + _sessionId)) {
goto EXIT_INTERPRETER;
}
try {
_dataModel.setEvent(_currEvent);
} catch (Event e) {
LOG(ERROR) << "Syntax error while setting external event:" << std::endl << e << std::endl << _currEvent;
}
finalizeAndAutoForwardCurrentEvent();
// run internal processing until we reach a stable configuration again
enabledTransitions = selectTransitions(_currEvent.name);
if (!enabledTransitions.empty()) {
// test 403b
enabledTransitions.to_document_order();
microstep(enabledTransitions);
}
if (_topLevelFinalReached)
goto EXIT_INTERPRETER;
return _state;
EXIT_INTERPRETER:
USCXML_MONITOR_CALLBACK(beforeCompletion)
exitInterpreter();
if (_sendQueue) {
std::map<std::string, std::pair<InterpreterImpl*, SendRequest> >::iterator sendIter = _sendIds.begin();
while(sendIter != _sendIds.end()) {
_sendQueue->cancelEvent(sendIter->first);
sendIter++;
}
}
USCXML_MONITOR_CALLBACK(afterCompletion)
// assert(hasLegalConfiguration());
_mutex.unlock();
// remove datamodel
if(!_userSuppliedDataModel)
_dataModel = DataModel();
setInterpreterState(USCXML_FINISHED);
return _state;
} catch (boost::bad_weak_ptr e) {
LOG(ERROR) << "Unclean shutdown " << std::endl << std::endl;
setInterpreterState(USCXML_DESTROYED);
return _state;
}
// set datamodel to null from this thread
if(_dataModel)
_dataModel = DataModel();
}
void InterpreterImpl::microstep(const Arabica::XPath::NodeSet<std::string>& enabledTransitions) {
USCXML_MONITOR_CALLBACK(beforeMicroStep)
exitStates(enabledTransitions);
for (int i = 0; i < enabledTransitions.size(); i++) {
Element<std::string> transition(enabledTransitions[i]);
USCXML_MONITOR_CALLBACK3(beforeTakingTransition, transition, (i + 1 < enabledTransitions.size()))
executeContent(transition);
USCXML_MONITOR_CALLBACK3(afterTakingTransition, transition, (i + 1 < enabledTransitions.size()))
}
enterStates(enabledTransitions);
USCXML_MONITOR_CALLBACK(afterMicroStep)
}
// process transitions until we are in a stable configuration again
void InterpreterImpl::stabilize() {
NodeSet<std::string> enabledTransitions;
_stable = false;
if (_configuration.size() == 0) {
// goto initial configuration
NodeSet<std::string> initialTransitions = getDocumentInitialTransitions();
assert(initialTransitions.size() > 0);
enterStates(initialTransitions);
}
std::set<std::string> configurationsSeen;
do { // process microsteps for enabled transitions until there are no more left
enabledTransitions = selectEventlessTransitions();
if (enabledTransitions.size() == 0) {
if (_internalQueue.size() == 0) {
_stable = true;
} else {
_currEvent = _internalQueue.front();
_internalQueue.pop_front();
#if VERBOSE
std::cout << "Received internal event " << _currEvent.name << std::endl;
#endif
USCXML_MONITOR_CALLBACK2(beforeProcessingEvent, _currEvent)
if (_dataModel)
_dataModel.setEvent(_currEvent);
enabledTransitions = selectTransitions(_currEvent.name);
}
}
if (!enabledTransitions.empty()) {
// test 403b
enabledTransitions.to_document_order();
microstep(enabledTransitions);
}
} while(!_internalQueue.empty() || !_stable);
USCXML_MONITOR_CALLBACK(onStableConfiguration)
// when we reach a stable configuration, invoke
for (unsigned int i = 0; i < _statesToInvoke.size(); i++) {
NodeSet<std::string> invokes = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", _statesToInvoke[i]);
for (unsigned int j = 0; j < invokes.size(); j++) {
Element<std::string> invokeElem = Element<std::string>(invokes[j]);
if (!HAS_ATTR(invokeElem, "persist") || !DOMUtils::attributeIsTrue(ATTR(invokeElem, "persist"))) {
invoke(invokeElem);
}
}
}
_statesToInvoke = NodeSet<std::string>();
}
Arabica::XPath::NodeSet<std::string> InterpreterImpl::selectTransitions(const std::string& event) {
Arabica::XPath::NodeSet<std::string> enabledTransitions;
NodeSet<std::string> states;
for (unsigned int i = 0; i < _configuration.size(); i++) {
if (isAtomic(Element<std::string>(_configuration[i])))
states.push_back(_configuration[i]);
}
states.to_document_order();
unsigned int index = 0;
while(states.size() > index) {
NodeSet<std::string> transitions = filterChildElements(_nsInfo.xmlNSPrefix + "transition", states[index]);
for (unsigned int k = 0; k < transitions.size(); k++) {
if (isEnabledTransition(Element<std::string>(transitions[k]), event)) {
enabledTransitions.push_back(transitions[k]);
goto LOOP;
}
}
{
Node<std::string> parent = states[index].getParentNode();
if (parent) {
states.push_back(parent);
}
}
LOOP:
index++;
}
enabledTransitions = removeConflictingTransitions(enabledTransitions);
return enabledTransitions;
}
Arabica::XPath::NodeSet<std::string> InterpreterImpl::selectEventlessTransitions() {
Arabica::XPath::NodeSet<std::string> enabledTransitions;
NodeSet<std::string> states;
for (unsigned int i = 0; i < _configuration.size(); i++) {
if (isAtomic(Element<std::string>(_configuration[i])))
states.push_back(_configuration[i]);
}
states.to_document_order();
unsigned int index = 0;
while(states.size() > index) {
bool foundTransition = false;
NodeSet<std::string> transitions = filterChildElements(_nsInfo.xmlNSPrefix + "transition", states[index]);
for (unsigned int k = 0; k < transitions.size(); k++) {
Element<std::string> transElem(transitions[k]);
if (!HAS_ATTR(transElem, "event") && hasConditionMatch(transElem)) {
enabledTransitions.push_back(transitions[k]);
foundTransition = true;
goto LOOP;
}
}
if (!foundTransition) {
Node<std::string> parent = states[index].getParentNode();
if (parent) {
states.push_back(parent);
}
}
LOOP:
index++;
}
#if VERBOSE
std::cout << "Enabled eventless transitions: " << std::endl;
for (int i = 0; i < enabledTransitions.size(); i++) {
std::cout << enabledTransitions[i] << std::endl << "----" << std::endl;
}
std::cout << std::endl;
#endif
enabledTransitions = removeConflictingTransitions(enabledTransitions);
return enabledTransitions;
}
bool InterpreterImpl::isEnabledTransition(const Element<std::string>& transition, const std::string& event) {
std::string eventName;
if (HAS_ATTR(transition, "event")) {
eventName = ATTR(transition, "event");
} else if(HAS_ATTR(transition, "eventexpr")) {
if (_dataModel) {
eventName = _dataModel.evalAsString(ATTR(transition, "eventexpr"));
} else {
LOG(ERROR) << "Transition has eventexpr attribute with no datamodel defined";
return false;
}
} else {
return false;
}
std::list<std::string> eventNames = tokenizeIdRefs(eventName);
std::list<std::string>::iterator eventIter = eventNames.begin();
while(eventIter != eventNames.end()) {
if(nameMatch(*eventIter, event) && hasConditionMatch(transition)) {
return true;
}
eventIter++;
}
return false;
}
InterpreterState InterpreterImpl::getInterpreterState() {
return _state;
}
void InterpreterImpl::setInterpreterState(InterpreterState newState) {
switch (_state) {
case USCXML_INSTANTIATED:
if (VALID_FROM_INSTANTIATED(newState))
break;
assert(false);
break;
case USCXML_MICROSTEPPED:
if (VALID_FROM_MICROSTEPPED(newState))
break;
assert(false);
break;
case USCXML_MACROSTEPPED:
if (VALID_FROM_MACROSTEPPED(newState))
break;
assert(false);
break;
case USCXML_IDLE:
if (VALID_FROM_IDLE(newState))
break;
assert(false);
break;
case USCXML_FINISHED:
if (VALID_FROM_FINISHED(newState))
break;
assert(false);
break;
case USCXML_DESTROYED:
assert(false);
break;
default:
break;
}
_state = newState;
}
bool InterpreterImpl::runOnMainThread(int fps, bool blocking) {
if (_state == USCXML_FINISHED || _state == USCXML_DESTROYED || !_isStarted)
return false;
if (fps > 0) {
if (blocking && _lastRunOnMainThread > 0) {
uint64_t nextRun = _lastRunOnMainThread + (1000 / fps);
while(nextRun > tthread::timeStamp()) {
tthread::this_thread::sleep_for(tthread::chrono::milliseconds(nextRun - tthread::timeStamp()));
}
} else {
return true;
}
}
tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);
_lastRunOnMainThread = tthread::timeStamp();
{
tthread::lock_guard<tthread::recursive_mutex> lock(_pluginMutex);
std::map<std::string, IOProcessor>::iterator ioProcessorIter = _ioProcessors.begin();
while(ioProcessorIter != _ioProcessors.end()) {
ioProcessorIter->second.runOnMainThread();
ioProcessorIter++;
}
std::map<std::string, Invoker>::iterator invokerIter = _invokers.begin();
while(invokerIter != _invokers.end()) {
invokerIter->second.runOnMainThread();
invokerIter++;
}
}
return (_thread != NULL);
}
void InterpreterImpl::reset() {
tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);
_externalQueue.clear();
_internalQueue.clear();
_historyValue.clear();
_currEvent = Event();
_alreadyEntered = NodeSet<std::string>();
_configuration = NodeSet<std::string>();
_topLevelFinalReached = false;
_isInitialized = false;
_stable = false;
setInterpreterState(USCXML_INSTANTIATED);
}
std::list<InterpreterIssue> InterpreterImpl::validate() {
return InterpreterIssue::forInterpreter(this);
}
std::ostream& operator<< (std::ostream& os, const InterpreterIssue& issue) {
switch (issue.severity) {
case InterpreterIssue::USCXML_ISSUE_FATAL:
os << "Issue (FATAL) ";
break;
case InterpreterIssue::USCXML_ISSUE_WARNING:
os << "Issue (WARNING) ";
break;
case InterpreterIssue::USCXML_ISSUE_INFO:
os << "Issue (INFO) ";
break;
default:
break;
}
if (issue.xPath.size() > 0) {
os << "at " << issue.xPath << ": ";
} else {
os << ": ";
}
os << issue.message;
return os;
}
void InterpreterImpl::setupDOM() {
if (_domIsSetup)
return;
if (!_document) {
ERROR_PLATFORM_THROW("Interpreter has no DOM");
}
// find scxml element
if (!_scxml) {
NodeList<std::string> scxmls;
if (_nsInfo.nsURL.size() == 0) {
scxmls = _document.getElementsByTagName("scxml");
} else {
scxmls = _document.getElementsByTagNameNS(_nsInfo.nsURL, "scxml");
}
if (scxmls.getLength() == 0) {
ERROR_PLATFORM_THROW("Cannot find SCXML element in DOM");
}
_scxml = (Arabica::DOM::Element<std::string>)scxmls.item(0);
}
if (_nsInfo.getNSContext() != NULL)
_xpath.setNamespaceContext(*_nsInfo.getNSContext());
// normalize document
// TODO: Resolve XML includes
#if 0
// make sure every state has an id
Arabica::XPath::NodeSet<std::string> states;
states.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "state", _scxml).asNodeSet());
states.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "final", _scxml).asNodeSet());
states.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "history", _scxml).asNodeSet());
for (int i = 0; i < states.size(); i++) {
Arabica::DOM::Element<std::string> stateElem = Arabica::DOM::Element<std::string>(states[i]);
if (!stateElem.hasAttribute("id")) {
stateElem.setAttribute("id", UUID::getUUID());
}
}
#endif
// make sure every invoke has an idlocation or id
Arabica::XPath::NodeSet<std::string> invokes = _xpath.evaluate("//" + _nsInfo.xpathPrefix + "invoke", _scxml).asNodeSet();
for (int i = 0; i < invokes.size(); i++) {
Arabica::DOM::Element<std::string> invokeElem = Arabica::DOM::Element<std::string>(invokes[i]);
if (!invokeElem.hasAttribute("id") && !invokeElem.hasAttribute("idlocation")) {
invokeElem.setAttribute("id", UUID::getUUID());
}
}
#if 0
// add an id to the scxml element
if (!_scxml.hasAttribute("id")) {
_scxml.setAttribute("id", UUID::getUUID());
}
#endif
// register for dom events to manage cached states
Arabica::DOM::Events::EventTarget<std::string> eventTarget(_scxml);
eventTarget.addEventListener("DOMNodeInserted", _domEventListener, true);
eventTarget.addEventListener("DOMNodeRemoved", _domEventListener, true);
eventTarget.addEventListener("DOMSubtreeModified", _domEventListener, true);
_domIsSetup = true;
}
void InterpreterImpl::init() {
// make sure we have a factory if none was set before
if (_factory == NULL)
_factory = Factory::getInstance();
// setup and normalize DOM
setupDOM();
// get our name or generate as UUID
if (_name.length() == 0)
_name = (HAS_ATTR(_scxml, "name") ? ATTR(_scxml, "name") : UUID::getUUID());
// setup event queue for delayed send
if (!_sendQueue) {
_sendQueue = new DelayedEventQueue();
_sendQueue->start();
}
// start io processoes
setupIOProcessors();
// instantiate datamodel if not explicitly set
if (!_dataModel) {
if (HAS_ATTR(_scxml, "datamodel")) {
// might throw
_dataModel = _factory->createDataModel(ATTR(_scxml, "datamodel"), this);
for (std::set<DataModelExtension*>::iterator extIter = _dataModelExtensions.begin(); extIter != _dataModelExtensions.end(); extIter++) {
_dataModel.addExtension(*extIter);
}
} else {
_dataModel = _factory->createDataModel("null", this);
}
}
_dataModel.assign("_x.args", _cmdLineOptions);
// _running = true;
#if VERBOSE
std::cout << "running " << this << std::endl;
#endif
_binding = (HAS_ATTR(_scxml, "binding") && iequals(ATTR(_scxml, "binding"), "late") ? LATE : EARLY);
if (_binding == EARLY) {
// initialize all data elements
NodeSet<std::string> dataElems = _xpath.evaluate("//" + _nsInfo.xpathPrefix + "data", _scxml).asNodeSet();
for (unsigned int i = 0; i < dataElems.size(); i++) {
// do not process data elements of nested documents from invokers
if (!getAncestorElement(dataElems[i], _nsInfo.xmlNSPrefix + "invoke"))
if (dataElems[i].getNodeType() == Node_base::ELEMENT_NODE) {
initializeData(Element<std::string>(dataElems[i]));
}
}
} else {
// initialize current data elements
NodeSet<std::string> topDataElems = filterChildElements(_nsInfo.xmlNSPrefix + "data", filterChildElements(_nsInfo.xmlNSPrefix + "datamodel", _scxml));
for (unsigned int i = 0; i < topDataElems.size(); i++) {
if (topDataElems[i].getNodeType() == Node_base::ELEMENT_NODE)
initializeData(Element<std::string>(topDataElems[i]));
}
}
// executeGlobalScriptElements
NodeSet<std::string> globalScriptElems = filterChildElements(_nsInfo.xmlNSPrefix + "script", _scxml);
for (unsigned int i = 0; i < globalScriptElems.size(); i++) {
executeContent(Element<std::string>(globalScriptElems[i]));
}
_isInitialized = true;
_stable = false;
}
/**
* Called with a single data element from the topmost datamodel element.
*/
void InterpreterImpl::initializeData(const Element<std::string>& data) {
/// test 226/240 - initialize from invoke request
if (_invokeReq.params.find(ATTR(data, "id")) != _invokeReq.params.end()) {
try {
_dataModel.init(ATTR(data, "id"), _invokeReq.params.find(ATTR(data, "id"))->second);
} catch (Event e) {
LOG(ERROR) << "Syntax error when initializing data " << DOMUtils::xPathForNode(data) << " from parameters:" << std::endl << e << std::endl;
receiveInternal(e);
}
return;
}
if (_invokeReq.namelist.find(ATTR(data, "id")) != _invokeReq.namelist.end()) {
try {
_dataModel.init(ATTR(data, "id"), _invokeReq.namelist.find(ATTR(data, "id"))->second);
} catch (Event e) {
LOG(ERROR) << "Syntax error when initializing data " << DOMUtils::xPathForNode(data) << " from namelist:" << std::endl << e << std::endl;
receiveInternal(e);
}
return;
}
try {
Arabica::DOM::Node<std::string> dom;
std::string text;
processDOMorText(data, dom, text);
_dataModel.init(data, dom, text);
} catch (Event e) {
LOG(ERROR) << "Syntax error when initializing data " << DOMUtils::xPathForNode(data) << ":" << std::endl << e << std::endl;
receiveInternal(e);
}
}
void InterpreterImpl::receiveInternal(const Event& event) {
#if VERBOSE
std::cout << _name << " receiveInternal: " << event.name << std::endl;
#endif
_internalQueue.push_back(event);
// _condVar.notify_all();
}
void InterpreterImpl::receive(const Event& event, bool toFront) {
#if VERBOSE
std::cout << _name << " receive: " << event.name << std::endl;
#endif
if (toFront) {
_externalQueue.push_front(event);
} else {
_externalQueue.push(event);
}
_condVar.notify_all();
}
void InterpreterImpl::internalDoneSend(const Arabica::DOM::Element<std::string>& state) {
if (!isState(state))
return;
if (parentIsScxmlState(state))
return;
Event event;
Arabica::XPath::NodeSet<std::string> doneDatas = filterChildElements(_nsInfo.xmlNSPrefix + "donedata", state);
if (doneDatas.size() > 0) {
// only process first donedata element
Arabica::DOM::Element<std::string> doneData = Element<std::string>(doneDatas[0]);
processParamChilds(doneData, event.params);
Arabica::XPath::NodeSet<std::string> contents = filterChildElements(_nsInfo.xmlNSPrefix + "content", doneDatas[0]);
if (contents.size() > 1)
LOG(ERROR) << "Only a single content element is allowed for send elements - using first one";
if (contents.size() > 0) {
std::string expr;
processContentElement(Element<std::string>(contents[0]), event.dom, event.content, expr);
if (expr.length() > 0) {
try {
event.content =_dataModel.evalAsString(expr);
} catch (Event e) {
e.name = "error.execution";
e.dom = contents[0];
receiveInternal(e);
}
}
}
}
event.name = "done.state." + ATTR_CAST(state.getParentNode(), "id"); // parent?!
receiveInternal(event);
}
void InterpreterImpl::processContentElement(const Arabica::DOM::Element<std::string>& content,
Arabica::DOM::Node<std::string>& dom,
std::string& text,
std::string& expr) {
if (HAS_ATTR(content, "expr")) {
expr = ATTR(content, "expr");
} else if (content.hasChildNodes() || HAS_ATTR(content, "src") || HAS_ATTR(content, "srcexpr")) {
processDOMorText(content, dom, text);
} else {
LOG(ERROR) << "content element does not specify any content.";
}
}
void InterpreterImpl::processDOMorText(const Arabica::DOM::Element<std::string>& element,
Arabica::DOM::Node<std::string>& dom,
std::string& text) {
// do we need to download?
if (HAS_ATTR(element, "src") ||
(HAS_ATTR(element, "srcexpr"))) {
std::stringstream srcContent;
URL sourceURL(HAS_ATTR(element, "srcexpr") ? _dataModel.evalAsString(ATTR(element, "srcexpr")) : ATTR(element, "src"));
if (!sourceURL.toAbsolute(_baseURI)) {
LOG(ERROR) << LOCALNAME(element) << " element has relative src or srcexpr URI with no baseURI set.";
return;
}
if (_cachedURLs.find(sourceURL.asString()) != _cachedURLs.end() && false) {
srcContent << _cachedURLs[sourceURL.asString()];
} else {
srcContent << sourceURL;
if (sourceURL.downloadFailed()) {
LOG(ERROR) << LOCALNAME(element) << " source cannot be downloaded";
return;
}
_cachedURLs[sourceURL.asString()] = sourceURL;
}
if (srcContent.str().length() > 0) {
// try to parse as XML
NameSpacingParser parser;
std::stringstream* ss = new std::stringstream();
(*ss) << srcContent.str();
std::auto_ptr<std::istream> ssPtr(ss);
Arabica::SAX::InputSource<std::string> inputSource;
inputSource.setByteStream(ssPtr);
if (parser.parse(inputSource) && parser.getDocument()) {
Document<std::string> doc = parser.getDocument();
dom = doc.getDocumentElement();
return;
} else {
text = srcContent.str();
return;
}
}
}
if (!element.hasChildNodes())
return;
/**
* Figure out whether the given element contains text, has one child or many childs
*/
bool hasTextContent = false;
bool hasOneChild = false;
Node<std::string> theOneChild;
bool hasManyChilds = false;
Node<std::string> child = element.getFirstChild();
while (child) {
// std::cout << child.getNodeType() << std::endl;
if (child.getNodeType() == Node_base::TEXT_NODE ||
child.getNodeType() == Node_base::CDATA_SECTION_NODE) {
std::string trimmed = child.getNodeValue();
boost::trim(trimmed);
if (trimmed.length() > 0) {
hasTextContent = true;
}
} else {
if (hasOneChild) {
hasManyChilds = true;
hasOneChild = false;
break;
}
hasOneChild = true;
theOneChild = child;
}
child = child.getNextSibling();
}
if (hasOneChild) {
// if we have a single child, it will be the content of the dom
dom = theOneChild;
} else if (hasManyChilds) {
// if we have multiple childs
dom = element;
} else if(hasTextContent) {
child = element.getFirstChild();
while(child) {
if ((child.getNodeType() == Node_base::TEXT_NODE || child.getNodeType() == Node_base::CDATA_SECTION_NODE)) {
text += child.getNodeValue();
}
child = child.getNextSibling();
}
// updated test 179 - conflicts with test 562
// text = _dataModel.evalAsString(text);
} else {
LOG(ERROR) << LOCALNAME(element) << " has neither text nor element children.";
}
}
void InterpreterImpl::processParamChilds(const Arabica::DOM::Element<std::string>& element, std::multimap<std::string, Data>& params) {
NodeSet<std::string> paramElems = filterChildElements(_nsInfo.xmlNSPrefix + "param", element);
for (int i = 0; i < paramElems.size(); i++) {
try {
Element<std::string> paramElem = Element<std::string>(paramElems[i]);
if (!HAS_ATTR(paramElem, "name")) {
LOG(ERROR) << "param element is missing name attribute";
continue;
}
Data paramValue;
if (HAS_ATTR(paramElem, "expr")) {
paramValue = _dataModel.getStringAsData(ATTR(paramElem, "expr"));
} else if(HAS_ATTR(paramElem, "location")) {
paramValue = _dataModel.getStringAsData(ATTR(paramElem, "location"));
} else {
LOG(ERROR) << "param element is missing expr or location or no datamodel is specified";
continue;
}
std::string paramKey = ATTR(paramElem, "name");
params.insert(std::make_pair(paramKey, paramValue));
} catch(Event e) {
LOG(ERROR) << "Syntax error while processing params " << DOMUtils::xPathForNode(paramElems[i]) << ":" << std::endl << e << std::endl;
// test 343
std::multimap<std::string, Data>::iterator paramIter = params.begin();
while(paramIter != params.end()) {
params.erase(paramIter++);
}
e.name = "error.execution";
receiveInternal(e);
break;
}
}
}
void InterpreterImpl::send(const Arabica::DOM::Element<std::string>& element) {
SendRequest sendReq;
// test 331
sendReq.Event::eventType = Event::EXTERNAL;
try {
// event
if (HAS_ATTR(element, "eventexpr")) {
sendReq.name = _dataModel.evalAsString(ATTR(element, "eventexpr"));
} else if (HAS_ATTR(element, "event")) {
sendReq.name = ATTR(element, "event");
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element eventexpr " << DOMUtils::xPathForNode(element) << ":" << std::endl << e << std::endl;
return;
}
try {
// target
if (HAS_ATTR(element, "targetexpr")) {
sendReq.target = _dataModel.evalAsString(ATTR(element, "targetexpr"));
} else if (HAS_ATTR(element, "target")) {
sendReq.target = ATTR(element, "target");
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(element) << " targetexpr:" << std::endl << e << std::endl;
return;
}
try {
// type
if (HAS_ATTR(element, "typeexpr")) {
sendReq.type = _dataModel.evalAsString(ATTR(element, "typeexpr"));
} else if (HAS_ATTR(element, "type")) {
sendReq.type = ATTR(element, "type");
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(element) << " typeexpr:" << std::endl << e << std::endl;
return;
}
try {
// id
if (HAS_ATTR(element, "id")) {
sendReq.sendid = ATTR(element, "id");
} else {
/*
* The ids for <send> and <invoke> are subtly different. In a conformant
* SCXML document, they must be unique within the session, but in the case
* where the author does not provide them, the processor must generate a
* new unique ID not at load time but each time the element is executed.
* Furthermore the attribute 'idlocation' can be used to capture this
* automatically generated id. Finally note that the automatically generated
* id for <invoke> has a special format. See 6.4.1 Attribute Details for
* details. The SCXML processor may generate all other ids in any format,
* as long as they are unique.
*/
/**
*
* If 'idlocation' is present, the SCXML Processor must generate an id when
* the parent <send> element is evaluated and store it in this location.
* See 3.14 IDs for details.
*
*/
sendReq.sendid = ATTR(getParentState(element), "id") + "." + UUID::getUUID();
if (HAS_ATTR(element, "idlocation")) {
_dataModel.assign(ATTR(element, "idlocation"), Data(sendReq.sendid, Data::VERBATIM));
} else {
sendReq.hideSendId = true;
}
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(element) << " idlocation:" << std::endl << e << std::endl;
return;
}
try {
// delay
std::string delay;
sendReq.delayMs = 0;
if (HAS_ATTR(element, "delayexpr")) {
delay = _dataModel.evalAsString(ATTR(element, "delayexpr"));
} else if (HAS_ATTR(element, "delay")) {
delay = ATTR(element, "delay");
}
if (delay.size() > 0) {
boost::trim(delay);
NumAttr delayAttr(delay);
if (iequals(delayAttr.unit, "ms")) {
sendReq.delayMs = strTo<uint32_t>(delayAttr.value);
} else if (iequals(delayAttr.unit, "s")) {
sendReq.delayMs = strTo<double>(delayAttr.value) * 1000;
} else if (delayAttr.unit.length() == 0) { // unit less delay is interpreted as milliseconds
sendReq.delayMs = strTo<uint32_t>(delayAttr.value);
} else {
LOG(ERROR) << "Cannot make sense of delay value " << delay << ": does not end in 's' or 'ms'";
}
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(element) << " delayexpr:" << std::endl << e << std::endl;
return;
}
try {
// namelist
if (HAS_ATTR(element, "namelist")) {
std::list<std::string> names = tokenizeIdRefs(ATTR(element, "namelist"));
for (std::list<std::string>::const_iterator nameIter = names.begin(); nameIter != names.end(); nameIter++) {
if (!_dataModel.isLocation(*nameIter)) {
LOG(ERROR) << "Error in send element " << DOMUtils::xPathForNode(element) << " namelist:" << std::endl << "'" << *nameIter << "' is not a location expression" << std::endl;
ERROR_EXECUTION2(err, "Location expression '" + *nameIter + "' in namelist is invalid", element);
receiveInternal(err);
return;
}
Data namelistValue = _dataModel.getStringAsData(*nameIter);
sendReq.namelist[*nameIter] = namelistValue;
sendReq.data.compound[*nameIter] = namelistValue; // this is questionable
}
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(element) << " namelist:" << std::endl << e << std::endl;
return;
}
try {
// params
processParamChilds(element, sendReq.params);
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(element) << " param expr:" << std::endl << e << std::endl;
return;
}
try {
// content
NodeSet<std::string> contents = filterChildElements(_nsInfo.xmlNSPrefix + "content", element);
if (contents.size() > 1)
LOG(ERROR) << "Only a single content element is allowed for send elements " << DOMUtils::xPathForNode(element) << " - using first one";
if (contents.size() > 0) {
std::string expr;
processContentElement(Element<std::string>(contents[0]), sendReq.dom, sendReq.content, expr);
if (expr.length() > 0) {
try {
sendReq.data = _dataModel.getStringAsData(expr);
} catch (Event e) {
e.name = "error.execution";
receiveInternal(e);
return;
}
// set as content if it's only an atom
if (sendReq.data.atom.length() > 0) {
sendReq.content = sendReq.data.atom;
}
} else if (sendReq.content.length() > 0) {
sendReq.data = Data::fromJSON(sendReq.content);
}
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(element) << " content:" << std::endl << e << std::endl;
return;
}
if (sendReq.dom) {
std::stringstream ss;
ss << sendReq.dom;
sendReq.xml = ss.str();
_dataModel.replaceExpressions(sendReq.xml);
}
assert(_sendIds.find(sendReq.sendid) == _sendIds.end());
_sendIds[sendReq.sendid] = std::make_pair(this, sendReq);
if (sendReq.delayMs > 0) {
_sendQueue->addEvent(sendReq.sendid, InterpreterImpl::delayedSend, sendReq.delayMs, &_sendIds[sendReq.sendid]);
} else {
delayedSend(&_sendIds[sendReq.sendid], sendReq.name);
}
}
void InterpreterImpl::delayedSend(void* userdata, std::string eventName) {
std::pair<InterpreterImpl*, SendRequest>* data = (std::pair<InterpreterImpl*, SendRequest>*)(userdata);
InterpreterImpl* INSTANCE = data->first;
SendRequest sendReq = data->second;
/**
* If neither the 'type' nor the 'typeexpr' is defined, the SCXML Processor
* must assume the default value of http://www.w3.org/TR/scxml/#SCXMLEventProcessor
*/
if (sendReq.type.length() == 0)
sendReq.type = "http://www.w3.org/TR/scxml/#SCXMLEventProcessor";
IOProcessor ioProc = INSTANCE->getIOProcessor(sendReq.type);
if (ioProc) {
try {
ioProc.send(sendReq);
} catch(Event e) {
throw e;
} catch (const std::exception &e) {
LOG(ERROR) << "Exception caught while sending event to ioprocessor " << sendReq.type << ": '" << e.what() << "'";
} catch(...) {
LOG(ERROR) << "Exception caught while sending event to ioprocessor " << sendReq.type;
}
} else {
/**
* If the SCXML Processor does not support the type that is specified, it
* must place the event error.execution on the internal event queue.
*/
ERROR_EXECUTION(exc, "Unsupported type '" + sendReq.type + "' with send element");
INSTANCE->receiveInternal(exc);
}
assert(INSTANCE->_sendIds.find(sendReq.sendid) != INSTANCE->_sendIds.end());
INSTANCE->_sendIds.erase(sendReq.sendid);
}
void InterpreterImpl::invoke(const Arabica::DOM::Element<std::string>& element) {
InvokeRequest invokeReq;
invokeReq.Event::eventType = Event::EXTERNAL;
try {
// type
if (HAS_ATTR(element, "typeexpr")) {
invokeReq.type = _dataModel.evalAsString(ATTR(element, "typeexpr"));
} else if (HAS_ATTR(element, "type")) {
invokeReq.type = ATTR(element, "type");
}
// src
std::string source;
if (HAS_ATTR(element, "srcexpr")) {
source = _dataModel.evalAsString(ATTR(element, "srcexpr"));
} else if (HAS_ATTR(element, "src")) {
source = ATTR(element, "src");
}
if (source.length() > 0) {
URL srcURI(source);
if (!srcURI.toAbsolute(_baseURI)) {
LOG(ERROR) << "invoke element has relative src URI with no baseURI set.";
return;
}
invokeReq.src = srcURI.asString();
}
// id
try {
if (HAS_ATTR(element, "id")) {
invokeReq.invokeid = ATTR(element, "id");
} else {
if (HAS_ATTR(_scxml, "flat") && DOMUtils::attributeIsTrue(ATTR(_scxml, "flat")) && HAS_ATTR(element, "parent")) {
invokeReq.invokeid = ATTR(element, "parent") + "." + UUID::getUUID();
} else {
invokeReq.invokeid = ATTR(getParentState(element), "id") + "." + UUID::getUUID();
}
if (HAS_ATTR(element, "idlocation")) {
_dataModel.assign(ATTR(element, "idlocation"), Data(invokeReq.invokeid, Data::VERBATIM));
}
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in invoke element idlocation:" << std::endl << e << std::endl;
return;
}
// namelist
if (HAS_ATTR(element, "namelist")) {
std::list<std::string> names = tokenizeIdRefs(ATTR(element, "namelist"));
for (std::list<std::string>::const_iterator nameIter = names.begin(); nameIter != names.end(); nameIter++) {
if (!_dataModel.isLocation(*nameIter)) {
LOG(ERROR) << "Error in send element " << DOMUtils::xPathForNode(element) << " namelist:" << std::endl << "'" << *nameIter << "' is not a location expression" << std::endl;
ERROR_EXECUTION2(err, "Location expression '" + *nameIter + "' in namelist is invalid", element);
receiveInternal(err);
return;
}
Data namelistValue = _dataModel.getStringAsData(*nameIter);
invokeReq.namelist[*nameIter] = namelistValue;
invokeReq.data.compound[*nameIter] = namelistValue;
}
}
// autoforward
if (HAS_ATTR(element, "autoforward")) {
if (iequals(ATTR(element, "autoforward"), "true")) {
invokeReq.autoForward = true;
}
} else {
invokeReq.autoForward = false;
}
// params
processParamChilds(element, invokeReq.params);
// content
try {
NodeSet<std::string> contents = filterChildElements(_nsInfo.xmlNSPrefix + "content", element);
if (contents.size() > 1)
LOG(ERROR) << "Only a single content element is allowed for send elements - using first one";
if (contents.size() > 0) {
std::string expr;
processContentElement(Element<std::string>(contents[0]), invokeReq.dom, invokeReq.content, expr);
if (expr.length() > 0) {
try {
invokeReq.data =_dataModel.getStringAsData(expr);
} catch (Event e) {
e.name = "error.execution";
e.dom = contents[0];
receiveInternal(e);
}
} else if (invokeReq.content.length() > 0) {
invokeReq.data = Data::fromJSON(invokeReq.content);
}
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(element) << " content:" << std::endl << e << std::endl;
return;
}
if (invokeReq.dom) {
std::stringstream ss;
ss << invokeReq.dom;
invokeReq.xml = ss.str();
_dataModel.replaceExpressions(invokeReq.xml);
}
// test 422
if (invokeReq.type.size() == 0)
invokeReq.type = "http://www.w3.org/TR/scxml/";
Invoker invoker;
// is there such an invoker already?
if (_invokers.find(invokeReq.invokeid) != _invokers.end()) {
invoker = _invokers[invokeReq.invokeid];
} else {
try {
invoker = _factory->createInvoker(invokeReq.type, this);
invoker.setInvokeId(invokeReq.invokeid);
invoker.setInterpreter(this);
_invokers[invokeReq.invokeid] = invoker;
} catch (Event e) {
receiveInternal(e);
}
}
if (invoker) {
tthread::lock_guard<tthread::recursive_mutex> lock(_pluginMutex);
try {
if (!invoker.getElement())
invoker.setElement(Element<std::string>(element));
if (invoker.getType().size() == 0)
invoker.setType(invokeReq.type);
try {
USCXML_MONITOR_CALLBACK3(beforeInvoking, Arabica::DOM::Element<std::string>(element), invokeReq.invokeid);
invoker.invoke(invokeReq);
LOG(INFO) << "Added invoker " << invokeReq.type << " at " << invokeReq.invokeid;
USCXML_MONITOR_CALLBACK3(afterInvoking, Arabica::DOM::Element<std::string>(element), invokeReq.invokeid)
// this is out of draft but so useful to know when an invoker started
// Event invSuccess;
// invSuccess.name = "invoke.success." + invokeReq.invokeid;
// receive(invSuccess);
} catch(boost::bad_lexical_cast e) {
LOG(ERROR) << "Exception caught while sending invoke request to invoker " << invokeReq.invokeid << ": " << e.what();
} catch (const std::exception &e) {
LOG(ERROR) << "Unknown exception caught while sending invoke request to invoker " << invokeReq.invokeid << ": " << e.what();
} catch(...) {
LOG(ERROR) << "Unknown exception caught while sending invoke request to invoker " << invokeReq.invokeid;
}
try {
// _dataModel.assign("_invokers['" + invokeReq.invokeid + "']", invoker.getDataModelVariables());
} catch (const std::exception &e) {
LOG(ERROR) << "Exception caught while assigning datamodel variables from invoker " << invokeReq.invokeid << ": " << e.what();
} catch(...) {
LOG(ERROR) << "Exception caught while assigning datamodel variables from invoker " << invokeReq.invokeid;
}
} catch (...) {
LOG(ERROR) << "Invoker " << invokeReq.type << " threw an exception";
}
} else {
LOG(ERROR) << "No invoker known for type " << invokeReq.type;
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in invoke element " << DOMUtils::xPathForNode(element) << ":" << std::endl << e << std::endl;
}
}
void InterpreterImpl::cancelInvoke(const Arabica::DOM::Element<std::string>& element) {
std::string invokeId;
if (HAS_ATTR(element, "idlocation")) {
invokeId = _dataModel.evalAsString(ATTR(element, "idlocation"));
} else if (HAS_ATTR(element, "id")) {
invokeId = ATTR(element, "id");
} else {
assert(false);
}
if (_invokers.find(invokeId) != _invokers.end()) {
LOG(INFO) << "Removed invoker at " << invokeId;
try {
// TODO: this is datamodel specific!
//_dataModel.assign("_invokers['" + invokeId + "']", Data(std::string("''"), Data::INTERPRETED));
} catch (Event e) {
LOG(ERROR) << "Syntax when removing invoker:" << std::endl << e << std::endl;
}
USCXML_MONITOR_CALLBACK3(beforeUninvoking, Element<std::string>(element), invokeId)
_invokers[invokeId].uninvoke();
/**
* This should not be necessary. Most invokers have their "clean-up" code in their
* destructor and not their uninvoke method - we need to refactor them all!
*/
if (_invokers[invokeId].deleteOnUninvoke())
_invokers.erase(invokeId);
USCXML_MONITOR_CALLBACK3(beforeUninvoking, Element<std::string>(element), invokeId)
} else {
LOG(ERROR) << "Cannot cancel invoke for id " << invokeId << ": no such invokation";
}
//receiveInternal(Event("done.invoke." + invokeId, Event::PLATFORM));
}
// see: http://www.w3.org/TR/scxml/#EventDescriptors
bool InterpreterImpl::nameMatch(const std::string& eventDescs, const std::string& eventName) {
if(eventDescs.length() == 0 || eventName.length() == 0)
return false;
// naive case of single descriptor and exact match
if (iequals(eventDescs, eventName))
return true;
size_t start = 0;
std::string eventDesc;
for (int i = 0; i < eventDescs.size(); i++) {
if (isspace(eventDescs[i])) {
if (i > 0 && start < i - 1) {
eventDesc = eventDescs.substr(start, i - start);
}
while(isspace(eventDescs[++i])); // skip whitespaces
start = i;
} else if (i + 1 == eventDescs.size()) {
eventDesc = eventDescs.substr(start, i + 1 - start);
}
if (eventDesc.size() > 0) {
// remove optional trailing .* for CCXML compatibility
if (eventDesc.find("*", eventDesc.size() - 1) != std::string::npos)
eventDesc = eventDesc.substr(0, eventDesc.size() - 1);
if (eventDesc.find(".", eventDesc.size() - 1) != std::string::npos)
eventDesc = eventDesc.substr(0, eventDesc.size() - 1);
// was eventDesc the * wildcard
if (eventDesc.size() == 0)
return true;
// eventDesc has to be a real prefix of event now and therefore shorter
if (eventDesc.size() >= eventName.size())
goto NEXT_DESC;
// are they already equal?
if (iequals(eventDesc, eventName))
return true;
if (eventName.find(eventDesc) == 0) {
if (eventName.find(".", eventDesc.size()) == eventDesc.size())
return true;
}
NEXT_DESC:
eventDesc = "";
}
}
return false;
}
bool InterpreterImpl::hasConditionMatch(const Arabica::DOM::Element<std::string>& conditional) {
if (HAS_ATTR(conditional, "cond") && ATTR(conditional, "cond").length() > 0) {
try {
return _dataModel.evalAsBool(conditional, ATTR(conditional, "cond"));
} catch (Event e) {
LOG(ERROR) << "Syntax error in cond attribute of " << TAGNAME(conditional) << " element " << DOMUtils::xPathForNode(conditional) << ":" << std::endl << e << std::endl;
e.name = "error.execution";
receiveInternal(e);
return false;
}
}
return true; // no condition is always true
}
void InterpreterImpl::executeContent(const NodeList<std::string>& content, bool rethrow) {
for (unsigned int i = 0; i < content.getLength(); i++) {
const Arabica::DOM::Node<std::string>& node = content.item(i);
if (node.getNodeType() != Node_base::ELEMENT_NODE)
continue;
try {
executeContent(Element<std::string>(node), true);
}
CATCH_AND_DISTRIBUTE2("Error when executing content", content.item(i));
}
}
void InterpreterImpl::executeContent(const NodeSet<std::string>& content, bool rethrow) {
for (unsigned int i = 0; i < content.size(); i++) {
const Arabica::DOM::Node<std::string>& node = content[i];
if (node.getNodeType() != Node_base::ELEMENT_NODE)
continue;
try {
executeContent(Element<std::string>(node), true);
}
CATCH_AND_DISTRIBUTE2("Error when executing content", content[i]);
}
}
void InterpreterImpl::executeContent(const Arabica::DOM::Element<std::string>& content, bool rethrow) {
if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "onentry") ||
iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "onexit") ||
iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "finalize") ||
iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "transition")) {
// --- CONVENIENCE LOOP --------------------------
NodeList<std::string> executable = content.getChildNodes();
for (int i = 0; i < executable.getLength(); i++) {
const Arabica::DOM::Node<std::string>& childNode = executable.item(i);
if (childNode.getNodeType() != Node_base::ELEMENT_NODE)
continue;
executeContent(Element<std::string>(childNode), rethrow);
}
return;
}
USCXML_MONITOR_CALLBACK2(beforeExecutingContent, Element<std::string>(content))
if (false) {
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "raise")) {
// --- RAISE --------------------------
#if 0
if (HAS_ATTR(content, "event")) {
receiveInternal(Event(ATTR(content, "event")));
}
#else
// Extension for donedata in flat documents - we need to send them internally - use raise
if (HAS_ATTR(content, "event")) {
Event raised(ATTR(content, "event"));
try {
// content
processParamChilds(content, raised.params);
NodeSet<std::string> contents = filterChildElements(_nsInfo.xmlNSPrefix + "content", content);
if (contents.size() > 1)
LOG(ERROR) << "Only a single content element is allowed for raise elements " << DOMUtils::xPathForNode(content) << " - using first one";
if (contents.size() > 0) {
std::string expr;
processContentElement(Element<std::string>(contents[0]), raised.dom, raised.content, expr);
if (expr.length() > 0) {
try {
raised.data = _dataModel.getStringAsData(expr);
} catch (Event e) {
e.name = "error.execution";
receiveInternal(e);
}
// set as content if it's only an atom
if (raised.data.atom.length() > 0) {
raised.content = raised.data.atom;
}
} else if (raised.content.length() > 0) {
raised.data = Data::fromJSON(raised.content);
}
}
} catch (Event e) {
LOG(ERROR) << "Syntax error in send element " << DOMUtils::xPathForNode(content) << " content:" << std::endl << raised << std::endl;
return;
}
if (raised.dom) {
std::stringstream ss;
ss << raised.dom;
raised.xml = ss.str();
_dataModel.replaceExpressions(raised.xml);
}
receiveInternal(raised);
}
#endif
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "if")) {
// --- IF / ELSEIF / ELSE --------------
Arabica::DOM::Element<std::string> ifElem = (Arabica::DOM::Element<std::string>)content;
#if VERBOSE
if (HAS_ATTR(ifElem, "cond"))
std::cout << ATTR(ifElem, "cond") << std::endl;
#endif
/**
* A block is everything up to or between elseifs and else. Those element
* determine whether the block is true and its executable content executed.
*/
if (ifElem.hasChildNodes()) {
bool blockIsTrue = hasConditionMatch(ifElem);
NodeList<std::string> childs = ifElem.getChildNodes();
for (unsigned int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() != Node_base::ELEMENT_NODE)
continue;
Element<std::string> childElem(childs.item(i));
if (iequals(TAGNAME_CAST(childs.item(i)), _nsInfo.xmlNSPrefix + "elseif") ||
iequals(TAGNAME_CAST(childs.item(i)), _nsInfo.xmlNSPrefix + "else")) {
if (blockIsTrue) {
// last block was true, break here
break;
} else {
// is this block the one to execute?
blockIsTrue = hasConditionMatch(childElem);
}
} else {
if (blockIsTrue) {
executeContent(childElem, rethrow);
}
}
}
}
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "elseif")) {
std::cerr << "Found single elsif to evaluate!" << std::endl;
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "else")) {
std::cerr << "Found single else to evaluate!" << std::endl;
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "foreach")) {
// --- FOREACH --------------------------
if (HAS_ATTR(content, "array") && HAS_ATTR(content, "item")) {
std::string array = ATTR(content, "array");
std::string item = ATTR(content, "item");
std::string index = (HAS_ATTR(content, "index") ? ATTR(content, "index") : "");
uint32_t iterations = 0;
try {
iterations = _dataModel.getLength(array);
}
CATCH_AND_DISTRIBUTE2("Syntax error in array attribute of foreach element", content)
try {
_dataModel.pushContext(); // copy old and enter new context
// if (!_dataModel.isDeclared(item)) {
// _dataModel.init(item, Data());
// }
for (uint32_t iteration = 0; iteration < iterations; iteration++) {
_dataModel.setForeach(item, array, index, iteration);
if (content.hasChildNodes())
// execute content and have exception rethrown to break foreach
executeContent(content.getChildNodes(), rethrow);
}
_dataModel.popContext(); // leave stacked context
}
CATCH_AND_DISTRIBUTE2("Syntax error in foreach element", content)
} else {
LOG(ERROR) << "Expected array and item attributes with foreach element!" << std::endl;
}
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "log")) {
// --- LOG --------------------------
Arabica::DOM::Element<std::string> logElem = (Arabica::DOM::Element<std::string>)content;
if (logElem.hasAttribute("label"))
std::cout << logElem.getAttribute("label") << ": ";
if (logElem.hasAttribute("expr")) {
try {
std::cout << _dataModel.evalAsString(logElem.getAttribute("expr")) << std::endl;
}
CATCH_AND_DISTRIBUTE2("Syntax error in expr attribute of log element", content)
} else {
if (logElem.hasAttribute("label"))
std::cout << std::endl;
}
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "assign")) {
// --- ASSIGN --------------------------
if (HAS_ATTR(content, "location")) {
try {
if (!_dataModel.isDeclared(ATTR(content, "location"))) {
// test 286, 331
ERROR_EXECUTION_THROW("Assigning to undeclared location '" + ATTR(content, "location") + "' not allowed.");
} else {
Node<std::string> dom;
std::string text;
processDOMorText(content, dom, text);
_dataModel.assign(Element<std::string>(content), dom, text);
}
}
CATCH_AND_DISTRIBUTE2("Syntax error in attributes of assign element", content)
}
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "validate")) {
// --- VALIDATE --------------------------
std::string location = (HAS_ATTR(content, "location") ? ATTR(content, "location") : "");
std::string schema = (HAS_ATTR(content, "schema") ? ATTR(content, "schema") : "");
_dataModel.validate(location, schema);
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "script")) {
// --- SCRIPT --------------------------
if (HAS_ATTR(content, "src")) {
URL scriptUrl(ATTR(content, "src"));
if (!scriptUrl.isAbsolute() && !_baseURI) {
LOG(ERROR) << "script element has relative URI " << ATTR(content, "src") << " with no base URI set for interpreter";
return;
}
if (!scriptUrl.toAbsolute(_baseURI)) {
LOG(ERROR) << "Failed to convert relative script URI " << ATTR(content, "src") << " to absolute with base URI " << _baseURI.asString();
return;
}
std::stringstream srcContent;
try {
if (_cachedURLs.find(scriptUrl.asString()) != _cachedURLs.end() && false) {
srcContent << _cachedURLs[scriptUrl.asString()];
} else {
srcContent << scriptUrl;
if (scriptUrl.downloadFailed()) {
LOG(ERROR) << "script element source cannot be downloaded";
}
_cachedURLs[scriptUrl.asString()] = scriptUrl;
}
} catch (Event exception) {
// script failed to download
if (exception.name == "error.communication") {
throw exception; // terminate test329, test301
}
receive(exception);
return;
}
try {
_dataModel.eval((Element<std::string>)content, srcContent.str());
}
CATCH_AND_DISTRIBUTE("Syntax error while executing script element from '" + ATTR(content, "src") + "':")
} else {
if (content.hasChildNodes()) {
// search for the text node with the actual script
std::string scriptContent;
for (Node<std::string> child = content.getFirstChild(); child; child = child.getNextSibling()) {
if (child.getNodeType() == Node_base::TEXT_NODE || child.getNodeType() == Node_base::CDATA_SECTION_NODE)
scriptContent += child.getNodeValue();
}
if (scriptContent.size() > 0) {
try {
_dataModel.eval((Element<std::string>)content, scriptContent);
}
CATCH_AND_DISTRIBUTE2("Syntax error while executing script element", content)
}
}
}
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "send")) {
// --- SEND --------------------------
try {
send(content);
}
CATCH_AND_DISTRIBUTE2("Error while sending content", content)
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "cancel")) {
// --- CANCEL --------------------------
std::string sendId;
try {
if (HAS_ATTR(content, "sendidexpr")) {
sendId = _dataModel.evalAsString(ATTR(content, "sendidexpr"));
} else if(HAS_ATTR(content, "sendid")) {
sendId = ATTR(content, "sendid");
} else {
LOG(ERROR) << "Expected sendidexpr or sendid attribute in cancel element";
return;
}
_sendQueue->cancelEvent(sendId);
}
CATCH_AND_DISTRIBUTE2("Syntax error while executing cancel element", content)
} else if (iequals(TAGNAME(content), _nsInfo.xmlNSPrefix + "invoke")) {
// --- INVOKE --------------------------
} else {
// --- Custom Executable Content
ExecutableContent execContent;
if (_executableContent.find(content) == _executableContent.end()) {
_executableContent[content] = _factory->createExecutableContent(content.getLocalName(), content.getNamespaceURI(), this);
}
execContent = _executableContent[content];
execContent.enterElement(content);
if (execContent.processChildren()) {
NodeList<std::string> executable = content.getChildNodes();
for (int i = 0; i < executable.getLength(); i++) {
if (executable.item(i).getNodeType() != Node_base::ELEMENT_NODE)
continue;
executeContent(Element<std::string>(executable.item(i)), rethrow);
}
}
execContent.exitElement(content);
}
USCXML_MONITOR_CALLBACK2(afterExecutingContent, Element<std::string>(content))
}
void InterpreterImpl::finalizeAndAutoForwardCurrentEvent() {
for (std::map<std::string, Invoker>::iterator invokeIter = _invokers.begin();
invokeIter != _invokers.end();
invokeIter++) {
if (iequals(invokeIter->first, _currEvent.invokeid)) {
Arabica::XPath::NodeSet<std::string> finalizes = filterChildElements(_nsInfo.xmlNSPrefix + "finalize", invokeIter->second.getElement());
for (int k = 0; k < finalizes.size(); k++) {
Element<std::string> finalizeElem = Element<std::string>(finalizes[k]);
executeContent(finalizeElem);
}
}
if (HAS_ATTR(invokeIter->second.getElement(), "autoforward") && DOMUtils::attributeIsTrue(ATTR(invokeIter->second.getElement(), "autoforward"))) {
try {
// do not autoforward to invokers that send to #_parent from the SCXML IO Processor!
// Yes do so, see test229!
// if (!boost::equals(_currEvent.getOriginType(), "http://www.w3.org/TR/scxml/#SCXMLEventProcessor"))
invokeIter->second.send(_currEvent);
} catch (const std::exception &e) {
LOG(ERROR) << "Exception caught while sending event to invoker " << invokeIter->first << ": " << e.what();
} catch(...) {
LOG(ERROR) << "Exception caught while sending event to invoker " << invokeIter->first;
}
}
}
}
void InterpreterImpl::returnDoneEvent(const Arabica::DOM::Node<std::string>& state) {
// std::cout << state << std::endl;
if (_parentQueue != NULL) {
Event done;
done.name = "done.invoke." + _sessionId;
_parentQueue->push(done);
}
}
bool InterpreterImpl::parentIsScxmlState(const Arabica::DOM::Element<std::string>& state) {
Arabica::DOM::Element<std::string> parentElem = (Arabica::DOM::Element<std::string>)state.getParentNode();
if (iequals(TAGNAME(parentElem), _nsInfo.xmlNSPrefix + "scxml"))
return true;
return false;
}
bool InterpreterImpl::isInFinalState(const Arabica::DOM::Element<std::string>& state) {
if (isCompound(state)) {
Arabica::XPath::NodeSet<std::string> childs = getChildStates(state);
for (int i = 0; i < childs.size(); i++) {
if (isFinal(Element<std::string>(childs[i])) && isMember(childs[i], _configuration))
return true;
}
} else if (isParallel(state)) {
Arabica::XPath::NodeSet<std::string> childs = getChildStates(state);
for (int i = 0; i < childs.size(); i++) {
if (!isInFinalState(Element<std::string>(childs[i])))
return false;
}
return true;
}
return false;
}
bool InterpreterImpl::isMember(const Arabica::DOM::Node<std::string>& node, const Arabica::XPath::NodeSet<std::string>& set) {
for (int i = 0; i < set.size(); i++) {
if (set[i] == node)
return true;
}
return false;
}
Arabica::XPath::NodeSet<std::string> InterpreterImpl::getChildStates(const Arabica::DOM::Node<std::string>& state) {
Arabica::XPath::NodeSet<std::string> childs;
Arabica::DOM::NodeList<std::string> childElems = state.getChildNodes();
for (int i = 0; i < childElems.getLength(); i++) {
if (childElems.item(i).getNodeType() != Node_base::ELEMENT_NODE)
continue;
if (isState(Element<std::string>(childElems.item(i)))) {
childs.push_back(childElems.item(i));
}
}
return childs;
}
Arabica::XPath::NodeSet<std::string> InterpreterImpl::getChildStates(const Arabica::XPath::NodeSet<std::string>& states) {
Arabica::XPath::NodeSet<std::string> childs;
for (int i = 0; i < states.size(); i++) {
childs.push_back(getChildStates(states[i]));
}
return childs;
}
Arabica::DOM::Element<std::string> InterpreterImpl::getParentState(const Arabica::DOM::Node<std::string>& element) {
Arabica::DOM::Node<std::string> parent = element.getParentNode();
while(parent && !isState(Element<std::string>(parent))) {
parent = parent.getParentNode();
}
return Element<std::string>(parent);
}
Arabica::DOM::Node<std::string> InterpreterImpl::getAncestorElement(const Arabica::DOM::Node<std::string>& node, const std::string tagName) {
Arabica::DOM::Node<std::string> parent = node.getParentNode();
while(parent) {
if (parent.getNodeType() == Node_base::ELEMENT_NODE &&
iequals(TAGNAME_CAST(parent), tagName)) {
return parent;
}
parent = parent.getParentNode();
}
return Arabica::DOM::Node<std::string>();
}
/**
See: http://www.w3.org/TR/scxml/#LCCA
The Least Common Compound Ancestor is the <state> or <scxml> element s such that s is a proper ancestor
of all states on stateList and no descendant of s has this property. Note that there is guaranteed to be
such an element since the <scxml> wrapper element is a common ancestor of all states. Note also that since
we are speaking of proper ancestor (parent or parent of a parent, etc.) the LCCA is never a member of stateList.
*/
Arabica::DOM::Node<std::string> InterpreterImpl::findLCCA(const Arabica::XPath::NodeSet<std::string>& states) {
#if VERBOSE_FIND_LCCA
std::cout << "findLCCA: ";
for (int i = 0; i < states.size(); i++) {
std::cout << ATTR_CAST(states[i], "id") << ", ";
}
std::cout << std::endl << std::flush;
#endif
Arabica::XPath::NodeSet<std::string> ancestors = getProperAncestors(states[0], Arabica::DOM::Node<std::string>());
Arabica::DOM::Node<std::string> ancestor;
for (int i = 0; i < ancestors.size(); i++) {
if (!isCompound(Element<std::string>(ancestors[i])))
continue;
for (int j = 0; j < states.size(); j++) {
#if VERBOSE_FIND_LCCA
std::cout << "Checking " << ATTR_CAST(states[j], "id") << " and " << ATTR_CAST(ancestors[i], "id") << std::endl;
#endif
if (!isDescendant(states[j], ancestors[i]))
goto NEXT_ANCESTOR;
}
ancestor = ancestors[i];
break;
NEXT_ANCESTOR:
;
}
// take uppermost root as ancestor
if (!ancestor)
ancestor = _scxml;
assert(ancestor);
#if VERBOSE_FIND_LCCA
std::cout << " -> " << ATTR_CAST(ancestor, "id") << " " << ancestor.getLocalName() << std::endl;
#endif
return ancestor;
}
Arabica::XPath::NodeSet<std::string> InterpreterImpl::getStates(const std::list<std::string>& stateIds) {
Arabica::XPath::NodeSet<std::string> states;
std::list<std::string>::const_iterator tokenIter = stateIds.begin();
while(tokenIter != stateIds.end()) {
states.push_back(getState(*tokenIter));
tokenIter++;
}
return states;
}
Arabica::DOM::Element<std::string> InterpreterImpl::getState(const std::string& stateId) {
if (_cachedStates.find(stateId) != _cachedStates.end()) {
return _cachedStates[stateId];
}
// first try atomic and compound states
NodeSet<std::string> target = _xpath.evaluate("//" + _nsInfo.xpathPrefix + "state[@id='" + stateId + "']", _scxml).asNodeSet();
if (target.size() > 0)
goto FOUND;
// now parallel states
target = _xpath.evaluate("//" + _nsInfo.xpathPrefix + "parallel[@id='" + stateId + "']", _scxml).asNodeSet();
if (target.size() > 0)
goto FOUND;
// now final states
target = _xpath.evaluate("//" + _nsInfo.xpathPrefix + "final[@id='" + stateId + "']", _scxml).asNodeSet();
if (target.size() > 0)
goto FOUND;
// now history states
target = _xpath.evaluate("//" + _nsInfo.xpathPrefix + "history[@id='" + stateId + "']", _scxml).asNodeSet();
if (target.size() > 0)
goto FOUND;
{
ERROR_EXECUTION_THROW("No state with id '" + stateId + "' found");
}
FOUND:
if (target.size() > 0) {
for (int i = 0; i < target.size(); i++) {
Element<std::string> targetElem(target[i]);
if (!isInEmbeddedDocument(targetElem)) {
_cachedStates[stateId] = targetElem;
return targetElem;
}
}
}
// return the empty node
return Arabica::DOM::Element<std::string>();
}
Arabica::XPath::NodeSet<std::string> InterpreterImpl::getAllStates() {
NodeSet<std::string> states;
states.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "state", _scxml).asNodeSet());
states.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "parallel", _scxml).asNodeSet());
states.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "final", _scxml).asNodeSet());
states.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "history", _scxml).asNodeSet());
return states;
}
Arabica::DOM::Node<std::string> InterpreterImpl::getSourceState(const Arabica::DOM::Element<std::string>& transition) {
if (iequals(TAGNAME_CAST(transition.getParentNode()), _nsInfo.xmlNSPrefix + "initial"))
return transition.getParentNode().getParentNode();
return transition.getParentNode();
}
/**
* In a conformant SCXML document, a compound state may specify either an "initial"
* attribute or an <initial> element, but not both. See 3.6 <initial> for a
* discussion of the difference between the two notations. If neither the "initial"
* attribute nor an <initial> element is specified, the SCXML Processor must use
* the first child state in document order as the default initial state.
*/
Arabica::XPath::NodeSet<std::string> InterpreterImpl::getInitialStates(Arabica::DOM::Element<std::string> state) {
if (!state) {
state = _scxml;
}
#if VERBOSE
std::cout << "Getting initial state of " << TAGNAME(state) << " " << ATTR(state, "id") << std::endl;
#endif
if (isAtomic(state)) {
return Arabica::XPath::NodeSet<std::string>();
}
assert(isCompound(state) || isParallel(state));
if (isParallel(state)) {
return getChildStates(state);
}
// initial attribute at element
Arabica::DOM::Element<std::string> stateElem = (Arabica::DOM::Element<std::string>)state;
if (stateElem.hasAttribute("initial")) {
return getStates(tokenizeIdRefs(stateElem.getAttribute("initial")));
}
// initial element as child - but not the implicit generated one
NodeSet<std::string> initElems = filterChildElements(_nsInfo.xmlNSPrefix + "initial", state);
if(initElems.size() == 1 && !iequals(ATTR_CAST(initElems[0], "generated"), "true")) {
NodeSet<std::string> initTrans = filterChildElements(_nsInfo.xmlNSPrefix + "transition", initElems[0]);
return getTargetStates(Element<std::string>(initTrans[0]));
}
// first child state
Arabica::XPath::NodeSet<std::string> initStates;
NodeList<std::string> childs = state.getChildNodes();
for (int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() != Node_base::ELEMENT_NODE)
continue;
if (isState(Element<std::string>(childs.item(i)))) {
initStates.push_back(childs.item(i));
return initStates;
}
}
// nothing found
return Arabica::XPath::NodeSet<std::string>();
}
NodeSet<std::string> InterpreterImpl::getTargetStates(const Arabica::DOM::Element<std::string>& transition) {
if (_cachedTargets.find(transition) != _cachedTargets.end())
return _cachedTargets[transition];
NodeSet<std::string> targetStates;
assert(boost::ends_with(TAGNAME(transition), "transition"));
// if we are called with a state, process all its transitions
if (isState(transition) || (transition.getNodeType() == Node_base::ELEMENT_NODE && iequals(_nsInfo.xmlNSPrefix + "initial", TAGNAME(transition)))) {
NodeList<std::string> childs = transition.getChildNodes();
for (int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() != Node_base::ELEMENT_NODE)
continue;
Element<std::string> childElem = Element<std::string>(childs.item(i));
if (iequals(TAGNAME(childElem), _nsInfo.xmlNSPrefix + "transition")) {
targetStates.push_back(getTargetStates(childElem));
}
}
_cachedTargets[transition] = targetStates;
return targetStates;
}
std::string targetId = ((Arabica::DOM::Element<std::string>)transition).getAttribute("target");
std::list<std::string> targetIds = InterpreterImpl::tokenizeIdRefs(ATTR(transition, "target"));
for (std::list<std::string>::const_iterator targetIter = targetIds.begin(); targetIter != targetIds.end(); targetIter++) {
Arabica::DOM::Node<std::string> state = getState(*targetIter);
if (state) {
assert(HAS_ATTR_CAST(state, "id"));
targetStates.push_back(state);
}
}
_cachedTargets[transition] = targetStates;
return targetStates;
}
NodeSet<std::string> InterpreterImpl::getTargetStates(const Arabica::XPath::NodeSet<std::string>& transitions) {
NodeSet<std::string> targets;
for (unsigned int i = 0; i < transitions.size(); i++) {
targets.push_back(getTargetStates(Element<std::string>(transitions[i])));
}
return targets;
}
std::list<std::string> InterpreterImpl::tokenize(const std::string& line, const char sep) {
std::list<std::string> tokens;
// appr. 3x faster than stringstream
size_t start = 0;
for (int i = 0; i < line.size(); i++) {
if (line[i] == sep) {
if (i > 0 && start < i) {
tokens.push_back(line.substr(start, i - start));
}
while(line[++i] == sep); // skip multiple occurences of seperator
start = i;
} else if (i + 1 == line.size()) {
tokens.push_back(line.substr(start, i + 1 - start));
}
}
return tokens;
}
std::string InterpreterImpl::spaceNormalize(const std::string& text) {
std::stringstream content;
#if 1
// 195ms with test-performance-events.scml
std::string seperator;
size_t start = 0;
for (int i = 0; i < text.size(); i++) {
if (isspace(text[i])) {
if (i > 0 && start < i) {
content << seperator << text.substr(start, i - start);
seperator = " ";
}
while(isspace(text[++i])); // skip whitespaces
start = i;
} else if (i + 1 == text.size()) {
content << seperator << text.substr(start, i + 1 - start);
}
}
// std::cout << ">>" << content.str() << "<<" << std::endl;
#else
// 291ms with test-performance-events.scml
std::istringstream iss(text);
std::string seperator;
do {
std::string token;
iss >> token;
if (token.length() > 0) {
content << seperator << token;
seperator = " ";
}
} while (iss);
#endif
return content.str();
}
NodeSet<std::string> InterpreterImpl::filterChildElements(const std::string& tagName, const NodeSet<std::string>& nodeSet, bool recurse) {
NodeSet<std::string> filteredChildElems;
for (unsigned int i = 0; i < nodeSet.size(); i++) {
filteredChildElems.push_back(filterChildElements(tagName, nodeSet[i], recurse));
}
return filteredChildElems;
}
NodeSet<std::string> InterpreterImpl::filterChildElements(const std::string& tagName, const Node<std::string>& node, bool recurse) {
NodeSet<std::string> filteredChildElems;
if (!node)
return filteredChildElems;
NodeList<std::string> childs = node.getChildNodes();
for (unsigned int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() != Node_base::ELEMENT_NODE)
continue;
// std::cout << TAGNAME(childs.item(i)) << std::endl;
if(iequals(TAGNAME_CAST(childs.item(i)), tagName)) {
filteredChildElems.push_back(childs.item(i));
}
if (recurse) {
filteredChildElems.push_back(filterChildElements(tagName, childs.item(i), recurse));
}
}
return filteredChildElems;
}
NodeSet<std::string> InterpreterImpl::filterChildType(const Node_base::Type type, const NodeSet<std::string>& nodeSet, bool recurse) {
NodeSet<std::string> filteredChildType;
for (unsigned int i = 0; i < nodeSet.size(); i++) {
filteredChildType.push_back(filterChildType(type, nodeSet[i], recurse));
}
return filteredChildType;
}
NodeSet<std::string> InterpreterImpl::filterChildType(const Node_base::Type type, const Node<std::string>& node, bool recurse) {
NodeSet<std::string> filteredChildTypes;
if (!node)
return filteredChildTypes;
NodeList<std::string> childs = node.getChildNodes();
for (unsigned int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() == type)
filteredChildTypes.push_back(childs.item(i));
if (recurse) {
filteredChildTypes.push_back(filterChildType(type, childs.item(i), recurse));
}
}
return filteredChildTypes;
}
NodeSet<std::string> InterpreterImpl::getProperAncestors(const Arabica::DOM::Node<std::string>& s1,
const Arabica::DOM::Node<std::string>& s2) {
std::pair<Arabica::DOM::Node<std::string>, Arabica::DOM::Node<std::string> > ancPair = std::make_pair(s1, s2);
if (_cachedProperAncestors.find(ancPair) != _cachedProperAncestors.end())
return _cachedProperAncestors[ancPair];
NodeSet<std::string> ancestors;
if (isState(Element<std::string>(s1))) {
Arabica::DOM::Node<std::string> node = s1;
while((node = node.getParentNode())) {
if (node.getNodeType() != Node_base::ELEMENT_NODE)
continue;
Element<std::string> nodeElem(node);
if (!isState(nodeElem))
break;
if (iequals(TAGNAME(nodeElem), _nsInfo.xmlNSPrefix + "scxml")) // do not return scxml root itself - this is somewhat ill-defined
break;
if (!iequals(TAGNAME(nodeElem), _nsInfo.xmlNSPrefix + "parallel") &&
!iequals(TAGNAME(nodeElem), _nsInfo.xmlNSPrefix + "state") &&
!iequals(TAGNAME(nodeElem), _nsInfo.xmlNSPrefix + "scxml"))
break;
if (node == s2)
break;
ancestors.push_back(node);
}
}
_cachedProperAncestors[ancPair] = ancestors;
return ancestors;
}
bool InterpreterImpl::isDescendant(const Arabica::DOM::Node<std::string>& s1,
const Arabica::DOM::Node<std::string>& s2) {
Arabica::DOM::Node<std::string> parent = s1.getParentNode();
while(parent) {
if (s2 == parent)
return true;
parent = parent.getParentNode();
}
return false;
}
bool InterpreterImpl::isTargetless(const Arabica::DOM::Element<std::string>& transition) {
if (transition.hasAttribute("target")) {
return false;
}
return true;
}
bool InterpreterImpl::isState(const Arabica::DOM::Element<std::string>& state) {
if (!state)
return false;
std::string tagName = LOCALNAME(state);
if (iequals("state", tagName))
return true;
if (iequals("scxml", tagName))
return true;
if (iequals("parallel", tagName))
return true;
// if (iequals("history", tagName)) // this is no state, see mail to W3C list
// return true;
if (iequals("final", tagName))
return true;
return false;
}
bool InterpreterImpl::isFinal(const Arabica::DOM::Element<std::string>& state) {
std::string tagName = LOCALNAME(state);
if (iequals("final", tagName))
return true;
if (HAS_ATTR(state, "final") && iequals("true", ATTR(state, "final")))
return true;
return false;
}
bool InterpreterImpl::isInEmbeddedDocument(const Node<std::string>& node) {
// a node is in an embedded document if there is a content element in its parents
Node<std::string> parent = node;
while(parent) {
if(parent == _scxml) {
return false;
}
if(iequals(parent.getLocalName(), "content")) {
return true;
}
parent = parent.getParentNode();
}
return false;
}
bool InterpreterImpl::isInitial(const Arabica::DOM::Element<std::string>& state) {
if (!isState(state))
return false;
Arabica::DOM::Node<std::string> parentNode = state.getParentNode();
if (parentNode.getNodeType() != Node_base::ELEMENT_NODE)
return false;
Arabica::DOM::Element<std::string> parent = (Element<std::string>)parentNode;
if (!isState(parent))
return true; // scxml element
if (isMember(state, getInitialStates(parent)))
return true; // every nested node
// if (isParallel(parent))
// return true;
return false;
}
bool InterpreterImpl::isPseudoState(const Arabica::DOM::Element<std::string>& state) {
std::string tagName = LOCALNAME(state);
if (iequals("initial", tagName))
return true;
if (iequals("history", tagName))
return true;
return false;
}
bool InterpreterImpl::isTransitionTarget(const Arabica::DOM::Element<std::string>& elem) {
return (isState(elem) || iequals(LOCALNAME(elem), "history"));
}
bool InterpreterImpl::isAtomic(const Arabica::DOM::Element<std::string>& state) {
if (iequals("final", LOCALNAME(state)))
return true;
if (iequals("parallel", LOCALNAME(state)))
return false;
Arabica::DOM::NodeList<std::string> childs = state.getChildNodes();
for (unsigned int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() != Node_base::ELEMENT_NODE)
continue;
if (isState(Element<std::string>(childs.item(i))))
return false;
}
return true;
}
bool InterpreterImpl::isHistory(const Arabica::DOM::Element<std::string>& state) {
if (iequals("history", LOCALNAME(state)))
return true;
return false;
}
bool InterpreterImpl::isParallel(const Arabica::DOM::Element<std::string>& state) {
if (!isState(state))
return false;
if (iequals("parallel", LOCALNAME(state)))
return true;
return false;
}
bool InterpreterImpl::isCompound(const Arabica::DOM::Element<std::string>& state) {
if (!isState(state))
return false;
if (iequals(LOCALNAME(state), "parallel")) // parallel is no compound state
return false;
Arabica::DOM::NodeList<std::string> childs = state.getChildNodes();
for (unsigned int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() != Node_base::ELEMENT_NODE)
continue;
if (isState(Element<std::string>(childs.item(i))))
return true;
}
return false;
}
void InterpreterImpl::setupIOProcessors() {
tthread::lock_guard<tthread::recursive_mutex> lock(_pluginMutex);
std::map<std::string, IOProcessorImpl*> ioProcs = _factory->getIOProcessors();
std::map<std::string, IOProcessorImpl*>::iterator ioProcIter = ioProcs.begin();
while(ioProcIter != ioProcs.end()) {
if (iequals(ioProcIter->first, "basichttp") && !(_capabilities & CAN_BASIC_HTTP)) {
ioProcIter++;
continue;
}
if (iequals(ioProcIter->first, "http") && !(_capabilities & CAN_GENERIC_HTTP)) {
ioProcIter++;
continue;
}
// do not override if already set
if (_ioProcessors.find(ioProcIter->first) != _ioProcessors.end()) {
ioProcIter++;
continue;
}
// this might throw error.execution
_ioProcessors[ioProcIter->first] = _factory->createIOProcessor(ioProcIter->first, this);
_ioProcessors[ioProcIter->first].setType(ioProcIter->first);
_ioProcessors[ioProcIter->first].setInterpreter(this);
if (iequals(ioProcIter->first, "http")) {
// this is somewhat ugly
_httpServlet = static_cast<InterpreterHTTPServlet*>(_ioProcessors[ioProcIter->first]._impl.get());
}
if (iequals(ioProcIter->first, "websocket")) {
// this is somewhat ugly
_wsServlet = static_cast<InterpreterWebSocketServlet*>(_ioProcessors[ioProcIter->first]._impl.get());
}
// register aliases
std::list<std::string> names = _ioProcessors[ioProcIter->first].getNames();
std::list<std::string>::iterator nameIter = names.begin();
while(nameIter != names.end()) {
// do not override
if (!boost::equal(*nameIter, ioProcIter->first) && _ioProcessors.find(*nameIter) == _ioProcessors.end())
_ioProcessors[*nameIter] = _ioProcessors[ioProcIter->first];
nameIter++;
}
#if 0
try {
_dataModel.registerIOProcessor(ioProcIter->first, _ioProcessors[ioProcIter->first]);
} catch (Event e) {
LOG(ERROR) << "Syntax error when setting _ioprocessors:" << std::endl << e << std::endl;
}
#endif
ioProcIter++;
}
}
IOProcessor InterpreterImpl::getIOProcessor(const std::string& type) {
tthread::lock_guard<tthread::recursive_mutex> lock(_pluginMutex);
if (_ioProcessors.find(type) == _ioProcessors.end()) {
LOG(ERROR) << "No ioProcessor known for type " << type;
return IOProcessor();
}
return _ioProcessors[type];
}
void InterpreterImpl::setCmdLineOptions(std::map<std::string, std::string> params) {
std::map<std::string, std::string>::iterator paramIter = params.begin();
while (paramIter != params.end()) {
if (paramIter->second.length() > 0) {
_cmdLineOptions.compound[paramIter->first] = Data(paramIter->second, Data::VERBATIM);
} else {
_cmdLineOptions.compound[paramIter->first] = Data("true");
}
paramIter++;
}
}
bool InterpreterImpl::hasLegalConfiguration() {
return isLegalConfiguration(_configuration);
}
bool InterpreterImpl::isLegalConfiguration(const std::list<std::string>& config) {
NodeSet<std::string> states;
for (std::list<std::string>::const_iterator confIter = config.begin(); confIter != config.end(); confIter++) {
Element<std::string> state = getState(*confIter);
if (!state) {
LOG(INFO) << "No state with id '" << *confIter << "'";
return false;
}
states.push_back(state);
while((state = getParentState(state))) {
states.push_back(state);
};
}
return isLegalConfiguration(states);
}
/**
* See: http://www.w3.org/TR/scxml/#LegalStateConfigurations
*/
bool InterpreterImpl::isLegalConfiguration(const NodeSet<std::string>& config) {
// The configuration contains exactly one child of the <scxml> element.
NodeSet<std::string> scxmlChilds = getChildStates(_scxml);
Node<std::string> foundScxmlChild;
for (int i = 0; i < scxmlChilds.size(); i++) {
if (isMember(scxmlChilds[i], config)) {
if (foundScxmlChild) {
LOG(ERROR) << "Invalid configuration: Multiple childs of scxml root are active '" << ATTR_CAST(foundScxmlChild, "id") << "' and '" << ATTR_CAST(scxmlChilds[i], "id") << "'";
return false;
}
foundScxmlChild = scxmlChilds[i];
}
}
if (!foundScxmlChild) {
LOG(ERROR) << "Invalid configuration: No childs of scxml root are active";
return false;
}
// The configuration contains one or more atomic states.
bool foundAtomicState = false;
for (int i = 0; i < config.size(); i++) {
if (isAtomic(Element<std::string>(config[i]))) {
foundAtomicState = true;
break;
}
}
if (!foundAtomicState) {
LOG(ERROR) << "Invalid configuration: No atomic state is active";
return false;
}
// the configuration contains no history pseudo-states
for (int i = 0; i < config.size(); i++) {
if (isHistory(Element<std::string>(config[i]))) {
LOG(ERROR) << "Invalid configuration: history state " << ATTR_CAST(config[i], "id") << " is active";
return false;
}
}
// When the configuration contains an atomic state, it contains all of its <state> and <parallel> ancestors.
for (int i = 0; i < config.size(); i++) {
if (isAtomic(Element<std::string>(config[i]))) {
Node<std::string> parent = config[i];
while(((parent = parent.getParentNode()) && parent.getNodeType() == Node_base::ELEMENT_NODE)) {
if (isState(Element<std::string>(parent)) &&
(iequals(LOCALNAME(parent), "state") ||
iequals(LOCALNAME(parent), "parallel"))) {
if (!isMember(parent, config)) {
LOG(ERROR) << "Invalid configuration: atomic state '" << ATTR_CAST(config[i], "id") << "' is active, but parent '" << ATTR_CAST(parent, "id") << "' is not";
return false;
}
}
}
}
}
// When the configuration contains a non-atomic <state>, it contains one and only one of the state's children
for (int i = 0; i < config.size(); i++) {
Element<std::string> configElem(config[i]);
if (!isAtomic(configElem) && !isParallel(configElem)) {
Node<std::string> foundChildState;
//std::cout << config[i] << std::endl;
NodeSet<std::string> childs = getChildStates(config[i]);
for (int j = 0; j < childs.size(); j++) {
//std::cout << childs[j] << std::endl;
if (isMember(childs[j], config)) {
if (foundChildState) {
LOG(ERROR) << "Invalid configuration: Multiple childs of compound '" << ATTR_CAST(config[i], "id")
<< "' are active '" << ATTR_CAST(foundChildState, "id") << "' and '" << ATTR_CAST(childs[j], "id") << "'";
return false;
}
foundChildState = childs[j];
}
}
if (!foundChildState) {
LOG(ERROR) << "Invalid configuration: No childs of compound '" << ATTR_CAST(config[i], "id") << "' are active";
return false;
}
}
}
// If the configuration contains a <parallel> state, it contains all of its children
for (int i = 0; i < config.size(); i++) {
if (isParallel(Element<std::string>(config[i]))) {
NodeSet<std::string> childs = getChildStates(config[i]);
for (int j = 0; j < childs.size(); j++) {
if (!isMember(childs[j], config) && !isHistory(Element<std::string>(childs[j]))) {
LOG(ERROR) << "Invalid configuration: Not all children of parallel '" << ATTR_CAST(config[i], "id") << "' are active i.e. '" << ATTR_CAST(childs[j], "id") << "' is not";
return false;
}
}
}
}
// everything worked out fine!
return true;
}
bool InterpreterImpl::isInState(const std::string& stateId) {
if (HAS_ATTR(_scxml, "flat") && DOMUtils::attributeIsTrue(ATTR(_scxml, "flat"))) {
// extension for flattened SCXML documents
if (_configuration.size() > 0 && HAS_ATTR_CAST(_configuration[0], "id")) {
// all states are encoded in the current statename
FlatStateIdentifier flatId(ATTR_CAST(_configuration[0], "id"));
for (std::list<std::string>::const_iterator iter = flatId.getActive().begin(); iter != flatId.getActive().end(); iter++) {
if (iequals(stateId, *iter))
return true;
}
}
return false;
} else {
for (int i = 0; i < _configuration.size(); i++) {
if (HAS_ATTR_CAST(_configuration[i], "id") &&
iequals(ATTR_CAST(_configuration[i], "id"), stateId)) {
return true;
}
}
}
return false;
}
void InterpreterImpl::handleDOMEvent(Arabica::DOM::Events::Event<std::string>& event) {
// clear targets
_cachedTargets.clear();
if (event.getType().compare("DOMAttrModified") == 0) // we do not care about other attributes
return;
// remove modified states from cache
Node<std::string> target = Arabica::DOM::Node<std::string>(event.getTarget());
NodeSet<std::string> childs = InterpreterImpl::filterChildElements(_nsInfo.xmlNSPrefix + "state", target);
for (int i = 0; i < childs.size(); i++) {
if (HAS_ATTR_CAST(childs[i], "id")) {
_cachedStates.erase(ATTR_CAST(childs[i], "id"));
}
}
// it's more stress to search through all pairs, just have them recalculated
_cachedProperAncestors.clear();
}
void InterpreterImpl::DOMEventListener::handleEvent(Arabica::DOM::Events::Event<std::string>& event) {
if (_interpreter)
_interpreter->handleDOMEvent(event);
}
std::ostream& operator<< (std::ostream& os, const InterpreterState& interpreterState) {
os << "[" << InterpreterImpl::stateToString(interpreterState) << "]" << std::endl;
return os;
}
std::string InterpreterImpl::stateToString(InterpreterState state) {
std::stringstream ss;
switch(state) {
case USCXML_INSTANTIATED:
ss << "INSTANTIATED";
break;
case USCXML_MICROSTEPPED:
ss << "MICROSTEPPED";
break;
case USCXML_MACROSTEPPED:
ss << "MACROSTEPPED";
break;
case USCXML_IDLE:
ss << "IDLE";
break;
case USCXML_FINISHED:
ss << "FINISHED";
break;
case USCXML_DESTROYED:
ss << "DESTROYED";
break;
default:
ss << "INVALID";
break;
}
return ss.str();
}
}
|