summaryrefslogtreecommitdiffstats
path: root/javatoscachecker/checker/src/main/java/org/onap/tosca/checker/Checker.java
blob: 358dc2bef7e813bc064958f6d3eed7b414b650c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
/*
 * Copyright (c) 2017 <AT&T>.  All rights reserved.
 * ===================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed 
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
 * the specific language governing permissions and limitations under the License.
 */
package org.onap.tosca.checker;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.Reader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.MalformedURLException;

import java.util.HashMap;
import java.util.TreeMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.EnumMap;
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Set;
import java.util.Properties;
import java.util.Collection;
import java.util.Collections;
import java.util.Arrays;
import java.util.MissingResourceException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

import javax.naming.CompositeName;
import javax.naming.InvalidNameException;

import org.yaml.snakeyaml.Yaml;

import com.google.common.collect.Maps;
import com.google.common.collect.MapDifference;
import com.google.common.reflect.Invokable;

import com.google.common.io.CharStreams;

import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;

import kwalify.YamlParser;
import kwalify.Validator;
import kwalify.Rule;
import kwalify.Types;
import kwalify.SchemaException;
import kwalify.SyntaxException;
import kwalify.ValidationException;

import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathException;

import org.apache.commons.lang.reflect.ConstructorUtils;

import org.reflections.Reflections;
import org.reflections.util.FilterBuilder;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.scanners.SubTypesScanner; 
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.adapters.JavaReflectionAdapter;

import org.onap.tosca.checker.annotations.Checks;
import org.onap.tosca.checker.annotations.Catalogs;
import org.onap.tosca.checker.annotations.Validates;

import static org.onap.tosca.checker.Messages.Message;


/*
 * To consider: model consistency checking happens now along with validation
 * (is implemented as part of the validation hooks). It might be better to
 * separate the 2 stages and perform all the consistency checking once 
 * validation is completed.
 */
public class Checker {


  public static void main(String[] theArgs) {

    if (theArgs.length == 0) {
      System.err.println("checker resource_to_validate [processor]*");
      return;
    }

		try {
			Catalog cat = Checker.check(new File(theArgs[0]));

			for (Target t: cat.targets()) {
				System.err.println(t.getLocation() + "\n" + cat.importString(t) + "\n" + t.getReport());
			}

			for (Target t: cat.sortedTargets()) {
				System.out.println(t);
			}

		}
		catch (Exception x) {
			x.printStackTrace();
		}
  }


  private Target   						target = null; //what we're validating at the moment
	private	Map<String, Target>	grammars = new HashMap<String, Target>(); //grammars for the different tosca versions

	private CheckerConfiguration config;
	private Catalog   		catalog;
	private	TargetLocator	locator = new CommonLocator();

	private Table<String, Method, Object> handlers = HashBasedTable.create();
	private Messages											messages;
	private Logger    log = Logger.getLogger(Checker.class.getName());


	private static String[] EMPTY_STRING_ARRAY = new String[0];
	private static final	String[] grammarFiles = new String[] {"tosca/tosca_simple_yaml_1_0.grammar",
																															"tosca/tosca_simple_yaml_1_1.grammar"};	


  public Checker(CheckerConfiguration theConfig) throws CheckerException {
		this.config = theConfig;
    loadGrammars();
		loadAnnotations();
		messages = new Messages();
  }

  public Checker() throws CheckerException {
		this(new CheckerConfiguration());
	}

	private void loadGrammars() throws CheckerException {

		for (String grammarFile: this.config.grammars()) {
			Target grammarTarget = this.locator.resolve(grammarFile);
			if (grammarTarget == null) {
				log.warning("Failed to locate grammar " + grammarFile);
				continue;
			}

    	parseTarget(grammarTarget);
			if (grammarTarget.getReport().hasErrors()) {
				log.warning("Invalid grammar " + grammarFile + ": " + grammarTarget.getReport().toString());
				continue;
			}

			List versions = null;
			try {
				versions = (List)
										((Map)
											((Map)
												((Map)grammarTarget.getTarget())
													.get("mapping"))
														.get("tosca_definitions_version"))
															.get("enum");
			}
			catch (Exception x) {
				log.warning("Invalid grammar " + grammarFile + ": cannot locate tosca_definitions_versions");
			}
			if (versions == null || versions.isEmpty()) {
				log.warning("Invalid grammar " + grammarFile + ": no tosca_definitions_version specified");
				continue;
			}

			for (Object version: versions) {
				this.grammars.put(version.toString(), grammarTarget);
			}
		}

		log.finer("Loaded grammars: " + this.grammars);
	}

	private void loadAnnotations() throws CheckerException {

		Reflections				 reflections = new Reflections(
																			new ConfigurationBuilder()
																						.forPackages("org.onap.tosca")
																						.filterInputsBy(new FilterBuilder()
																															.include(".*\\.class")
																														)
																						.setScanners(new TypeAnnotationsScanner(),
																												 new SubTypesScanner(),
																												 new MethodAnnotationsScanner())
																						.setExpandSuperTypes(false)
																						//.setMetadataAdapter(new JavaReflectionAdapter())
																				);

		Map<Class, Object> refs = new HashMap<Class, Object>();
		Set<Method> 			 methods = null; 
		
		//very similar but annotatons cannot be handled in a more 'generic' manner

		methods = reflections.getMethodsAnnotatedWith(Checks.class);
		for (Method method: methods) {
			handlers.put("checks:" + method.getAnnotation(Checks.class).path(),
									 method,
									 refs.computeIfAbsent(method.getDeclaringClass(),	type -> newInstance(type))); 
		}
			
		methods = reflections.getMethodsAnnotatedWith(Catalogs.class);
		for (Method method: methods) {
			handlers.put("catalogs:" + method.getAnnotation(Catalogs.class).path(),
								   method,
								   refs.computeIfAbsent(method.getDeclaringClass(),	type -> newInstance(type)));
		}
		
		methods = reflections.getMethodsAnnotatedWith(Validates.class);
		for (Method method: methods) {
			Validates annotation =  method.getAnnotation(Validates.class);
			handlers.put(annotation.timing() + "-validates:" + annotation.rule(),
								   method,
								   refs.computeIfAbsent(method.getDeclaringClass(),	type -> newInstance(type)));
		}
	}


	private Object newInstance(Class theType) {
		try {
			return (getClass() == theType) ? this
																 	   : theType.newInstance();
		}
		catch(Exception x) {
			throw new RuntimeException(x); 
		}
	}

	/*
	 * Lookup one of the handlers, by handler type
	 */
	public <T> T getHandler(Class<T> theType) {
		return (T)handlers.values()
											.stream()
									 	  .filter(h -> theType.isInstance(h))
									 		.findFirst()
									 		.orElse(null);
	}

	public CheckerConfiguration configuration() {
		return this.config;
	}

	public void setTargetLocator(TargetLocator theLocator) {
		this.locator = theLocator;
	}

	public TargetLocator getTargetLocator() {
		return this.locator;
	}
	
  public Collection<Target> targets() {
		if (this.catalog == null)
			throw new IllegalStateException("targets are only available after check");

		return this.catalog.targets();
	}

	public Catalog catalog() {
		return this.catalog;
	}

	/* a facility for handling all files in a target directory ..
   */
  public static Catalog check(File theSource)
																	throws CheckerException {
		
		Catalog catalog = new Catalog(commonsCatalog());
		Checker	checker = new Checker();
		try {	
			if (theSource.isDirectory()) {
				for (File f: theSource.listFiles()) {
    	  	if (f.isFile()) {
      	  	checker.check(new Target(theSource.getCanonicalPath(), f.toURI().normalize()), catalog);
      		}
    		}
			}
			else {
      	checker.check(new Target(theSource.getCanonicalPath(), theSource.toURI().normalize()), catalog);
 			}
		}
		catch (IOException iox) {
			throw new CheckerException("Failed to initialize target", iox);
		}

		return catalog;
	}
	
 	/**
	 * Main checking process entry point. In this case the source is passed to the locator in order to
 	 * obtain a {@link org.onap.tosca.checker.Target target}, and then all other processing stages are performed.
	 * @param String the string representation of the uri pointing to the document/template to be processed
	 * @throws CheckerException for any checker encountered error 
	 */	
  public void check(String theSource)
																	throws CheckerException {
		check(theSource, buildCatalog());
	}

	/**
	 * Main checking entry point using a pre-computed Catalog. Same as {@link org.onap.tosca.checker.Chacker#check(String) check} except that the given catalog information is available. i.e. all types available in the given catalog types are
available and the available targets won't be re-processed.
	 */
  public void check(String theSource, Catalog theCatalog)
																							throws CheckerException {
		Target tgt =
					this.locator.resolve(theSource);
		if (null == tgt) {
			throw new CheckerException("Unable to locate the target " + theSource);
		}

		check(tgt, theCatalog);
	}

	/**
	 * Starts the processing after the localization phase, i.e. the Target is obtained/constructed outside the checker.
	 * @param Target the Target representation of the document/template to be processed. The actual target content (yaml
	 *					character string) is obtained by calling {@link org.onap.tosca.checker.Target#open() open} on the target 
	 * @throws CheckerException for any checker encountered error 
	 */
	public void check(Target theTarget) throws CheckerException {
		check(theTarget, buildCatalog());
	}

	/**
	 *
	 * @param Target the Target representation of the document/template to be processed. The actual target content (yaml
	 *					character string) is obtained by calling {@link org.onap.tosca.checker.Target#open() open} on the target 
   * @param theCatalog a default catalog providing common construct definitions
	 * @throws CheckerException for any checker encountered error 
	 */
	public void check(Target theTarget, Catalog theCatalog) throws CheckerException {

		this.catalog = theCatalog;
		this.locator.addSearchPath(theTarget.getLocation());
		
		if (this.catalog.addTarget(theTarget, null)) {
			List<Target> targets = parseTarget(theTarget);
			if (theTarget.getReport().hasErrors())
				return;
			for (Target target: targets) {
				this.catalog.addTarget(target, null);
				//what about this -> this.catalog.addTarget(target, theTarget);
				if (!validateTarget(target).getReport().hasErrors()) {
					checkTarget(target);
				}
			}
		}
	}

	/**
	 * Starts the processing after the {@link org.onap.tosca.checker.Staget#parsed parsed} stage. As such the Target must
	 * have been located (content is available) and {@link org.onap.tosca.checker.Staget#parsed parsed} (the parsed form
   * is stored within the Target, {@see org.onap.tosca.checker.Target#getTarget getTarget}).
   * The target will be validated (grammar) and chcked (consistency). While the checker uses snakeyaml to parse
	 * a yaml document using this entry point allows one to use any other yaml parser for a long as it produces a
	 * compatible representation (java primitive types object representations, Strings, Maps and Lists).
 	 * 
   * @param theTarget the processing subject, located and parsed.
	 * @throws CheckerException for any checker encountered error 
	 */
	public void validate(Target theTarget) throws CheckerException {
		validate(theTarget, buildCatalog());
	}

	/**
	 *
   * @param theTarget the processing subject, located and parsed.
   * @param theCatalog a default catalog providing common construct definitions
   * @throws CheckerException 
	 */
	public void validate(Target theTarget, Catalog theCatalog) throws CheckerException {
		this.catalog = theCatalog;
		this.locator.addSearchPath(theTarget.getLocation());
		
		if (this.catalog.addTarget(theTarget, null)) {
			if (!validateTarget(theTarget).getReport().hasErrors()) {
				checkTarget(theTarget);
			}
		}
	}


  /* */
  protected List<Target> parseTarget(final Target theTarget)
																		throws CheckerException {
		log.entering(getClass().getName(), "parseTarget", theTarget);

		Reader source = null;
		try {
			source = theTarget.open();
		}
		catch (IOException iox) {
			throw new CheckerException("Failed to open target " + theTarget, iox);
		}
		

		List<Object> yamlRoots = new ArrayList<Object>();
    try {
			Yaml yaml = new Yaml();
			for (Object yamlRoot: yaml.loadAll(source)) {
				yamlRoots.add(yamlRoot);
			}

			//yamlRoots.add(
			//				new YamlParser(CharStreams.toString(source)).parse());
    }
/*
		catch(SyntaxException sx) {
			System.out.println(sx.getLineNumber() + ": " + sx.getMessage());
			theTarget.report(sx);
		}
*/
    catch(Exception x) {
			theTarget.report(x);
			return Collections.EMPTY_LIST;
			//return Collections.singletonSet(theTarget);
    }
    finally {
      try {
        source.close();
      }
      catch (IOException iox) {
        //just log it
      }
    }

		List<Target> targets = new ArrayList<Target>(yamlRoots.size());
		if (yamlRoots.size() == 1) {
			//he target turned out to be a bare document
			theTarget.setTarget(yamlRoots.get(0));
			theTarget.setStage(Stage.parsed);
			targets.add(theTarget);
		}
		else {	
			//the target turned out to be a stream containing multiple documents
			for (int i = 0; i < yamlRoots.size(); i++) {
/*
!!We're changing the target below, i.e. we're changing the target implementation hence caching implementation will suffer!!
*/
				Target target = new Target(theTarget.getName(), 
																	 fragmentTargetURI(theTarget.getLocation(), String.valueOf(i)));
				target.setTarget(yamlRoots.get(i));
				target.setStage(Stage.parsed);
				targets.add(target);
			}
		}
	
		log.exiting(getClass().getName(), "parseTarget", theTarget);
    return targets;
  }

	protected URI fragmentTargetURI(URI theRoot, String theFragment) {
		try {
			return new URI(theRoot.getScheme(),
  	      					 theRoot.getSchemeSpecificPart(),
    	    					 theFragment);
		}
		catch(URISyntaxException urisx) {
			throw new RuntimeException();
		}
	}

  protected Target validateTarget(Target theTarget)
																						throws CheckerException {
		log.entering(getClass().getName(), "validateTarget", theTarget);
	
		String version = (String)
											((Map)theTarget.getTarget())
												.get("tosca_definitions_version");
		if (version == null)
			throw new CheckerException("Target " + theTarget + " does not specify a tosca_definitions_version");

		Target grammar = this.grammars.get(version);
		if (grammar == null)
			throw new CheckerException("Target " + theTarget + " specifies unknown tosca_definitions_version " + version);

		TOSCAValidator validator = null;
    try {
      validator = new TOSCAValidator(theTarget, grammar.getTarget());
    }
    catch (SchemaException sx) {
      throw new CheckerException("Grammar error at: " + sx.getPath(), sx);
    }

    theTarget.getReport().addAll(
				validator.validate(theTarget.getTarget()));
		theTarget.setStage(Stage.validated);
		
		if (!theTarget.getReport().hasErrors()) {
			//applyCanonicals(theTarget.getTarget(), validator.canonicals);
    }
    
		log.exiting(getClass().getName(), "validateTarget", theTarget);
		return theTarget;
  }

  /** */
  protected Target checkTarget(Target theTarget) throws CheckerException {
	
		log.entering(getClass().getName(), "checkTarget", theTarget);

		CheckContext ctx = new CheckContext(theTarget);
    //start at the top
		check_service_template_definition(
			(Map<String,Object>)theTarget.getTarget(), ctx);

		theTarget.setStage(Stage.checked);
		log.exiting(getClass().getName(), "checkTarget", theTarget);
		return theTarget;
	}

	private String errorReport(List<Throwable> theErrors) {
    StringBuilder sb = new StringBuilder(theErrors.size() + " errors");
    for (Throwable x: theErrors) {
      sb.append("\n");
			if (x instanceof ValidationException) {
        ValidationException vx = (ValidationException)x;
			  //.apend("at ")
        //.append(error.getLineNumber())
        //.append(" : ")
				sb.append("[")
          .append(vx.getPath())
          .append("] ");
      }
			else if (x instanceof TargetError) {
        TargetError tx = (TargetError)x;
				sb.append("[")
          .append(tx.getLocation())
          .append("] ");
			}
			sb.append(x.getMessage());
			if (x.getCause() != null) {
				sb.append("\n\tCaused by:\n")
          .append(x.getCause());
			}
    }
		sb.append("\n");
		return sb.toString();
	}


  protected void range_definition_post_validation_handler(Object theValue, Rule theRule, Validator.ValidationContext theContext) {
    log.entering("", "range_definition", theContext.getPath());

    assert theRule.getType().equals("seq");
    List bounds = (List)theValue;

    if (bounds.size() != 2) {
      theContext.addError("Too many values in bounds specification", theRule, theValue, null);
      return;
    }

    try { 
      Double.parseDouble(bounds.get(0).toString());  
    }  
    catch(NumberFormatException nfe) {
      theContext.addError("Lower bound not a number", theRule, theValue, null);
    }  

    try { 
      Double.parseDouble(bounds.get(1).toString());  
    }  
    catch(NumberFormatException nfe) {
      if (!"UNBOUNDED".equals(bounds.get(1).toString())) {
        theContext.addError("Upper bound not a number or 'UNBOUNDED'", theRule, theValue, null);
      }
    }  
    
  }
 
  public void check_properties(
								Map<String,Map> theDefinitions, CheckContext theContext) {
		theContext.enter("properties");
    try {
			if(!checkDefinition("properties", theDefinitions, theContext))
				return;

    	for (Iterator<Map.Entry<String,Map>> i = theDefinitions.entrySet().iterator(); i.hasNext(); ) {
      	Map.Entry<String,Map> e = i.next();
				check_property_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
	}

	protected void check_property_definition(
							String theName, Map theDefinition, CheckContext theContext) {
    theContext.enter(theName);
		if (!checkName(theName, theContext) ||
				!checkDefinition(theName, theDefinition, theContext)) {
			return;
    }
    //check the type
    if (!checkDataType (theName, theDefinition, theContext)) {
			return;
		}
    //check default value is compatible with type
		Object defaultValue = theDefinition.get("default");
		if (defaultValue != null) {
			checkDataValuation(defaultValue, theDefinition, theContext);
		}

		theContext.exit();
  }
  
	public void check_attributes(
								Map<String,Map> theDefinitions, CheckContext theContext) {
		theContext.enter("attributes");
    try {
			if(!checkDefinition("attributes", theDefinitions, theContext))
				return;

  	  for (Iterator<Map.Entry<String,Map>> i = theDefinitions.entrySet().iterator(); i.hasNext(); ) {
    	  Map.Entry<String,Map> e = i.next();
				check_attribute_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
	}

  protected void check_attribute_definition(
								String theName, Map theDefinition, CheckContext theContext) {
    theContext.enter(theName);
		try {
			if (!checkName(theName, theContext) ||
					!checkDefinition(theName, theDefinition, theContext)) {
				return;
    	}
			if (!checkDataType(theName, theDefinition, theContext)) {
				return;
			}
		}
		finally {
			theContext.exit();
		}
  }
  
	/* top level rule, we collected the whole information set.
	 * this is where checking starts
	 */
  protected void check_service_template_definition(
										Map<String, Object> theDef, CheckContext theContext) {
    theContext.enter("");

		if (theDef == null) {
			theContext.addError("Empty template", null);
			return;
		}
		
		catalogs("", theDef, theContext); //root
//!!! imports need to be processed first now that catalogging takes place at check time!! 
		//first catalog whatever it is there to be cataloged so that the checks can perform cross-checking
		for (Iterator<Map.Entry<String,Object>> ri = theDef.entrySet().iterator();
		     ri.hasNext(); ) {
			Map.Entry<String,Object> e = ri.next();
			catalogs(e.getKey(), e.getValue(), theContext);
		}

		checks("", theDef, theContext); //root
		for (Iterator<Map.Entry<String,Object>> ri = theDef.entrySet().iterator();
		     ri.hasNext(); ) {
			Map.Entry<String,Object> e = ri.next();
			checks(e.getKey(), e.getValue(), theContext);
		}
    theContext.exit();
  }

	@Catalogs(path="/data_types")
  protected void catalog_data_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
		theContext.enter("data_types");
		try {
			catalogTypes(Construct.Data, theDefinitions, theContext);
		}
		finally {
			theContext.exit();
		}
	}

	@Checks(path="/data_types")
  protected void check_data_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
		theContext.enter("data_types");
		
		try {
			if(!checkDefinition("data_types", theDefinitions, theContext))
		 		return;

    	for (Iterator<Map.Entry<String,Map>> i = theDefinitions.entrySet().iterator(); i.hasNext(); ) {
      	Map.Entry<String,Map> e = i.next();
				check_data_type_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }

  /* */
  protected void check_data_type_definition(String theName,
	                                          Map theDefinition,
																						CheckContext theContext) {
    theContext.enter(theName, Construct.Data);
	  try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDefinition, theContext)) { 
			  return;
      }

			checkTypeConstruct(
			  Construct.Data, theName, theDefinition, theContext);

      if (theDefinition.containsKey("properties")) {
      	check_properties(
					(Map<String,Map>)theDefinition.get("properties"), theContext);
		    checkTypeConstructFacet(Construct.Data, theName, theDefinition, 
																Facet.properties, theContext);
			}
    }
		finally {
		  theContext.exit();
		}
  }
	
	@Catalogs(path="/capability_types")
  protected void catalog_capability_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
    theContext.enter("capability_types");
		try {
			catalogTypes(Construct.Capability, theDefinitions, theContext);
		}
		finally {
			theContext.exit();
		}
	}

  /* */
	@Checks(path="/capability_types")
  protected void check_capability_types(
	                    Map<String, Map> theTypes, CheckContext theContext) {
    theContext.enter("capability_types");
		try {
			if(!checkDefinition("capability_types", theTypes, theContext))
		 		return;

  	  for (Iterator<Map.Entry<String,Map>> i = theTypes.entrySet().iterator(); i.hasNext(); ) {
    	  Map.Entry<String,Map> e = i.next();
      	check_capability_type_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }

  /* */
  protected void check_capability_type_definition(String theName,
																									Map theDefinition,
																									CheckContext theContext) {
	  theContext.enter(theName, Construct.Capability);

    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDefinition, theContext)) {
			  return;
			}

		  checkTypeConstruct(
			  Construct.Capability, theName, theDefinition, theContext);

      if (theDefinition.containsKey("properties")) {
      	check_properties(
					(Map<String,Map>)theDefinition.get("properties"), theContext);
      	checkTypeConstructFacet(Construct.Capability, theName, theDefinition, 
																Facet.properties, theContext);
      }

      if (theDefinition.containsKey("attributes")) {
      	check_attributes(
					(Map<String,Map>)theDefinition.get("attributes"), theContext);
	    	checkTypeConstructFacet(Construct.Capability, theName, theDefinition,
																Facet.attributes, theContext);
			}

	    //valid_source_types: see capability_type_definition
  		//unclear: how is the valid_source_types list definition eveolving across
	  	//the type hierarchy: additive, overwriting, ??
		  if (theDefinition.containsKey("valid_source_types")) {
			  checkTypeReference(Construct.Node, theContext, 
				  ((List<String>)theDefinition.get("valid_source_types")).toArray(EMPTY_STRING_ARRAY));
		  }
    }
		finally {
		  theContext.exit();
		}
	}

	@Catalogs(path="/relationship_types")
  protected void catalog_relationship_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
		theContext.enter("relationship_types");
		try {
			catalogTypes(Construct.Relationship, theDefinitions, theContext);
		}
		finally {
			theContext.exit();
		}
	}

  /* */
	@Checks(path="/relationship_types")
  protected void check_relationship_types(
										Map<String, Map> theDefinition, CheckContext theContext) {
		theContext.enter("relationship_types");
		try {
			if(!checkDefinition("relationship_types", theDefinition, theContext))
		 		return;

    	for (Iterator<Map.Entry<String,Map>> i = theDefinition.entrySet().iterator(); i.hasNext(); ) {
      	Map.Entry<String,Map> e = i.next();
      	check_relationship_type_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }
 
  /* */
	protected void check_relationship_type_definition(String theName,
																										Map theDefinition,
																										CheckContext theContext) {
    theContext.enter(theName, Construct.Relationship);
    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDefinition, theContext)) {
			  return;
			}

		  checkTypeConstruct(
			  Construct.Relationship, theName, theDefinition, theContext);
		  
      if (theDefinition.containsKey("properties")) {
      	check_properties(
					(Map<String,Map>)theDefinition.get("properties"), theContext);
				checkTypeConstructFacet(Construct.Relationship, theName, theDefinition,
											 					Facet.properties, theContext); 
			}
			
      if (theDefinition.containsKey("attributes")) {
      	check_properties(
					(Map<String,Map>)theDefinition.get("attributes"), theContext);
				checkTypeConstructFacet(Construct.Relationship, theName, theDefinition,
											 					Facet.attributes, theContext);
			}

			Map<String,Map> interfaces = (Map<String,Map>)theDefinition.get("interfaces");
      if (interfaces != null) {
			  theContext.enter("interfaces");
        for (Iterator<Map.Entry<String,Map>> i =
								interfaces.entrySet().iterator(); i.hasNext(); ) {
          Map.Entry<String,Map> e = i.next();
          check_type_interface_definition(
						e.getKey(), e.getValue(), theContext);
        }
				theContext.exit();
      }
      
		  if (theDefinition.containsKey("valid_target_types")) {
			  checkTypeReference(Construct.Capability, theContext, 
				  ((List<String>)theDefinition.get("valid_target_types")).toArray(EMPTY_STRING_ARRAY));
			}
    }
		finally {
		  theContext.exit();
		}
  }

	@Catalogs(path="/artifact_types")
  protected void catalog_artifact_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
    theContext.enter("artifact_types");
		try {
			catalogTypes(Construct.Artifact, theDefinitions, theContext);
		}
		finally {
			theContext.exit();
		}
	}

  /* */
	@Checks(path="/artifact_types")
	protected void check_artifact_types(
										Map<String, Map> theDefinition, CheckContext theContext) {
    theContext.enter("artifact_types");
		try {
			if(!checkDefinition("artifact_types", theDefinition, theContext))
		 		return;

  	  for (Iterator<Map.Entry<String,Map>> i = theDefinition.entrySet().iterator(); i.hasNext(); ) {
    	  Map.Entry<String,Map> e = i.next();
				check_artifact_type_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
    	theContext.exit();
		}
  }
	
	/* */
	protected void check_artifact_type_definition(String theName,
																								Map theDefinition,
																								CheckContext theContext) {
    theContext.enter(theName, Construct.Artifact);
    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDefinition, theContext)) {
			  return;
			}

		  checkTypeConstruct(
			  Construct.Artifact, theName, theDefinition, theContext);
		}
		finally {
		  theContext.exit();
		}
  }

	@Catalogs(path="/interface_types")
  protected void catalog_interface_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
    theContext.enter("interface_types");
		try {
			catalogTypes(Construct.Interface, theDefinitions, theContext);
		}
		finally {
			theContext.exit();
		}
	}

	/* */
	@Checks(path="/interface_types")
  protected void check_interface_types(
										Map<String, Map> theDefinition, CheckContext theContext) {
    theContext.enter("interface_types");
		try {
			if(!checkDefinition("interface_types", theDefinition, theContext))
		 		return;

  	  for (Iterator<Map.Entry<String,Map>> i = theDefinition.entrySet().iterator(); i.hasNext(); ) {
    	  Map.Entry<String,Map> e = i.next();
				check_interface_type_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }
	
	/* */
	protected void check_interface_type_definition(String theName,
																								 Map theDefinition,
																								 CheckContext theContext) {
    theContext.enter(theName, Construct.Interface);
    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDefinition, theContext)) {
			  return;
			}

		  checkTypeConstruct(
			  Construct.Interface, theName, theDefinition, theContext);

			//not much else here: a list of operation_definitions, each with its
			//implementation and inputs

			//check that common inputs are re-defined in a compatible manner

			//check that the interface operations are overwritten in a compatible manner
			//for (Iterator<Map.Entry<String,Map>> i = theDefinition.entrySet()

    }
		finally {
		  theContext.exit();
		}
  }

	@Catalogs(path="/node_types")
  protected void catalog_node_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
    theContext.enter("node_types");
		try {
			catalogTypes(Construct.Node, theDefinitions, theContext);
		}
		finally {
			theContext.exit();
		}
	}

  /* */
	@Checks(path="/node_types")
  protected void check_node_types(
										Map<String, Map> theDefinition, CheckContext theContext) {
    theContext.enter("node_types");
		try {
			if(!checkDefinition("node_types", theDefinition, theContext))
		 		return;

  	  for (Iterator<Map.Entry<String,Map>> i = theDefinition.entrySet().iterator(); i.hasNext(); ) {
    	  Map.Entry<String,Map> e = i.next();
				check_node_type_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }

	
	/* */
	protected void check_node_type_definition(String theName,
																						Map theDefinition,
																						CheckContext theContext) {
    theContext.enter(theName, Construct.Node);
      
	  try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDefinition, theContext)) {
			  return;
			}

		  checkTypeConstruct(
			  Construct.Node, theName, theDefinition, theContext);
		  
      if (theDefinition.containsKey("properties")) {
      	check_properties(
					(Map<String,Map>)theDefinition.get("properties"), theContext);
				checkTypeConstructFacet(Construct.Node, theName, theDefinition,
																Facet.properties, theContext);
      }

      if (theDefinition.containsKey("attributes")) {
      	check_properties(
					(Map<String,Map>)theDefinition.get("attributes"), theContext);
				checkTypeConstructFacet(Construct.Node, theName, theDefinition, 
																Facet.attributes, theContext);
			}

  		//requirements
      if (theDefinition.containsKey("requirements")) {
				check_requirements(
				  (List<Map>)theDefinition.get("requirements"), theContext);
			}

  	  //capabilities
      if (theDefinition.containsKey("capabilities")) {
				check_capabilities(
				  (Map<String,Map>)theDefinition.get("capabilities"), theContext);
			}
	  
		  //interfaces: 
			Map<String,Map> interfaces = 
													(Map<String,Map>)theDefinition.get("interfaces");
      if (interfaces != null) {
				try {
			  	theContext.enter("interfaces");
        	for (Iterator<Map.Entry<String,Map>> i =
									interfaces.entrySet().iterator(); i.hasNext(); ) {
          	Map.Entry<String,Map> e = i.next();
          	check_type_interface_definition(
							e.getKey(), e.getValue(), theContext);
        	}
				}
				finally {
					theContext.exit();
				}
      }
		  
			//artifacts
      
    }
		finally {
		  theContext.exit();
		}
  }
  
	@Catalogs(path="/group_types")
  protected void catalog_group_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
    theContext.enter("group_types");
		try {
			catalogTypes(Construct.Group, theDefinitions, theContext);
		}
		finally {
			theContext.exit();
		}
	}

	/* */
	@Checks(path="/group_types")
  protected void check_group_types(
										Map<String, Map> theDefinition, CheckContext theContext) {
    theContext.enter("group_types");
		try {
			if(!checkDefinition("group_types", theDefinition, theContext))
		 		return;

  	  for (Iterator<Map.Entry<String,Map>> i = theDefinition.entrySet().iterator(); i.hasNext(); ) {
    	  Map.Entry<String,Map> e = i.next();
				check_group_type_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }
	
	/* */
	protected void check_group_type_definition(String theName,
																						Map theDefinition,
																						CheckContext theContext) {
    theContext.enter(theName, Construct.Group);
      
	  try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDefinition, theContext)) {
			  return;
			}

		  checkTypeConstruct(
			  Construct.Group, theName, theDefinition, theContext);
      
			if (theDefinition.containsKey("properties")) {
      	check_properties(
					(Map<String,Map>)theDefinition.get("properties"), theContext);
				checkTypeConstructFacet(Construct.Group, theName, theDefinition,
																Facet.properties, theContext);
      }

		  if (theDefinition.containsKey("targets")) {
			  checkTypeReference(Construct.Node, theContext, 
				  ((List<String>)theDefinition.get("targets")).toArray(EMPTY_STRING_ARRAY));
		  }

			//interfaces
			Map<String,Map> interfaces = 
													(Map<String,Map>)theDefinition.get("interfaces");
      if (interfaces != null) {
				try {
				  theContext.enter("interfaces");
      	  for (Iterator<Map.Entry<String,Map>> i =
									interfaces.entrySet().iterator(); i.hasNext(); ) {
     	     Map.Entry<String,Map> e = i.next();
      	    check_type_interface_definition(
							e.getKey(), e.getValue(), theContext);
        	}
				}
				finally {
					theContext.exit();
				}
      }

		}
		finally {
			theContext.exit();
		}
	}
	
	@Catalogs(path="/policy_types")
  protected void catalog_policy_types(
										Map<String, Map> theDefinitions, CheckContext theContext) {
    theContext.enter("policy_types");
		try {
			catalogTypes(Construct.Policy, theDefinitions, theContext);
		}
		finally {
			theContext.exit();
		}
	}

	/* */
	@Checks(path="/policy_types")
  protected void check_policy_types(
										Map<String, Map> theDefinition, CheckContext theContext) {
    theContext.enter("policy_types");
		try {
			if(!checkDefinition("policy_types", theDefinition, theContext))
		 		return;

  	  for (Iterator<Map.Entry<String,Map>> i = theDefinition.entrySet().iterator(); i.hasNext(); ) {
    	  Map.Entry<String,Map> e = i.next();
				check_policy_type_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }

	/* */
	protected void check_policy_type_definition(String theName,
																						Map theDefinition,
																						CheckContext theContext) {
    theContext.enter(theName, Construct.Policy);
      
	  try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDefinition, theContext)) { 
			  return;
			}
		  
			checkTypeConstruct(
			  Construct.Policy, theName, theDefinition, theContext);

			if (theDefinition.containsKey("properties")) {
      	check_properties(
					(Map<String,Map>)theDefinition.get("properties"), theContext);
				checkTypeConstructFacet(Construct.Policy, theName, theDefinition,
																Facet.properties, theContext);
      }

			//the targets can be known node types or group types
			List<String> targets = (List<String>)theDefinition.get("targets");
			if (targets != null) {
			  if (checkDefinition("targets", targets, theContext)) {
					for (String target: targets) {
						if (!(this.catalog.hasType(Construct.Node, target) ||
								  this.catalog.hasType(Construct.Group, target))) {
							theContext.addError(
								Message.INVALID_TYPE_REFERENCE, "targets", target, Arrays.asList(Construct.Node, Construct.Group));
						}
					}
				}
		  }

		}
		finally {
			theContext.exit();
		}
	}

  //checking of actual constructs (capability, ..)

	/* First, interface types do not have a hierarchical organization (no 
	 * 'derived_from' in a interface type definition).
	 * So, when interfaces (with a certain type) are defined in a node
	 * or relationship type (and they can define new? operations), what
	 * is there to check:
	 * 	Can operations here re-define their declaration from the interface
	 * type spec?? From A.5.11.3 we are to understand indicates override to be
	 * the default interpretation .. but they talk about sub-classing so it
	 * probably intended as a reference to the node or relationship type
	 * hierarchy and not the interface type (no hierarchy there).
	 *	Or is this a a case of augmentation where new operations can be added??
	 */
  protected void check_type_interface_definition(
			String theName, Map theDef, CheckContext theContext) {
    theContext.enter(theName);
    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDef, theContext)) {
			  return;
			}

			if (!checkTypeReference(Construct.Interface, theContext, (String)theDef.get("type")))
				return;

      if (theDef.containsKey("inputs")) {
				check_inputs((Map<String, Map>)theDef.get("inputs"), theContext);
			}

			//operations: all entries except for 'type' and 'inputs'
		/*
      for (Iterator<Map.Entry<String,Map>> i = 
							theDef.entrySet().iterator(); i.hasNext(); ) {
        Map.Entry<String,Map> e = i.next();
				String ename = e.getKey();
				if ("type".equals(ename) || "inputs".equals(ename)) {
					continue;
				}
			  ?? check_operation_definition(ename, e.getValue(), theContext);
		  }
		*/
		}
    finally {
		  theContext.exit();
		}
  } 

  /* */
	protected void check_capabilities(Map<String,Map> theDefinition,
																		CheckContext theContext) {
    theContext.enter("capabilities");
		try {
			if(!checkDefinition("capabilities", theDefinition, theContext))
		 		return;

	    for (Iterator<Map.Entry<String,Map>> i = theDefinition.entrySet().iterator(); i.hasNext(); ) {
  	    Map.Entry<String,Map> e = i.next();
				check_capability_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
	}

  /* A capability definition appears within the context ot a node type
	 */
  protected void check_capability_definition(String theName,
	                                           Map theDef,
	                                           CheckContext theContext) {
    theContext.enter(theName, Construct.Capability);

    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDef, theContext)) {
			  return;
			}

      //check capability type
		  if(!checkTypeReference(Construct.Capability, theContext, (String)theDef.get("type")))
        return;
    
      //check properties
      if (!checkFacetAugmentation(
			  		Construct.Capability, theDef, Facet.properties, theContext))
        return;    

      //check attributes
      if (!checkFacetAugmentation(
				  	Construct.Capability, theDef, Facet.attributes, theContext))
        return;    

      //valid_source_types: should point to valid template nodes
		  if (theDef.containsKey("valid_source_types")) {
			  checkTypeReference(Construct.Node, theContext, 
				  ((List<String>)theDef.get("valid_source_types")).toArray(EMPTY_STRING_ARRAY));
				//per A.6.1.4 there is an additinal check to be performed here: 
				//"Any Node Type (names) provides as values for the valid_source_types keyname SHALL be type-compatible (i.e., derived from the same parent Node Type) with any Node Types defined using the same keyname in the parent Capability Type."
			}
      //occurences: were verified in range_definition

		}
    finally {
		  theContext.exit();
		}
  } 

  protected void check_artifact_definition(String theName,
																					 Map theDef,
																					 CheckContext theContext) {
    theContext.enter(theName, Construct.Artifact);

    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDef, theContext)) {
			  return;
			}
      //check artifact type
		  if(!checkTypeReference(Construct.Artifact, theContext, (String)theDef.get("type"))) 
        return;
		}
		finally {
		  theContext.exit();
		}
  }

	protected void check_requirements(List<Map> theDefinition,
																		CheckContext theContext) {
    theContext.enter("requirements");
    try {
			if(!checkDefinition("requirements", theDefinition, theContext))
		 		return;
    
			for (Iterator<Map> i = theDefinition.iterator(); i.hasNext(); ) {
      	Map e = i.next();
				Iterator<Map.Entry<String, Map>> ei =
										(Iterator<Map.Entry<String, Map>>)e.entrySet().iterator();
				Map.Entry<String, Map> eie = ei.next();
				check_requirement_definition(eie.getKey(), eie.getValue(), theContext);
				assert ei.hasNext() == false;
    	}
		}
		finally {
			theContext.exit();
		}
	}

  protected void check_requirement_definition(String theName,
																							Map theDef,
																							CheckContext theContext) {
    theContext.enter(theName, Construct.Requirement);

    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDef, theContext)) {
			  return;
			}
      //check capability type
      String capabilityType = (String)theDef.get("capability");
      if (null != capabilityType) {
	   		checkTypeReference(Construct.Capability, theContext, capabilityType); 
      }

      //check node type
      String nodeType = (String)theDef.get("node");
      if (null != nodeType) {
		  	checkTypeReference(Construct.Node, theContext, nodeType); 
      }

      //check relationship type
      Map relationshipSpec = (Map)theDef.get("relationship");
			String relationshipType = null;
      if (null != relationshipSpec) {
        relationshipType = (String)relationshipSpec.get("type");
		  	if (relationshipType != null) { //should always be the case
  		  	checkTypeReference(Construct.Relationship,theContext,relationshipType); 
			  }

			  Map<String,Map> interfaces = (Map<String,Map>)
																					relationshipSpec.get("interfaces");
        if (interfaces != null) {
				  //augmentation (additional properties or operations) of the interfaces
				  //defined by the above relationship types

					//check that the interface types are known
					for (Map interfaceDef : interfaces.values()) {
						checkTypeReference(Construct.Interface, theContext, (String)interfaceDef.get("type"));
					}
			  }
      }

			//cross checks

			//the capability definition might come from the capability type or from the capability definition
			//within the node type. We might have more than one as a node might specify multiple capabilities of the
			//same type.
			//the goal here is to cross check the compatibility of the valid_source_types specification in the 
			//target capability definition (if that definition contains a valid_source_types entry). 
			List<Map> capabilityDefs = new LinkedList<Map>();
			//nodeType exposes capabilityType
			if (nodeType != null) {
				Map<String,Map> capabilities =
								findTypeFacetByType(Construct.Node, nodeType,
																		Facet.capabilities, capabilityType);
				if (capabilities.isEmpty()) {
					theContext.addError("The node type " + nodeType + " does not appear to expose a capability of a type compatible with " + capabilityType, null);
				}
				else {
					for (Map.Entry<String,Map> capability: capabilities.entrySet()) {
						//this is the capability as it was defined in the node type
						Map capabilityDef = capability.getValue();
						//if it defines a valid_source_types then we're working with it,
						//otherwise we're working with the capability type it points to.
						//The spec does not make it clear if the valid_source_types in a capability definition augments or
						//overwrites the one from the capabilityType (it just says they must be compatible).
						if (capabilityDef.containsKey("valid_source_types")) {
							capabilityDefs.add(capabilityDef);
						}
						else {
							capabilityDef =
								catalog.getTypeDefinition(Construct.Capability, (String)capabilityDef.get("type"));
							if (capabilityDef.containsKey("valid_source_types")) {
								capabilityDefs.add(capabilityDef);
							}
							else {
								//!!if there is a capability that does not have a valid_source_type than there is no reason to
								//make any further verification (as there is a valid node_type/capability target for this requirement)
								capabilityDefs.clear();
								break;
							}
						}
					}
				}
			}
			else {
				Map capabilityDef =	catalog.getTypeDefinition(Construct.Capability, capabilityType);
				if (capabilityDef.containsKey("valid_source_types")) {
					capabilityDefs.add(capabilityDef);
				}
			}

			//check that the node type enclosing this requirement definition
			//is in the list of valid_source_types
			if (!capabilityDefs.isEmpty()) {
				String enclosingNodeType =
										theContext.enclosingConstruct(Construct.Node).name();
				assert enclosingNodeType != null;

				if (!capabilityDefs.stream().anyMatch(
							(Map capabilityDef)->{
								List<String> valid_source_types =
												(List<String>)capabilityDef.get("valid_source_types");
								return valid_source_types.stream().anyMatch(
									(String source_type)-> catalog.isDerivedFrom(
												Construct.Node, enclosingNodeType, source_type));
							})) {
						theContext.addError("Node type: " + enclosingNodeType + " not compatible with any of the valid_source_types provided in the definition of compatible capabilities", null);

				}

				/*
				boolean found = false;
				for (Map capabilityDef: capabilityDefs) {

					List<String> valid_source_types =
											(List<String>)capabilityDef.get("valid_source_types");
					String enclosingNodeType =
										theContext.enclosingConstruct(Construct.Node);
					assert enclosingNodeType != null;

					//make sure enclosingNodeType is compatible (same or derived from)
					//one valid source type
					for (String source_type: valid_source_types) {
						if (catalog.isDerivedFrom(
									Construct.Node, enclosingNodeType, source_type)) {
							found = true;
							break;
						}
					}
				}
				
				if (!found) {
						//the message is not great as it points to the declared
						//capabilityType which is not necessarly where the information
						//is coming from
						theContext.addError("Node type: " + enclosingNodeType + " not compatible with any of the valid_source_types " + valid_source_types + " provided in the definition of capability " + capabilityType, null);
				}
				*/
			}

			//if we have a relationship type, check if it has a valid_target_types
			//if it does, make sure that the capability type is compatible with one
			//of them
		 	if (relationshipType != null) { //should always be the case
				Map relationshipTypeDef = catalog.getTypeDefinition(
																		Construct.Relationship, relationshipType);
				if (relationshipTypeDef != null) {
					List<String> valid_target_types =
								(List<String>)relationshipTypeDef.get("valid_target_types");
					if (valid_target_types != null) {
						boolean found = false;
						for (String target_type: valid_target_types) {
							if (catalog.isDerivedFrom(
										Construct.Capability, capabilityType, target_type)) {
								found = true;
								break;
							}
						}
						if (!found) {
							theContext.addError("Capability type: " + capabilityType + " not compatible with any of the valid_target_types " + valid_target_types + " provided in the definition of relationship type " + relationshipType, null);
						}
					}
				}
			}

			//relationship declares the capabilityType in its valid_target_type set
      //in A.6.9 'Relationship Type' the spec does not indicate how	inheritance
			//is to be applied to the valid_target_type spec: cumulative, overwrites, 
			//so we treat it as an overwrite.
		}
		finally {
		  theContext.exit();
		}
  }
  
	//topology_template_definition and sub-rules
	/* */
	@Catalogs(path="/topology_template")
	protected void catalog_topology_template(
										Map<String,Map> theDef, final CheckContext theContext) {
    
		theContext.enter("topology_template");

		try {		
			theDef.entrySet().stream()
				.forEach(e ->	catalogs(e.getKey(), e.getValue(), theContext));
		}
		finally {
			theContext.exit();
		}
  }

	/** */
	@Checks(path="/topology_template")
	protected void check_topology_template(
										Map<String,Map> theDef, final CheckContext theContext) {
    
		theContext.enter("topology_template");

		try {		
		//	theDef.entrySet().stream()
		//		.forEach(e ->	catalogs(e.getKey(), e.getValue(), theContext));
		
			theDef.entrySet().stream()
				.forEach(e ->	checks(e.getKey(), e.getValue(), theContext));
		}
		finally {
			theContext.exit();
		}
  }


  /*
   * Once the syntax of the imports section is validated parse/validate/catalog    * all the imported template information
   */
	@Checks(path="/imports")
  protected void check_imports(List theImports, CheckContext theContext) {
    theContext.enter("imports");

		for (ListIterator li = theImports.listIterator(); li.hasNext(); ) {
			Object importEntry = li.next(),
						 importFile =  ((Map)mapEntry(importEntry).getValue()).get("file");
			Target tgt = null;
			try {
				tgt = catalog.getTarget( (URI)importFile );
			}
			catch (ClassCastException ccx) {
				System.out.println("Import is " + importFile);
			}

			if (tgt == null) {
				//malfunction
    	  theContext.addError("Checking import '" + importFile + "': failed at a previous stage", null);
				return;
			}

			if (tgt.getReport().hasErrors()) {
				//import failed parsing or validation, we skip it
				continue;
			}

			if (tgt.getStage() == Stage.checked) {
				//been here before, this target had already been processed
				continue;
			}

			//import should have been fully processed by now ??? 
			log.log(Level.FINE, "Processing import " + tgt + ".");
   	  try {
      	checkTarget(tgt);
     	}
   	  catch (CheckerException cx) {
    	  theContext.addError("Failure checking import '" + tgt + "'", cx);
      }
		 
    }
		theContext.exit();
  }

	/* */
	@Checks(path="/topology_template/substitution_mappings")
  protected void check_substitution_mappings(Map<String, Object> theSub,
	                            							 CheckContext theContext) {
    theContext.enter("substitution_mappings");
		try {
			//type is mandatory
			String type = (String)theSub.get("node_type");
  		if (!checkTypeReference(Construct.Node, theContext, type)) {
				return;
			}

			Map<String,List> capabilities = (Map<String,List>)theSub.get("capabilities");
			if (null != capabilities) {
				for (Map.Entry<String,List> ce: capabilities.entrySet()) {
					//the key must be a capability of the type
					if (null == findTypeFacetByName(Construct.Node, type,
																					Facet.capabilities, ce.getKey())) {
    				theContext.addError("Unknown node type capability: " + ce.getKey() + ", type " + type, null);
					}
					//the value is a 2 element list: first is a local node, 
					//second is the name of one of its capabilities
					List target = ce.getValue();
					if (target.size() != 2) {
    				theContext.addError("Invalid capability mapping: " + target + ", expecting 2 elements", null);
						continue;
					}

					String targetNode = (String)target.get(0),
								 targetCapability = (String)target.get(1);
				
					Map<String,Object> targetNodeDef = (Map<String,Object>)
												this.catalog.getTemplate(theContext.target(), Construct.Node, targetNode);
					if (null == targetNodeDef) {
    				theContext.addError("Invalid capability mapping node template: " + targetNode, null);
						continue;
					}

					String targetNodeType = (String)targetNodeDef.get("type");
					if (null == findTypeFacetByName(Construct.Node, targetNodeType,
																		Facet.capabilities, targetCapability)) {
    				theContext.addError("Invalid capability mapping capability: " + targetCapability + ". No such capability found for node template " + targetNode + ", of type " + targetNodeType, null);
					}
				}
			}

			Map<String,List> requirements = (Map<String,List>)theSub.get("requirements");
			if (null != requirements) {
				for (Map.Entry<String,List> re: requirements.entrySet()) {
					//the key must be a requirement of the type
					if (null == findNodeTypeRequirementByName(type, re.getKey())) {
    				theContext.addError("Unknown node type requirement: " + re.getKey() + ", type " + type, null);
					}

					List target = re.getValue();
					if (target.size() != 2) {
    				theContext.addError("Invalid requirement mapping: " + target + ", expecting 2 elements", null);
						continue;
					}

					String targetNode = (String)target.get(0),
								 targetRequirement = (String)target.get(1);
				
					Map<String,Object> targetNodeDef = (Map<String,Object>)
												this.catalog.getTemplate(theContext.target(), Construct.Node, targetNode);
					if (null == targetNodeDef) {
    				theContext.addError("Invalid requirement mapping node template: " + targetNode, null);
						continue;
					}

					String targetNodeType = (String)targetNodeDef.get("type");
					if (null == findNodeTypeRequirementByName(targetNodeType,targetRequirement)) {
    				theContext.addError("Invalid requirement mapping requirement: " + targetRequirement + ". No such requirement found for node template " + targetNode + ", of type " + targetNodeType, null);
					}
				}
			}
		}
		finally {
		  theContext.exit();
		}
	}

  /* */
	@Catalogs(path="/topology_template/inputs")
  protected void catalog_inputs(Map<String, Map> theInputs,
	                            	CheckContext theContext) {
    theContext.enter("inputs");

		try {
			catalogTemplates(Construct.Data, theInputs, theContext);
    }
		finally {
			theContext.exit();
		}
	}

  /* */
	@Checks(path="/topology_template/inputs")
  protected void check_inputs(Map<String, Map> theInputs,
	                            CheckContext theContext) {
    theContext.enter("inputs");

    try {
			if(!checkDefinition("inputs", theInputs, theContext))
		 		return;
    
		  for (Iterator<Map.Entry<String,Map>> i = theInputs.entrySet().iterator(); i.hasNext(); ) {
				Map.Entry<String,Map> e = i.next();
				check_input_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }

	/* */
  protected void check_input_definition(String theName,
																				Map theDef,
																				CheckContext theContext) {
    theContext.enter(theName);
		try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDef, theContext)) {
			  return;
			}
			//
      if (!checkDataType(theName, theDef, theContext)) {
				return;
			}
      //check default value
			Object defaultValue = theDef.get("default");
			if (defaultValue != null) {
				checkDataValuation(defaultValue, theDef, theContext);
			}
		}
		finally {
		  theContext.exit();
		}
	}
  
	@Checks(path="/topology_template/outputs")
	protected void check_outputs(Map<String, Map> theOutputs,
	                            CheckContext theContext) {
    theContext.enter("outputs");

    try {
			if(!checkDefinition("outputs", theOutputs, theContext))
		 		return;
    
		  for (Iterator<Map.Entry<String,Map>> i = theOutputs.entrySet().iterator(); i.hasNext(); ) {
				Map.Entry<String,Map> e = i.next();
				check_output_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }
  
	protected void check_output_definition(String theName,
																				Map theDef,
																				CheckContext theContext) {
    theContext.enter(theName);
		try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDef, theContext)) {
			  return;
			}
      
      //check value
			Object value = theDef.get("value");
			if (value != null) {
				checkDataValuation(value, theDef, theContext);
			}
		}
		finally {
		  theContext.exit();
		}
	}
	
	@Checks(path="/topology_template/groups")
	protected void check_groups(Map<String, Map> theGroups,
	                            CheckContext theContext) {
    theContext.enter("groups");

    try {
			if(!checkDefinition("groups", theGroups, theContext))
		 		return;
    
		  for (Iterator<Map.Entry<String,Map>> i = theGroups.entrySet().iterator(); i.hasNext(); ) {
				Map.Entry<String,Map> e = i.next();
				check_group_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }

	protected void check_group_definition(String theName,
																				Map theDef,
																				CheckContext theContext) {
    theContext.enter(theName);
		try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDef, theContext)) {
			  return;
			}

      if (!checkTypeReference(Construct.Group, theContext, (String)theDef.get("type")))
        return;
			
			if (!checkFacet(
					   Construct.Group, theDef, Facet.properties, theContext))
        return;    
		  
			if (theDef.containsKey("targets")) {
			  //checkTemplateReference(Construct.Node, theContext, 
				//  ((List<String>)theDef.get("targets")).toArray(EMPTY_STRING_ARRAY));
				
				List<String> targetsTypes = (List<String>)
					this.catalog.getTypeDefinition(Construct.Group,
																				 (String)theDef.get("type"))
												.get("targets");

				List<String> targets = (List<String>)theDef.get("targets");
				for (String target: targets) {
					if (!this.catalog.hasTemplate(theContext.target(),Construct.Node, target)) {
						theContext.addError("The 'targets' entry must contain a reference to a node template, '" + target + "' is not one", null);
					}
					else {
						if (targetsTypes != null) {
							String targetType = (String)
								this.catalog.getTemplate(theContext.target(), Construct.Node, target).get("type");
						
							boolean found = false;
							for (String type: targetsTypes) {
								found = this.catalog
												.isDerivedFrom(Construct.Node, targetType, type);
								if (found)
									break;
							}
						
							if (!found) {
								theContext.addError("The 'targets' entry '" + target + "' is not type compatible with any of types specified in policy type targets", null);
							}
						}
					}
				}
		  }
			
			if (theDef.containsKey("interfaces")) {
			}
		}
		finally {
		  theContext.exit();
		}
	}

	@Checks(path="/topology_template/policies")
	protected void check_policies(List<Map<String,Map>> thePolicies,
	                              CheckContext theContext) {
    theContext.enter("policies");

    try {
			if(!checkDefinition("policies", thePolicies, theContext))
		 		return;
   
		 	for (Map<String,Map> policy: thePolicies) {
				assert policy.size() == 1;	
				Map.Entry<String,Map> e = policy.entrySet().iterator().next();
				check_policy_definition(e.getKey(), e.getValue(), theContext);
			}
		}
		finally {
			theContext.exit();
		}
  }
	
	protected void check_policy_definition(String theName,
																				 Map theDef,
																				 CheckContext theContext) {
    theContext.enter(theName);
		try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theDef, theContext)) {
			  return;
			}
      
			if (!checkTypeReference(Construct.Policy, theContext, (String)theDef.get("type")))
        return;
      
			if (!checkFacet(
					   Construct.Policy, theDef, Facet.properties, theContext))
        return;

			//targets: must point to node or group templates (that are of a type
			//specified in the policy type definition, if targets were specified
			//there).
		  if (theDef.containsKey("targets")) {
				List<String> targetsTypes = (List<String>)
					this.catalog.getTypeDefinition(Construct.Policy,
																				 (String)theDef.get("type"))
												.get("targets");

				List<String> targets = (List<String>)theDef.get("targets");
				for (String target: targets) {
					Construct targetConstruct = null;

					if (this.catalog.hasTemplate(theContext.target(),Construct.Group, target)) {
						targetConstruct = Construct.Group;
					}
					else if (this.catalog.hasTemplate(theContext.target(),Construct.Node, target)) {
						targetConstruct = Construct.Node;
					}
					else {
						theContext.addError(Message.INVALID_TEMPLATE_REFERENCE, "targets", target, new Object[] {"node", "group"});
					}
						
					if (targetConstruct != null &&
							targetsTypes != null) {
						//get the target type and make sure is compatible with the types
						//indicated in the type spec
						String targetType = (String)
								this.catalog.getTemplate(theContext.target(), targetConstruct, target).get("type");	

						boolean found = false;
						for (String type: targetsTypes) {
							found = this.catalog
												.isDerivedFrom(targetConstruct, targetType, type);
							if (found)
								break;
						}
						
						if (!found) {
							theContext.addError("The 'targets' " + targetConstruct + " entry '" + target + "' is not type compatible with any of types specified in policy type targets", null);
						}
					}
				}
		  }

			if (theDef.containsKey("triggers")) {
				List<Map> triggers = (List<Map>)theDef.get("triggers");
				//TODO
			}

		}
		finally {
		  theContext.exit();
		}
	}
  
	/* */
	@Catalogs(path="/topology_template/node_templates")
  protected void catalog_node_templates(Map<String, Map> theTemplates,
	                            					CheckContext theContext) {
    theContext.enter("node_templates");

		try {
			catalogTemplates(Construct.Node, theTemplates, theContext);
    }
		finally {
			theContext.exit();
		}
	}

  /* */
	@Checks(path="/topology_template/node_templates")
  protected void check_node_templates(Map<String, Map> theTemplates,
	                                    CheckContext theContext) {
    theContext.enter("node_templates");
    try {
			if(!checkDefinition("node_templates", theTemplates, theContext))
		 		return;

	    for (Iterator<Map.Entry<String,Map>> i = theTemplates.entrySet().iterator(); i.hasNext(); ) {
  	    Map.Entry<String,Map> e = i.next();
				check_node_template_definition(e.getKey(), e.getValue(), theContext);
    	}
		}
		finally {
			theContext.exit();
		}
  }

	/* */
  protected void check_node_template_definition(String theName,
	                                              Map theNode,
                                                CheckContext theContext) {
    theContext.enter(theName, Construct.Node);

    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theNode, theContext)) {
			  return;
			}

      if (!checkTypeReference(Construct.Node, theContext, (String)theNode.get("type")))
        return;
			
			//copy
			String copy = (String)theNode.get("copy");
			if (copy != null) {
				if (!checkTemplateReference(Construct.Node, theContext, copy)) {
					theContext.addError(Message.INVALID_TEMPLATE_REFERENCE, "copy", copy, Construct.Node);
				}
				else {
					//the 'copy' node specification should be used to provide 'defaults'
					//for this specification, we should check them
				}
			}

      /* check that we operate on properties and attributes within the scope of
	  	the specified node type */
      if (!checkFacet(
					   Construct.Node, /*theName,*/theNode, Facet.properties, theContext))
        return;    

      if (!checkFacet(
						 Construct.Node, /*theName,*/theNode, Facet.attributes, theContext))
        return;    

    	//requirement assignment seq
			if (theNode.containsKey("requirements")) {
				check_requirements_assignment_definition(
					(List<Map>)theNode.get("requirements"), theContext);
			}

			//capability assignment map: subject to augmentation
			if (theNode.containsKey("capabilities")) {
				check_capabilities_assignment_definition(
						(Map<String,Map>)theNode.get("capabilities"), theContext);
			}

			//interfaces
			if (theNode.containsKey("interfaces")) {
				check_template_interfaces_definition(
						(Map<String,Map>)theNode.get("interfaces"), theContext);
			}

			//artifacts: artifacts do not have different definition forms/syntax 
			//depending on the context (type or template) but they are still subject 
			//to 'augmentation'
			if (theNode.containsKey("artifacts")) {
				check_template_artifacts_definition(
						(Map<String,Object>)theNode.get("artifacts"), theContext);
			}

			/* node_filter: the context to which the node filter is applied is very
			 * wide here as opposed to the node filter specification in a requirement
			 * assignment which has a more strict context (target node/capability are
			 * specified).
			 * We could check that there are nodes in this template having the 
			 * properties/capabilities specified in this filter, i.e. the filter has
			 * a chance to succeed.
			 */
    }
		finally {
			theContext.exit();
		}
  }
  
	@Checks(path="/topology_template/relationship_templates")
  protected void check_relationship_templates(Map theTemplates,
	                                            CheckContext theContext) {
    theContext.enter("relationship_templates");

    for (Iterator<Map.Entry<String,Map>> i = theTemplates.entrySet().iterator(); i.hasNext(); ) {
      Map.Entry<String,Map> e = i.next();
			check_relationship_template_definition(e.getKey(), e.getValue(), theContext);
    }
		theContext.exit();
  }

  /* */
  protected void check_relationship_template_definition(
																								String theName,
																								Map theRelationship,
																								CheckContext theContext) {
    theContext.enter(theName, Construct.Relationship);
    try {
		  if (!checkName(theName, theContext) ||
			    !checkDefinition(theName, theRelationship, theContext)) {
			  return;
			}

      if (!checkTypeReference(Construct.Relationship, theContext, (String)theRelationship.get("type")))
        return;
			
			String copy = (String)theRelationship.get("copy");
			if (copy != null) {
				if (!checkTemplateReference(Construct.Relationship, theContext, copy)) {
					theContext.addError(Message.INVALID_TEMPLATE_REFERENCE, "copy", copy, Construct.Relationship);
				}
			}

      /* check that we operate on properties and attributes within the scope of
	  	the specified relationship type */
      if (!checkFacet(Construct.Relationship, theRelationship,
											Facet.properties, theContext))
        return;    

      if (!checkFacet(Construct.Relationship, theRelationship,
											Facet.attributes, theContext))
      return;    

    /* interface definitions
		   note: augmentation is allowed here so not clear what to check ..
			 maybe report augmentations if so configured .. */

    }
		finally {
			theContext.exit();
		}
	}

  //requirements and capabilities assignment appear in a node templates
  protected void check_requirements_assignment_definition(
										List<Map> theRequirements, CheckContext theContext) {
		theContext.enter("requirements");
    try {
			if(!checkDefinition("requirements", theRequirements, theContext))
		 		return;
		
			//the node type for the node template enclosing these requirements
			String nodeType =	(String)catalog.getTemplate(
															theContext.target(),
															Construct.Node,
															theContext.enclosingConstruct(Construct.Node).name())
																.get("type");
		
			for(Iterator<Map> ri = theRequirements.iterator(); ri.hasNext(); ) {
				Map<String,Map> requirement = (Map<String,Map>)ri.next();
			
				Iterator<Map.Entry<String,Map>> rai = 
					(Iterator<Map.Entry<String,Map>>)requirement.entrySet().iterator();
			
				Map.Entry<String,Map> requirementEntry = rai.next();
				assert !rai.hasNext();

				String requirementName = requirementEntry.getKey();
				Map		 requirementDef = findNodeTypeRequirementByName(
																								nodeType, requirementName);

				if (requirementDef == null /*&&
						!config.allowAugmentation()*/) {
					theContext.addError("No requirement " + requirementName + " was defined for the node type " + nodeType, null);
					continue;
				}

				check_requirement_assignment_definition(
					requirementName, requirementEntry.getValue(), requirementDef, theContext);
			}
		}
		finally {
    	theContext.exit();
		}
	}
	
	protected void check_requirement_assignment_definition(
																			String theRequirementName,
																			Map theAssignment,
																			Map theDefinition,
																			CheckContext theContext) {
		theContext//.enter("requirement_assignment")
							.enter(theRequirementName, Construct.Requirement);
		
		//grab the node type definition to verify compatibility

	  try {
			//node assignment
			boolean targetNodeIsTemplate = false;
			String targetNode = (String)theAssignment.get("node");
			if (targetNode == null) {
				targetNode = (String)theDefinition.get("node");
				//targetNodeIsTemplate stays false, targetNode must be a type
			}
			else {
				//the value must be a node template or a node type
				targetNodeIsTemplate = isTemplateReference(
																	Construct.Node, theContext, targetNode);
				if (!targetNodeIsTemplate) {
			  	if (!isTypeReference(Construct.Node/*, theContext*/, targetNode)) {
						theContext.addError(Message.INVALID_CONSTRUCT_REFERENCE, "node", targetNode, Construct.Node);
						return;
					}
					//targetNode is a type reference
				}
			
				//additional checks
				String targetNodeDef = (String)theDefinition.get("node");
				if (targetNodeDef != null && targetNode != null) {
					if (targetNodeIsTemplate) {
					//if the target is node template, it must be compatible with the
					//node type specification in the requirement defintion
						String targetNodeType = (String)
								catalog.getTemplate(theContext.target(),Construct.Node,targetNode).get("type");
						if (!catalog.isDerivedFrom(
																Construct.Node, targetNodeType,targetNodeDef)) {
							theContext.addError(Message.INCOMPATIBLE_REQUIREMENT_TARGET, Construct.Node, targetNodeType + " of target node " + targetNode, targetNodeDef);
							return;
						}
					}
					else {
					//if the target is a node type it must be compatible (= or derived
					//from) with the node type specification in the requirement definition
						if (!catalog.isDerivedFrom(
																Construct.Node, targetNode, targetNodeDef)) {
							theContext.addError(Message.INCOMPATIBLE_REQUIREMENT_TARGET, Construct.Node, targetNode, targetNodeDef);
							return;
						}
					}
				}
			}

			String targetNodeType = targetNodeIsTemplate ?
					(String)catalog.getTemplate(theContext.target(),Construct.Node,targetNode).get("type"):
					targetNode;

			//capability assignment
      boolean targetCapabilityIsType = false;
			String targetCapability = (String)theAssignment.get("capability");
			if (targetCapability == null) {
				targetCapability = (String)theDefinition.get("capability");
				//in a requirement definition the target capability can only be a
				//capability type (and not a capability name within some target node
				//type)
				targetCapabilityIsType = true;
			}
			else {
        targetCapabilityIsType = isTypeReference(Construct.Capability, targetCapability);

				//check compatibility with the target compatibility type specified
				//in the requirement definition, if any
				String targetCapabilityDef = (String)theDefinition.get("capability");
				if (targetCapabilityDef != null && targetCapability != null) {
					if (targetCapabilityIsType) {
						if (!catalog.isDerivedFrom(
								Construct.Capability, targetCapability, targetCapabilityDef)) {
							theContext.addError(Message.INCOMPATIBLE_REQUIREMENT_TARGET, Construct.Capability, targetCapability, targetCapabilityDef);
							return;
						}
					}
					else {
						//the capability is from a target node. Find its definition and
						//check that its type is compatible with the capability type
						//from the requirement definition

						//check target capability compatibility with target node		
						if (targetNode == null) {
							theContext.addError("The capability '" + targetCapability + "' is not a capability type, hence it has to be a capability of the node template indicated in 'node', which was not specified", null);
							return;
						}
						if (!targetNodeIsTemplate) {
							theContext.addError("The capability '" + targetCapability + "' is not a capability type, hence it has to be a capability of the node template indicated in 'node', but there you specified a node type", null);
							return;
						}
						//check that the targetNode (its type) indeed has the 
						//targetCapability

						Map<String,Object> targetNodeCapabilityDef = 
																findTypeFacetByName(
																			Construct.Node, targetNodeType,
																			Facet.capabilities,	targetCapability);
						if (targetNodeCapabilityDef == null) {
							theContext.addError("No capability '" + targetCapability + "' was specified in the node " + targetNode + " of type " + targetNodeType, null);
							return;
						}

						String targetNodeCapabilityType = (String)targetNodeCapabilityDef.get("type");

						if (!catalog.isDerivedFrom(Construct.Capability,
																			 targetNodeCapabilityType,
																			 targetCapabilityDef)) {
							theContext.addError("The required target capability type '" + targetCapabilityDef + "' is not compatible with the target capability type found in the target node type capability definition : " + targetNodeCapabilityType + ", targetNode " + targetNode + ", capability name " + targetCapability, null);
							return;
						}
					}
			  }
			}
		
			//relationship assignment
			Map targetRelationship = (Map)theAssignment.get("relationship");
      if (targetRelationship != null) {
				//this has to be compatible with the relationship with the same name
				//from the node type
				//check the type
			}

			//node_filter; used jxpath to simplify the navigation somewhat
			//this is too cryptic
	  	JXPathContext jxPath = JXPathContext.newContext(theAssignment);
			jxPath.setLenient(true);

			List<Map> propertiesFilter = 
									(List<Map>)jxPath.getValue("/node_filter/properties");
			if (propertiesFilter != null) {
				for (Map propertyFilter: propertiesFilter) {
//System.out.println("propertiesFilter " + propertyFilter);
					
					if (targetNode != null) {
						//if we have a target node or node template then it must have
						//have these properties
						for (Object propertyName: propertyFilter.keySet()) {
							if (null == findTypeFacetByName(Construct.Node,
																						  targetNodeType,
																							Facet.properties,
																							propertyName.toString())) {
								theContext.addError("The node_filter property " + propertyName + " is invalid: requirement target node " + targetNode + " does not have such a property", null);
							}
						}
					}
					else if (targetCapability != null) {
			/*
						//if we have a target capability type (but not have a target node)
						//than it must have these properties

			Not true, the filter always refer to node properties: it is the processor's/orchestrator job to match the
			this requirement with a node that satisfies the filter. We cannot anticipate the values of all properties
      (some might come from inputs) so we cannot scan for candidates at this point.


						if (targetCapabilityIsType) {
							for (Object propertyName: propertyFilter.keySet()) {
								if (null == findTypeFacetByName(Construct.Capability,
																								targetCapability,
																								Facet.properties,
																								propertyName.toString())) {
									theContext.addError("The node_filter property " + propertyName + " is invalid: requirement target capability " + targetCapability + " does not have such a property", null);
								}
							}
						}
						else {
							//cannot be: if you point to an explicit capability then you must
							//have specified a targetNode
						}
				*/
					}
					else {
						//what are the properties suppose to filter on ??
					}
				}
			}

			List<Map> capabilitiesFilter = 
											(List<Map>)jxPath.getValue("node_filter/capabilities");
			if (capabilitiesFilter != null) {
				for (Map capabilityFilterDef: capabilitiesFilter) {
					assert capabilityFilterDef.size() == 1;
					Map.Entry<String, Map> capabilityFilterEntry = 
							(Map.Entry<String, Map>)capabilityFilterDef.entrySet().iterator().next();
					String targetFilterCapability = capabilityFilterEntry.getKey();
					Map<String,Object> targetFilterCapabilityDef = null;

					//if we have a targetNode capabilityName must be a capability of
					//that node (type); or it can be simply capability type (but the node
					//must have a capability of that type)

					String targetFilterCapabilityType = null;
					if (targetNode != null) {
						targetFilterCapabilityDef = 
								findTypeFacetByName(Construct.Node, targetNodeType,
																		Facet.capabilities, targetFilterCapability);
						if (targetFilterCapabilityDef != null) {
							targetFilterCapabilityType =
										(String)targetFilterCapabilityDef/*.values().iterator().next()*/.get("type");
						}
						else {
							Map<String,Map> targetFilterCapabilities =
								findTypeFacetByType(Construct.Node, targetNodeType,
																		Facet.capabilities, targetFilterCapability);
							
							if (!targetFilterCapabilities.isEmpty()) {
								if (targetFilterCapabilities.size() > 1) {
									log.warning("check_requirement_assignment_definition: filter check, target node type '" + targetNodeType + "' has more than one capability of type '" + targetFilterCapability + "', not supported");
								}
								//pick the first entry, it represents a capability of the required type
								Map.Entry<String,Map> capabilityEntry = targetFilterCapabilities.entrySet().iterator().next();
								targetFilterCapabilityDef = Collections.singletonMap(capabilityEntry.getKey(),
																																		 capabilityEntry.getValue());
								targetFilterCapabilityType = targetFilterCapability;
							}
						}
					}
					else {
						//no node (type) specified, it can be a straight capability type
						targetFilterCapabilityDef = catalog.getTypeDefinition(
																	Construct.Capability, targetFilterCapability);
						//here comes the odd part: it can still be a just a name in which
						//case we should look at the requirement definition, see which 
						//capability (type) it indicates
						assert targetCapabilityIsType; //cannot be otherwise, we'd need a node
						targetFilterCapabilityDef = catalog.getTypeDefinition(
																	Construct.Capability, targetCapability);
						targetFilterCapabilityType = targetCapability;
					}

					if (targetFilterCapabilityDef == null) {
						theContext.addError("Capability (name or type) " + targetFilterCapability + " is invalid: not a known capability (type) " + 
						((targetNodeType != null) ? (" of node type" + targetNodeType) : ""), null);
						continue;
					}

					for (Map propertyFilter: 
									(List<Map>)jxPath.getValue("/node_filter/capabilities/" + targetFilterCapability + "/properties")) {
						//check that the properties are in the scope of the 
						//capability definition
						for (Object propertyName: propertyFilter.keySet()) {
							if (null == findTypeFacetByName(Construct.Capability,
																							targetCapability,
																							Facet.properties,
																							propertyName.toString())) {
									theContext.addError("The capability filter " + targetFilterCapability + " property " + propertyName + " is invalid: target capability " + targetFilterCapabilityType + " does not have such a property", null);
							}
						}
					}
				}
			}

		}
		finally {
			theContext//.exit()
			          .exit();
		}
  }

	protected void check_capabilities_assignment_definition(
										Map<String,Map> theCapabilities, CheckContext theContext) {
		theContext.enter("capabilities");
    try {
			if(!checkDefinition("capabilities", theCapabilities, theContext))
		 		return;
			
			//the node type for the node template enclosing these requirements
			String nodeType =	(String)catalog.getTemplate(
															theContext.target(),
															Construct.Node,
															theContext.enclosingConstruct(Construct.Node).name())
																.get("type");

			for (Iterator<Map.Entry<String,Map>> ci =
											theCapabilities.entrySet().iterator();
			     ci.hasNext(); ) {
				
				Map.Entry<String,Map> ce = ci.next();

				String capabilityName = ce.getKey();
				Map		 capabilityDef = findTypeFacetByName(Construct.Node, nodeType,
																			Facet.capabilities, capabilityName);
				if (capabilityDef == null) {
					theContext.addError("No capability " + capabilityName + " was defined for the node type " + nodeType, null);
					continue;
				}

				check_capability_assignment_definition(
					capabilityName, ce.getValue(), capabilityDef,theContext);
			}
		}
		finally {
 	   theContext.exit();
		}
	}

	protected void check_capability_assignment_definition(
																			String theCapabilityName,
																			Map theAssignment,
																			Map theDefinition,
																			CheckContext theContext) {

		theContext.enter(theCapabilityName, Construct.Capability);
	  try {
			String capabilityType = (String)theDefinition.get("type");
			//list of property and attributes assignments
			checkFacet(Construct.Capability, theAssignment, capabilityType,
								 Facet.properties, theContext);
			checkFacet(Construct.Capability, theAssignment, capabilityType,
								 Facet.attributes, theContext);
		}
		finally {
			theContext.exit();
		}
	}

	/** */
	protected void check_template_interfaces_definition(
																				Map<String,Map> theInterfaces,
																				CheckContext theContext) {
		theContext.enter("interfaces");
    try {
			if(!checkDefinition("interfaces", theInterfaces, theContext))
		 		return;
			
			//the node type for the node template enclosing these requirements
			String nodeType =	(String)catalog.getTemplate(
															theContext.target(),
															Construct.Node,
															theContext.enclosingConstruct(Construct.Node).name())
																.get("type");

			for (Iterator<Map.Entry<String,Map>> ii =
											theInterfaces.entrySet().iterator();
			     ii.hasNext(); ) {
				
				Map.Entry<String,Map> ie = ii.next();

				String interfaceName = ie.getKey();
				Map		 interfaceDef = findTypeFacetByName(Construct.Node,	nodeType, 
																					Facet.interfaces, interfaceName);
				
				if (interfaceDef == null) {
					/* this is subject to augmentation: this could be a warning but not an error */	
					theContext.addError(Message.INVALID_INTERFACE_REFERENCE, nodeType, interfaceName, Construct.Node);
					continue;
				}

				check_template_interface_definition(
					interfaceName, ie.getValue(), interfaceDef, theContext);
			}
		}
		finally {
			theContext.exit();
		}
	}
	
	protected void check_template_interface_definition(
																			String theInterfaceName,
																			Map theAssignment,
																			Map theDefinition,
																			CheckContext theContext) {

		theContext.enter(theInterfaceName, Construct.Interface);
	  try {
			//check the assignment of the common inputs
//System.out.println("Checking interface inputs for " + theInterfaceName);
			checkFacet(Construct.Interface,
								 theAssignment,
								 (String)theDefinition.get("type"),
								 Facet.inputs,
								 theContext);

			//check the assignment of inputs in each operation
			//unfortunately operations are not defined as a facet (grouped under a
			//facet name) i.e. operations..
			
/*
			Map<String, Map> inputsDefs = theDefinition.get("inputs");
			Map<String,?> inputs = theAssignment.get("inputs");
			
			if (inputs != null && !inputs.isEmpty()) {
				for (Map.Entry inputEntry: input.entrySet()) {
					//check the input name part of the definition
					if (inputDefs != null && inputDefs.containsKey(inputEntry.getKey())) {
						checkDataValuation(inputEntry.getValue(),
															 inputsDefs.get(inputEntry.getKey()),
															 theContext);						
					}
					else {
						theContext.addError("No input " + inputEntry.getKey() + " was defined for the interface " + theInterfaceName, null);
					}
				}
			}
*/
/*
			String interfaceType = (String)theDefinition.get("type");
			//list of property and attributes assignments
			checkFacet(Construct.Interface, theAssignment, interfaceType,
								 "inputs", theContext);
*/
			//the interface operations: can new operations be defined here??
		}
		finally {
			theContext.exit();
		}
	}

	
	@Checks(path="/topology_template/artifacts")
	protected void check_template_artifacts_definition(
																				Map<String,Object> theDefinition,
																				CheckContext theContext) {		
		theContext.enter("artifacts");
    try {
		}
		finally {
			theContext.exit();
		}
	}
	
	protected void check_template_artifact_definition(
																			String theArtifactName,
																			Map theAssignment,
																			Map theDefinition,
																			CheckContext theContext) {

		theContext.enter(theArtifactName, Construct.Artifact);
	  try {

		}
		finally {
			theContext.exit();
		}
	}

  //generic checking actions, not related to validation rules


  /* the type can be:
   *   a known type: predefined or user-defined
   *   a collection (list or map) and then check that the entry_schema points to one of the first two cases (is that it?)
   */
  protected boolean checkDataType(
											String theName, Map theSpec, CheckContext theContext) {
	  
		if (!checkTypeReference(Construct.Data, theContext, (String)theSpec.get("type")))
      return false;

	  String type = (String)theSpec.get("type");
    if (/*isCollectionType(type)*/
        "list".equals(type) || "map".equals(type)) {
 	   	Map entry_schema = (Map)theSpec.get("entry_schema");
  	  if (entry_schema == null) {
      	//maybe issue a warning ?? or is 'string' the default??
       	return true;
     	}

			if (!catalog.hasType(Construct.Data,(String)entry_schema.get("type"))) {
       	theContext.addError("Unknown entry_schema type: " + entry_schema, null);
       	return false;
     	}
    }
    return true;
  }

  /*
	 * generic checks for a type specification
	 */
  protected boolean checkTypeConstruct(Construct theConstruct,
	                                     String theTypeName,
	                                     Map theDef,
																			 CheckContext theContext) {
		/* There is a 'weakness' in the super-type check before: the search for the supertype is done globally and 
		 * not strictly on the 'import' path, i.e. one should explore for the super-type definition the target sub-tree
		 * starting at the current target and not ALL the targets
		 */
		String parentType = (String)theDef.get("derived_from");
		if (parentType != null && !catalog.hasType(theConstruct, parentType)) {
			theContext.addError(
				Message.INVALID_TYPE_REFERENCE, "derived_from", parentType, theConstruct);
			return false;
		}
    return true;
  }

  /* Check that a particular facet (properties, attributes) of a construct type
	 * (node type, capability type, etc) is correctly (consistenly) defined
	 * across a type hierarchy
	 */
  protected boolean checkTypeConstructFacet(Construct theConstruct,
	                                          String theTypeName,
	                                          Map theTypeSpec,
	                                          Facet theFacet,
																			      CheckContext theContext) {
    Map<String, Map> defs =
		   	               (Map<String,Map>)theTypeSpec.get(theFacet.name());
    if (null == defs) {
      return true;
    }

    boolean res = true;

    //given that the type was cataloged there will be at least one entry
    Iterator<Map.Entry<String,Map>> i =
															catalog.hierarchy(theConstruct, theTypeName);
		if (!i.hasNext()) {
      theContext.addError(
			  "The type " + theTypeName + " needs to be cataloged before attempting 'checkTypeConstruct'", null);
			return false;
		}
    i.next(); //skip self
    while(i.hasNext()) {
      Map.Entry<String,Map> e = i.next();
      Map<String, Map> superDefs = (Map<String,Map>)e.getValue()
																												.get(theFacet.name());
      if (null == superDefs) {
        continue;
      }
      //this computes entries that appear on both collections but with different values, i.e. the re-defined properties
      Map<String, MapDifference.ValueDifference<Map>> diff = Maps.difference(defs, superDefs).entriesDiffering();
      
      for (Iterator<Map.Entry<String, MapDifference.ValueDifference<Map>>> di = diff.entrySet().iterator(); di.hasNext(); ) {
         Map.Entry<String, MapDifference.ValueDifference<Map>> de = di.next();
         MapDifference.ValueDifference<Map> dediff = de.getValue();
         log.finest(
           theConstruct + " type " + theFacet + ": " + de.getKey() + " has been re-defined between the " + theConstruct + " types " + e.getKey() + " and " + theTypeName);
         //for now we just check that the type is consistenly re-declared
         //if (!dediff.leftValue().get("type").equals(dediff.rightValue().get("type"))) {
         if (!this.catalog.isDerivedFrom(theFacet.construct(),
												 						(String)dediff.leftValue().get("type"),
												 						(String)dediff.rightValue().get("type"))) {
           theContext.addError(
					  theConstruct + " type " + theFacet + ", redefiniton changed its type: "+ de.getKey() + " has been re-defined between the " + theConstruct + " types " + e.getKey() + " and " + theTypeName + " in an incompatible manner", null);
           res = false;  
         }
      }
    }

    return res;   
  }

  /*
	 * Checks the validity of a certain facet of a construct
	 * (properties of a node) across a type hierarchy.
   * For now the check is limited to a verifying that a a facet was declared
	 * somewhere in the construct type hierarchy (a node template property has
	 * been declared in the node type hierarchy).
	 *
	 * 2 versions with the more generic allowing the specification of the type
	 * to be done explicitly.
   */
  protected boolean checkFacet(Construct theConstruct,
															 Map theSpec,
															 Facet theFacet,
															 CheckContext theContext) {
		return checkFacet(theConstruct, theSpec, null, theFacet, theContext);
	}
	
	/**
	 * We walk the hierarchy and verify the assignment of a property with respect to its definition.
	 * We also collect the names of those properties defined as required but for which no assignment was provided.
 	 */
	protected boolean checkFacet(Construct theConstruct,
															 Map theSpec,
															 String theSpecType,
															 Facet theFacet,
															 CheckContext theContext) {

    Map<String,Map> defs = (Map<String,Map>)theSpec.get(theFacet.name());
    if (null == defs) {
      return true;
    }
    defs = Maps.newHashMap(defs); //

    boolean res = true;
		if (theSpecType == null) {
			theSpecType = (String)theSpec.get("type");
    }
		if (theSpecType == null) {
       theContext.addError("No specification type available", null);
			return false;
		}

		Map<String,Byte> missed = new HashMap<String, Byte>();  //keeps track of the missing required properties, the value is 
																											 //false if a default was found along the hierarchy
    Iterator<Map.Entry<String,Map>> i =
													catalog.hierarchy(theConstruct, theSpecType);
    while (i.hasNext() && !defs.isEmpty()) {
      Map.Entry<String,Map> type = i.next();

      Map<String, Map> typeDefs = (Map<String,Map>)type.getValue()
																													.get(theFacet.name());
      if (null == typeDefs) {
        continue;
      }

      MapDifference<String, Map> diff = Maps.difference(defs, typeDefs);

			//this are the ones this type and the spec have in common (same key,
			//different values)
      Map<String, MapDifference.ValueDifference<Map>> facetDefs = 
																								diff.entriesDiffering();
			//TODO: this assumes the definition of the facet is not cumulative, i.e.
			//subtypes 'add' something to the definition provided by the super-types
			//it considers the most specialized definition stands on its own
			for (MapDifference.ValueDifference<Map> valdef: facetDefs.values()) {
				checkDataValuation(valdef.leftValue(), valdef.rightValue(), theContext);
			}

			//the ones that appear in the type but not in spec; ensure the type does not requires them.
/*
			Map<String, Map> unassigned = diff.entriesOnlyOnRight();
			for (Map.Entry<String, Map> unassignedEntry: unassigned.entrySet()) {

System.out.println(" **** unassigned -> " + unassignedEntry.getKey() + " : " + unassignedEntry.getValue());

				if (unassignedEntry.getValue().containsKey("required")) {
					Boolean required = (Boolean)unassignedEntry.getValue().get("required");
					System.out.println(" **** before " + unassignedEntry.getKey() + ", required " + required  + " = " + missed.get(unassignedEntry.getKey()));
					missed.compute(unassignedEntry.getKey(),
												 (k, v) -> v == null ? (required.booleanValue() ? (byte)1 
																																				: (byte)0)
																						 : (required.booleanValue() ? (byte)(v.byteValue() | 0x01)
																																				: (byte)(v.byteValue() & 0x02)));


					System.out.println(" **** after " + unassignedEntry.getKey() + ", required " + required  + " = " + missed.get(unassignedEntry.getKey()));
				}
				if (unassignedEntry.getValue().containsKey("default")) {
					System.out.println(" **** before " + unassignedEntry.getKey() + ", default = " + missed.get(unassignedEntry.getKey()));
					missed.compute(unassignedEntry.getKey(),
												 (k, v) -> v == null ? (byte)2
																						 : (byte)(v.byteValue() | 0x02));
					System.out.println(" **** after " + unassignedEntry.getKey() + ", default = " + missed.get(unassignedEntry.getKey()));
				}
			}
*/
      //remove from properties all those that appear in this type: unfortunately this returns an unmodifiable map ..
      defs = Maps.newHashMap(diff.entriesOnlyOnLeft());
    }

    if (!defs.isEmpty()) {
			theContext.addError(Message.INVALID_FACET_REFERENCE, theConstruct, theFacet, theSpecType, defs);
      res = false;
    }

		if (!missed.isEmpty()) {
			List missedNames = 
				missed.entrySet()
							.stream()
							.filter(e -> e.getValue().byteValue() == (byte)1)
							.map(e -> e.getKey())
							.collect(Collectors.toList());
			if (!missedNames.isEmpty()) {
      	theContext.addError(theConstruct + " " + theFacet + " missing required values for: " + missedNames, null);
       	res = false;
			}
		}

    return res;
  }

	/* Augmentation occurs in cases such as the declaration of capabilities within a node type.
   * In such cases the construct facets (the capabilitity's properties) can redefine (augment) the 
   * specification found in the construct type. 
   */
  protected boolean checkFacetAugmentation(Construct theConstruct,
															 						 Map theSpec,
															 						 Facet theFacet,
															 						 CheckContext theContext) {
		return checkFacetAugmentation(theConstruct, theSpec, null, theFacet, theContext);
	}

	protected boolean checkFacetAugmentation(Construct theConstruct,
															 						 Map theSpec,
																					 String theSpecType,
																					 Facet theFacet,
																					 CheckContext theContext) {
    
		Map<String,Map> augs = (Map<String,Map>)theSpec.get(theFacet.name());
    if (null == augs) {
      return true;
    }
    
    boolean res = true;
		if (theSpecType == null) {
			theSpecType = (String)theSpec.get("type");
    }
		if (theSpecType == null) {
       theContext.addError("No specification type available", null);
			return false;
		}

		for (Iterator<Map.Entry<String,Map>> ai = augs.entrySet().iterator(); ai.hasNext(); ) {
			Map.Entry<String,Map> ae = ai.next();
			
			//make sure it was declared by the type
			Map facetDef = catalog.getFacetDefinition(theConstruct, theSpecType, theFacet, ae.getKey());
			if (facetDef == null) {
       	theContext.addError("Unknown " + theConstruct + " " + theFacet + " (not declared by the type " + theSpecType + ") were used: " + ae.getKey(), null);
				res = false;
				continue;
			}

			//check the compatibility of the augmentation: only the type cannot be changed
			//can the type be changed in a compatible manner ??
			if (!facetDef.get("type").equals(ae.getValue().get("type"))) {
       	theContext.addError(theConstruct + " " + theFacet + " " + ae.getKey() + " has a different type than its definition: " + ae.getValue().get("type") + " instead of " + facetDef.get("type"), null);
				res = false;
				continue;
			}

			//check any valuation (here just defaults)
			Object defaultValue = ae.getValue().get("default");
			if (defaultValue != null) {
				checkDataValuation(defaultValue, ae.getValue(), theContext);
			}
		}

		return res;
	}
  
  protected boolean catalogTypes(Construct theConstruct, Map<String,Map> theTypes, CheckContext theContext) {

		boolean res = true;
		for (Map.Entry<String,Map> typeEntry: theTypes.entrySet()) {
			res &= catalogType(theConstruct, typeEntry.getKey(), typeEntry.getValue(), theContext); 
		}

		return res;
	}

  /* */
	protected boolean catalogType(Construct theConstruct,
															  String theName,
															  Map theDef,
															  CheckContext theContext) {
			  
		if (!catalog.addType(theConstruct, theName, theDef)) {
			theContext.addError(theConstruct + " type " + theName + " re-declaration", null);
			return false;
		}
		log.finer(theConstruct + " type " + theName + " has been cataloged");

		return true;
	}


  /* */
  protected boolean checkTypeReference(Construct theConstruct,
																			 CheckContext theContext,
																			 String... theTypeNames) {
		boolean res = true;
		for (String typeName: theTypeNames) {
			if (!isTypeReference(theConstruct, typeName)) {
				theContext.addError(Message.INVALID_TYPE_REFERENCE, "", typeName, theConstruct);
				res = false;
			}
		}
		return res;
	}

  protected boolean isTypeReference(Construct theConstruct,
																		String theTypeName) {
		return this.catalog.hasType(theConstruct, theTypeName);
  }
  
	/* node or relationship templates */
	protected boolean checkTemplateReference(Construct theConstruct,
																			     CheckContext theContext,
																			     String... theTemplateNames) {
		boolean res = true;
		for (String templateName: theTemplateNames) {
			if (!isTemplateReference(theConstruct, theContext, templateName)) {
				theContext.addError(Message.INVALID_TEMPLATE_REFERENCE, "", templateName, theConstruct);
				res = false;
			}
		}
		return res;
  }
  
	protected boolean catalogTemplates(Construct theConstruct,
																		 Map<String,Map> theTemplates,
																		 CheckContext theContext) {

		boolean res = true;
		for (Map.Entry<String,Map> typeEntry: theTemplates.entrySet()) {
			res &= catalogTemplate(theConstruct, typeEntry.getKey(), typeEntry.getValue(), theContext); 
		}

		return res;
	}

	protected boolean catalogTemplate(Construct theConstruct,
															  		String theName,
															  		Map theDef,
															  		CheckContext theContext) {
		try {
	  	catalog.addTemplate(theContext.target(), theConstruct, theName, theDef);
			log.finer(theConstruct + " " + theName + " has been cataloged");
		}
		catch(CatalogException cx) {
		  theContext.addError("Failed to catalog " + theConstruct + " " + theName, cx);
			return false;
		}
		return true;
	}

	protected boolean isTemplateReference(Construct theConstruct,
																				CheckContext theContext,
																				String theTemplateName) {
		return this.catalog.hasTemplate(theContext.target(),theConstruct, theTemplateName);
	}

	/*
	 * For inputs/properties/attributes/(parameters). It is the caller's
	 * responsability to provide the value (from a 'default', inlined, ..)
	 *
	 * @param theDef the definition of the given construct/facet as it appears in
	 * 			its enclosing type definition.
	 * @param 
	 */
	protected boolean checkDataValuation(Object theExpr,
																			 Map<String,?> theDef,
																			 CheckContext theContext) {
		//first check if the expression is a function, if not handle it as a value assignment
		Data.Function f = Data.function(theExpr);
		if (f != null) {
			return f.evaluator()
							 .eval(theExpr, theDef, theContext);
		}
		else {
			Data.Type type = Data.typeByName((String)theDef.get("type"));
			if (type != null) {
//System.out.println("Evaluating " + theExpr + " as " + theExpr.getClass().getName() + " against " + theDef);
				Data.Evaluator evaluator = null;

				evaluator = type.evaluator();
				if (evaluator == null) {
					log.info("No value evaluator available for type " + type);
				}
				else {
					if (theExpr != null) {
						if (!evaluator.eval(theExpr, theDef, theContext)) {
							return false;
						}
					}
				}
				
				evaluator = type.constraintsEvaluator();
				if (evaluator == null) {
					log.info("No constraints evaluator available for type " + type);
				}
				else { 
					if (theExpr != null) {
						if (!evaluator.eval(theExpr, theDef, theContext)) {
							return false;
						}
					}
					else {
						//should have a null value validator
					}
				}
	
				return true;
			}
			else {
				theContext.addError("Expression " + theExpr + " of " + theDef + " could not be evaluated", null);
				return false;
			}
		}
	}

	/** Given the type of a certain construct (node type for example), look up
	 * in one of its facets (properties, capabilities, ..) for one of the given
	 * facet type (if looking in property, one of the given data type).
	 * @return a map of all facets of the given type, will be empty to signal
	 * none found
	 *
	 * Should we look for a facet construct of a compatible type: any type derived
	 * from the given facet's construct type??
	 */
	protected Map<String,Map> 
									findTypeFacetByType(Construct theTypeConstruct,
																	    String theTypeName,
																			Facet theFacet,
																			String theFacetType) {
		
		log.logp(Level.FINER, "", "findTypeFacetByType", theTypeName + " " +  theTypeConstruct + ": " + theFacetType + " " + theFacet);
		Map<String,Map> res= new HashMap<String,Map>();
    Iterator<Map.Entry<String,Map>> i =
															catalog.hierarchy(theTypeConstruct, theTypeName);
		while (i.hasNext()) {
			Map.Entry<String,Map> typeSpec = i.next();
			log.logp(Level.FINER, "", "findTypeFacetByType", "Checking " + theTypeConstruct + " type " + typeSpec.getKey() );
			Map<String,Map> typeFacet =
									(Map<String,Map>)typeSpec.getValue().get(theFacet.name());
			if (typeFacet == null) {
				continue;
			}
    	Iterator<Map.Entry<String,Map>> fi = typeFacet.entrySet().iterator();
			while(fi.hasNext()) {
				Map.Entry<String,Map> facet = fi.next();
				String facetType = (String)facet.getValue().get("type");
				log.logp(Level.FINER, "", "findTypeFacetByType", "Checking " + facet.getKey() + " type " + facetType);

				//here is the question: do we look for an exact match or ..
				//now we check that the type has a capability of a type compatible
				//(equal or derived from) the given capability type.
				if (catalog.isDerivedFrom(
							theFacet.construct(), /*theFacetType, facetType*/facetType, theFacetType)) {
					//res.merge(facet.getKey(), facet.getValue(), (currDef, newDef)->(merge the base class definition in the existing definition but provide the result in a new map as to avoid changing the stored defintitions));
					res.putIfAbsent(facet.getKey(), facet.getValue());
				}
			}
		}
		log.logp(Level.FINER, "", "findTypeFacetByType", "found " + res);

    return res;
  }
	
	/* */
	protected Map<String,Object>
									findTypeFacetByName(Construct theTypeConstruct,
																	    String theTypeName,
																			Facet theFacet,
																			String theFacetName) {
		log.logp(Level.FINER, "", "findTypeFacetByName", theTypeConstruct + " " + theTypeName);
    Iterator<Map.Entry<String,Map>> i =
															catalog.hierarchy(theTypeConstruct, theTypeName);
		while (i.hasNext()) {
			Map.Entry<String,Map> typeSpec = i.next();
			log.logp(Level.FINER, "", "findTypeFacetByName", "Checking " + theTypeConstruct + " type " + typeSpec.getKey() );
			Map<String,Map> typeFacet =
											(Map<String,Map>)typeSpec.getValue().get(theFacet.name());
			if (typeFacet == null) {
				continue;
			}
			Map<String,Object> facet = typeFacet.get(theFacetName);
			if (facet != null) {
				return facet;
			}
		}
		return null;
	}

	/* Requirements are the odd ball as they are structured as a sequence ..
	 */	
	protected Map<String,Map> findNodeTypeRequirementByName(
																String theNodeType, String theRequirementName) {
		log.logp(Level.FINER, "", "findNodeTypeRequirementByName", theNodeType + "/" + theRequirementName);
    Iterator<Map.Entry<String,Map>> i =
															catalog.hierarchy(Construct.Node, theNodeType);
		while (i.hasNext()) {
			Map.Entry<String,Map> nodeType = i.next();
			log.logp(Level.FINER, "", "findNodeTypeRequirementByName", "Checking node type " + nodeType.getKey() );
			List<Map<String,Map>> nodeTypeRequirements =
							(List<Map<String,Map>>)nodeType.getValue().get("requirements");
			if (nodeTypeRequirements == null) {
				continue;
			}

			for (Map<String,Map> requirement: nodeTypeRequirements) {
				Map requirementDef = requirement.get(theRequirementName);
				if (requirementDef != null) {
					return requirementDef;
				}
			}
		}
		return null;
	}

	/*
	 * 
	 */
	public Map findNodeTemplateInterfaceOperation(
								Target theTarget, String theNodeName, String theInterfaceName, String theOperationName) {

		Map nodeDefinition = (Map)catalog.getTemplate(theTarget, Construct.Node, theNodeName);
		if (nodeDefinition == null)
			return null;

		Map interfaces = (Map)nodeDefinition.get("interfaces");
		if (interfaces == null)
			return null;

		Map interfaceDef = (Map)interfaces.get(theInterfaceName);
		if (interfaceDef == null)
			return null;

		return (Map)interfaceDef.get(theOperationName);
	}

	public Map findNodeTypeInterfaceOperation(
								String theNodeType, String theInterfaceName, String theOperationName) {
	
		return null;	
	}
	
  /*
	 * Assumes that at this time the constrints (syntax) for all names (construct
	 * types, constructs, facets: ) are the same.
	 */
	public boolean checkName(String theName,
												      CheckContext theContext) {
		return true;
	}
	
	/*
	 * Additional generics checks to be performed on any definition: construct,
	 * construct types, etc ..
	 */
	public boolean checkDefinition(String theName,
															Map theDefinition, 
												      CheckContext theContext) {
	  if (theDefinition == null) {
		  theContext.addError("Missing definition for " + theName, null);
				return false;
		}
	  
		if (theDefinition.isEmpty()) {
		  theContext.addError("Empty definition for " + theName, null);
				return false;
		}

		return true;
	}

	public boolean checkDefinition(String theName,
															List theDefinition, 
												      CheckContext theContext) {
	  if (theDefinition == null) {
		  theContext.addError("Missing definition for " + theName, null);
				return false;
		}
	  
		if (theDefinition.isEmpty()) {
		  theContext.addError("Empty definition for " + theName, null);
				return false;
		}

		return true;
	}

	/* I'd rather validate each import once at it's own rule time (see next method) but unfortunately the canonicals
	 * are not visible 'right away' (they are applied at the end of the pre-validation but not visible in the
	 * post-validation of the same rule because of kwalify validator implementation).
	 */
	@Validates(rule="service_template_definition",timing=Validates.Timing.post)
  protected void validate_imports(
			Object theValue, Rule theRule, Validator.ValidationContext theContext) {

		Map template = (Map)theValue;
		List<Map> imports = (List)template.get("imports");

		if (imports != null) {
			for (Map importEntry: imports) {
				validate_import(mapEntry(importEntry).getValue(), theRule, theContext);
			}
		}
	}

	//@Validates(rule="import_definition",timing=Validates.Timing.post)
  protected void validate_import(
			Object theValue, Rule theRule, Validator.ValidationContext theContext) {

	  log.entering("", "import", theContext.getPath());
					
		TOSCAValidator validator = (TOSCAValidator)theContext.getValidator();
		Target tgt = validator.getTarget();

		Map def = (Map)theValue; //importEntry.getValue(); 
		log.fine("Processing import " + def);

		String tfile = (String)def.get("file");
		Target tgti = this.locator.resolve(tfile);
		if (tgti == null) {
     	theContext.addError("Failure to resolve import '" + def + "', imported from " + tgt, theRule, null, null);
     	return; 
		}
		log.finer("Import " + def + " located at " + tgti.getLocation());
		
		if (this.catalog.addTarget(tgti, tgt)) {
	
			//we've never seen this import (location) before
			try {
				List<Target> tgtis = parseTarget(tgti);
				if (tgtis.isEmpty())
					return; //continue;

				if (tgtis.size() > 1) {
       		theContext.addError("Import '" + tgti + "', imported from " + tgt + ", contains multiple yaml documents" , theRule, null, null);
       		return; //continue;
				}

				tgti = tgtis.get(0);
				if (tgt.getReport().hasErrors()) {
       		theContext.addError("Failure parsing import '" + tgti + "',imported from " + tgt, theRule, null, null);
					return; //continue;
				}
        	
				validateTarget(tgti);
				if (tgt.getReport().hasErrors()) {
        	theContext.addError("Failure validating import '" + tgti + "',imported from " + tgt, theRule, null, null);
					return; //continue;
				}
      }
      catch (CheckerException cx) {
       	theContext.addError("Failure validating import '" + tgti + "',imported from " + tgt, theRule, cx, null);
      }
		}

		//replace with the actual location (also because this is what they get
		//index by .. bad, this exposed catalog inner workings)
		def.put("file", tgti.getLocation());
	}
	
	/* plenty of one entry maps around */
	private Map.Entry mapEntry(Object theMap) {
		return (Map.Entry)((Map)theMap).entrySet().iterator().next();
	}
 

	/* */
	protected static Catalog commonsCatalog = null;

	/*
	 * commons are built-in and supposed to be bulletproof so any error in here 
	 * goes out loud.
	 */
	protected static Catalog commonsCatalog() {
		
		synchronized (Catalog.class) {
			
			if (commonsCatalog != null) {
				return commonsCatalog;
			}

			//if other templates are going to be part of the common type system
			//add them to this list. order is relevant.
			final String[] commons = new String[] {
																	"tosca/tosca-common-types.yaml" };
		
			Checker commonsChecker = null;
			try {
				commonsChecker = new Checker();

				for (String common: commons) {
					commonsChecker.check(common, buildCatalog(false));
					Report commonsReport = commonsChecker.targets().iterator().next().getReport();

					if (commonsReport.hasErrors()) {
						throw new RuntimeException("Failed to process commons:\n" + 
																				commonsReport);
					}
				}
			}
			catch(CheckerException cx) {
				throw new RuntimeException("Failed to process commons", cx);
			}

			return commonsCatalog = commonsChecker.catalog;
		}
	}
  
	public static Catalog buildCatalog() {
		return buildCatalog(true);
	}

  /*
	 */
  public static Catalog buildCatalog(boolean doCommons) {

   	Catalog catalog = new Catalog(doCommons ? commonsCatalog() : null);
		if (!doCommons) {
    	//add core TOSCA types
			for (Data.CoreType type: Data.CoreType.class.getEnumConstants()) {
     		catalog.addType(Construct.Data, type.toString(), Collections.emptyMap());
			}
		}
		return catalog;
	}

	protected void checks(String theName,
 	                      Object theTarget,
											  CheckContext theContext) {

		handles("checks:" + theContext.getPath(theName), theTarget, theContext);
  }
	
	protected void catalogs(String theName,
 	                      	Object theTarget,
											  	CheckContext theContext) {

		handles("catalogs:" + theContext.getPath(theName), theTarget, theContext);
	}
	
	protected boolean validates(Validates.Timing theTiming,
	                 		        Object theTarget,
															Rule theRule,
															Validator.ValidationContext theContext) {
		//might look odd but we need both 'handles' call to be executed
		boolean validated = 
			handles(theTiming + "-validates:" + theRule.getName(), theTarget, theRule, theContext);
		return handles(theTiming + "-validates:", theTarget, theRule, theContext) || validated;
	}

	/*
	 * allow the handlers to return a boolean .. only do this in order to accomodate the Canonical's way of avoiding
	 * validation when a short form is encoutered.
	 * @return true if any handler returned true (if they returned something at all), false otherwise (even when no
   * handlers were found)
	 */
	protected boolean handles(String theHandlerKey,	Object... theArgs) {

		boolean handled = false;
		Map<Method, Object> entries = handlers.row(theHandlerKey);
		if (entries != null) {
			for (Map.Entry<Method, Object> entry: entries.entrySet()) {
				Object res = null;
				try {
					res = entry.getKey().invoke(entry.getValue(), theArgs);
				}
				catch (Exception x) {
       		log.log(Level.WARNING, theHandlerKey + " by " + entry.getKey() + " failed", x);
				}
				handled |= res == null ? false : (res instanceof Boolean && ((Boolean)res).booleanValue());
			}	
		}
		return handled;
	}

  /**
	 */
  public class TOSCAValidator extends Validator {

		//what were validating
   	private Target	target;
			
    public TOSCAValidator(Target theTarget, Object theSchema)
																										throws SchemaException {
      super(theSchema);
			this.target = theTarget;
    }

		public Target getTarget() {
			return this.target;
		}

    /* hook method called by Validator#validate() 
     */
    protected boolean preValidationHook(Object value, Rule rule, ValidationContext context) {

			return validates(Validates.Timing.pre, value, rule, context);
    }

    /*
     * Only gets invoked once the value was succesfully verified against the syntax indicated by the given rule.
     */
    protected void postValidationHook(Object value,
		                                  Rule rule,
																			ValidationContext context) {
      validates(Validates.Timing.post, value, rule, context);
    }

  }

  /** 
	 * Maintains state across the checking process.
	 */
  public class CheckContext {

		public class Step {

		  private final Construct construct;
 			private final String		name;
			private final Object		info;

  		public Step(String theName, Construct theConstruct, Object theInfo) {
    		this.construct = theConstruct;
    		this.name = theName;
    		this.info = theInfo;
  		}

  		public Construct 	construct() { return this.construct; }
  		public String 		name() { return this.name; }
  		public Object 		info() { return this.info; }
		}		


		private Target							target;
	  private ArrayList<Step>			steps = new ArrayList<Step>(20); //artificial max nesting ..


		public CheckContext(Target theTarget) {
			this.target = theTarget;
		}

    public CheckContext enter(String theName) {
    	return enter(theName, null, null);
		}

		public CheckContext enter(String theName, Construct theConstruct) {
			return enter(theName, theConstruct, null);
		}

		public CheckContext enter(String theName, Construct theConstruct, Object theInfo) {
			this.steps.add(new Step(theName, theConstruct, theInfo));
      Checker.this.log.entering("check", theName, getPath());
			return this;
		}
    
		public CheckContext exit() {
	 		Step step = this.steps.get(this.steps.size()-1);
      Checker.this.log.exiting("check", step.name(), getPath());
	 		this.steps.remove(this.steps.size()-1);
		  return this;
		}

		public String getPath() {
			return buildPath(null);
		}

		public String getPath(String theNextElem) {
			return buildPath(theNextElem);
		}

		protected String buildPath(String theElem) {
			StringBuffer sb = new StringBuffer("");
			for (Step s: this.steps)
				sb.append(s.name())
					.append("/");
			if (theElem != null)
				sb.append(theElem)
					.append("/");
			
			return sb.substring(0,sb.length()-1);
		}

    public Step enclosingConstruct(Construct theConstruct) {
			for (int i = this.steps.size()-1; i > 0; i--) {
			  Construct c = this.steps.get(i).construct();
				if (c != null && c.equals(theConstruct)) {
					return this.steps.get(i);
				}
			}
			return null;
		}
    
		public Step enclosingElement(String theName) {
			for (int i = this.steps.size()-1; i > 0; i--) {
			  String n = this.steps.get(i).name();
				if (n != null && n.equals(theName)) {
					return this.steps.get(i);
				}
			}
			return null;
		}

		public Step enclosing() {
			if (this.steps.size() > 0) {
				return this.steps.get(this.steps.size()-1);
			}
			return null;
		}

		public CheckContext addError(String theMessage, Throwable theCause) {
      this.target.report(new TargetError("", getPath(), theMessage, theCause));
			return this;
		}
		
		public CheckContext addError(Message theMsg, Object... theArgs) {
			this.target.report(new TargetError("", getPath(), messages.format(theMsg, theArgs), null));
			return this;
		}

    public boolean hasErrors() {
			return this.target.getReport().hasErrors();
		}

		public Checker checker() {
			return Checker.this;
		}

		public Catalog catalog() {
			return Checker.this.catalog;
		}

		public Target target() {
			return this.target;
		}

		public String toString() {
			return "CheckContext(" + this.target.getLocation() + "," + getPath() + ")";
		}
	}

	public static class CheckerConfiguration {

		private boolean 			allowAugmentation = true;
		private String				defaultImportsPath = null;
		private List<String>	grammars = new LinkedList<String>();

		public CheckerConfiguration() {
			withGrammars(Checker.grammarFiles);
		}

		public CheckerConfiguration allowAugmentation(boolean doAllow) {
			this.allowAugmentation = doAllow;
			return this;
		}

		public boolean allowAugmentation() {
			return this.allowAugmentation;
		}

		public CheckerConfiguration withDefaultImportsPath(String thePath) {
			this.defaultImportsPath = thePath;
			return this;
		}

		public String defaultImportsPath() {
			return this.defaultImportsPath;
		}

		public CheckerConfiguration withGrammars(String... theGrammars) {
			for (String grammar: theGrammars) {
				this.grammars.add(grammar);
			}
			return this;
		}

		public String[] grammars() {
			return this.grammars.toArray(new String[0]);
		}
	}

}