File: VirtuosoRepositoryConnection.java

package info (click to toggle)
virtuoso-opensource 7.2.5.1%2Bdfsg1-0.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 285,240 kB
  • sloc: ansic: 641,220; sql: 490,413; xml: 269,570; java: 83,893; javascript: 79,900; cpp: 36,927; sh: 31,653; cs: 25,702; php: 12,690; yacc: 10,227; lex: 7,601; makefile: 7,129; jsp: 4,523; awk: 1,697; perl: 1,013; ruby: 1,003; python: 326
file content (3550 lines) | stat: -rw-r--r-- 133,711 bytes parent folder | download | duplicates (2)
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
/*
 *  $Id$
 *
 *  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
 *  project.
 *
 *  Copyright (C) 1998-2018 OpenLink Software
 *
 *  This project is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; only version 2 of the License, dated June 1991.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */
package virtuoso.rdf4j.driver;

import org.eclipse.rdf4j.common.iteration.CloseableIteration;
import org.eclipse.rdf4j.common.iteration.CloseableIteratorIteration;
import org.eclipse.rdf4j.common.iteration.Iteration;
import org.eclipse.rdf4j.common.iteration.Iterations;
import org.eclipse.rdf4j.IsolationLevel;
import org.eclipse.rdf4j.IsolationLevels;
import org.eclipse.rdf4j.OpenRDFUtil;
import org.eclipse.rdf4j.model.*;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.impl.SimpleNamespace;
import org.eclipse.rdf4j.model.vocabulary.XMLSchema;
import org.eclipse.rdf4j.query.*;
import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet;
import org.eclipse.rdf4j.query.impl.IteratingGraphQueryResult;
import org.eclipse.rdf4j.query.impl.IteratingTupleQueryResult;
import org.eclipse.rdf4j.repository.*;
import org.eclipse.rdf4j.rio.*;

import java.io.*;
import java.net.URL;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler;
import org.eclipse.rdf4j.rio.helpers.ParseErrorLogger;
import virtuoso.jdbc4.VirtuosoResultSet;
import virtuoso.sql.ExtendedString;
import virtuoso.sql.RdfBox;
import virtuoso.jdbc4.VirtuosoDate;
import virtuoso.jdbc4.VirtuosoTime;
import virtuoso.jdbc4.VirtuosoTimestamp;

/**
 * Main interface for updating data in and performing queries on a Sesame
 * repository. By default, a RepositoryConnection is in autoCommit mode, meaning
 * that each operation corresponds to a single transaction on the underlying
 * store. autoCommit can be switched off in which case it is up to the user to
 * handle transaction commit/rollback. Note that care should be taking to always
 * properly close a RepositoryConnection after one is finished with it, to free
 * up resources and avoid unnecessary locks.
 * <p>
 * Several methods take a vararg argument that optionally specifies a (set of)
 * context(s) on which the method should operate. Note that a vararg parameter
 * is optional, it can be completely left out of the method call, in which case
 * a method either operates on a provided statements context (if one of the
 * method parameters is a statement or collection of statements), or operates on
 * the repository as a whole, completely ignoring context. A vararg argument may
 * also be 'null' (cast to Resource) meaning that the method operates on those
 * statements which have no associated context only.
 * <p>
 * Examples:
 *
 * <pre>
 * // Ex 1: this method retrieves all statements that appear in either context1 or context2, or both.
 * RepositoryConnection.getStatements(null, null, null, true, context1, context2);
 *
 * // Ex 2: this method retrieves all statements that appear in the repository (regardless of context).
 * RepositoryConnection.getStatements(null, null, null, true);
 *
 * // Ex 3: this method retrieves all statements that have no associated context in the repository.
 * // Observe that this is not equivalent to the previous method call.
 * RepositoryConnection.getStatements(null, null, null, true, (Resource)null);
 *
 * // Ex 4: this method adds a statement to the store. If the statement object itself has
 * // a context (i.e. statement.getContext() != null) the statement is added to that context. Otherwise,
 * // it is added without any associated context.
 * RepositoryConnection.add(statement);
 *
 * // Ex 5: this method adds a statement to context1 in the store. It completely ignores any
 * // context the statement itself has.
 * RepositoryConnection.add(statement, context1);
 * </pre>
 *
 */
public class VirtuosoRepositoryConnection implements RepositoryConnection {

    private Resource nilContext;
    private Connection quadStoreConnection;
    protected VirtuosoRepository repository;
    static final String S_DELETE = "sparql delete from graph iri(??) {`iri(??)` `iri(??)` `bif:__rdf_long_from_batch_params(??,??,??)`}";
    static final String S_BATCH_INSERT = "DB.DBA.rdf_insert_triple_c (?,?,?,?,?,?)";
    static final String S_CLEAR_GRAPH = "DB.DBA.rdf_clear_graphs_c (?)";

    static final String S_TTLP_INSERT = "DB.DBA.TTLP_MT (?, '', ?, 255, 2, 3, ?)";

    static final int MAX_CMD_SIZE = 36000;

    private int BATCH_SIZE = 5000;
    private PreparedStatement psInsert;
    private PreparedStatement psInsert_BNode;
    private int psInsertCount = 0;
    private int psInsertBNodeCount = 0;

    private boolean useLazyAdd = false;
    private int prefetchSize = 100;
    private boolean useReprepare = true;
    private boolean insertBNodeAsVirtuosoIRI = false;
    private ValueFactory valueFactory = null;
    private boolean insertStringLiteralAsSimple = false;
    private int queryTimeout = 0;
    private String ruleSet;    
    private String macroLib;
    private String defGraph;
    private boolean useDefGraphForQueries;

    private volatile ParserConfig parserConfig = new ParserConfig();
    private IsolationLevel isolationLevel;
    private int concurencyMode;
    private int trn_concurrencyMode;

    public VirtuosoRepositoryConnection(VirtuosoRepository repository, Connection connection) throws RepositoryException {
        this.quadStoreConnection = connection;
        this.repository = repository;
        this.useLazyAdd = repository.useLazyAdd;
        this.prefetchSize = repository.prefetchSize;
        this.BATCH_SIZE = repository.batchSize;
        this.insertBNodeAsVirtuosoIRI = repository.insertBNodeAsVirtuosoIRI;
        this.insertStringLiteralAsSimple = repository.insertStringLiteralAsSimple;
        this.valueFactory = repository.getValueFactory();
        this.queryTimeout = repository.getQueryTimeout();
        this.ruleSet = repository.getRuleSet();
        this.macroLib = repository.getMacroLib();
        this.defGraph = repository.defGraph;
	this.useDefGraphForQueries = repository.useDefGraphForQueries;
        this.trn_concurrencyMode = this.concurencyMode = repository.concurencyMode;
        this.nilContext = valueFactory.createIRI(repository.defGraph);
        this.repository.initialize();

        try {
            virtuoso.jdbc4.Driver drv = new virtuoso.jdbc4.Driver();
            if (drv.getMajorVersion()>=3 && drv.getMinorVersion()>=72)
                useReprepare = false;
        } catch(Exception e) {}
    }



    /**
     * Returns the Repository object to which this connection belongs.
     */
    public Repository getRepository() {
        return repository;
    }


    /**
     * Set the parser configuration this connection should use for
     * RDFParser-based operations.
     *
     * @param parserConfig
     *        a Rio RDF Parser configuration.
     */
    public void setParserConfig(ParserConfig parserConfig) {
        this.parserConfig = parserConfig;
    }

    /**
     * Returns the parser configuration this connection uses for Rio-based
     * operations.
     *
     * @return a Rio RDF parser configuration.
     */
    public ParserConfig getParserConfig() {
        return parserConfig;
    }

    /**
     * Gets a ValueFactory for this RepositoryConnection.
     *
     * @return A repository-specific ValueFactory.
     */
    public ValueFactory getValueFactory() {
        return valueFactory;
    }

    /**
     * Checks whether this connection is open. A connection is open from the moment it is created until it is closed.
     *
     * @see #close()
     */
    public boolean isOpen() throws RepositoryException {
        try {
            return !this.getQuadStoreConnection().isClosed();
        }
        catch (SQLException e) {
            throw new RepositoryException("Problem inspecting connection", e);
        }
    }

    /**
     * Closes the connection, freeing resources. If the connection is not in
     * autoCommit mode, all non-committed operations will be lost.
     *
     * @throws RepositoryException
     *         If the connection could not be closed.
     */
    public void close() throws RepositoryException {
        try {
            if (!getQuadStoreConnection().isClosed()) {
                getQuadStoreConnection().close();
            }
        }
        catch (SQLException e) {
            throw new RepositoryException(e);
        }
    }


    /**
     * Prepares a query for evaluation on this repository (optional operation).
     * In case the query contains relative URIs that need to be resolved against
     * an external base URI, one should use
     * {@link #prepareQuery(QueryLanguage, String, String)} instead.
     *
     * @param ql
     *        The query language in which the query is formulated.
     * @param query
     *        The query string.
     * @return A query ready to be evaluated on this repository.
     * @throws MalformedQueryException
     *         If the supplied query is malformed.
     * @throws UnsupportedQueryLanguageException
     *         If the supplied query language is not supported.
     * @throws UnsupportedOperationException
     *         If the <tt>prepareQuery</tt> method is not supported by this
     *         repository.
     */
    public Query prepareQuery(QueryLanguage ql, String query) throws RepositoryException, MalformedQueryException {
        return prepareQuery(ql, query, null);
    }

    /**
     * Prepares a query for evaluation on this repository (optional operation).
     *
     * @param ql
     *        The query language in which the query is formulated.
     * @param query
     *        The query string.
     * @param baseURI
     *        The base URI to resolve any relative URIs that are in the query
     *        against, can be <tt>null</tt> if the query does not contain any
     *        relative URIs.
     * @return A query ready to be evaluated on this repository.
     * @throws MalformedQueryException
     *         If the supplied query is malformed.
     * @throws UnsupportedQueryLanguageException
     *         If the supplied query language is not supported.
     * @throws UnsupportedOperationException
     *         If the <tt>prepareQuery</tt> method is not supported by this
     *         repository.
     */
    public Query prepareQuery(QueryLanguage ql, String query, String baseURI) throws RepositoryException, MalformedQueryException {
        if (ql != QueryLanguage.SPARQL)
            throw new UnsupportedQueryLanguageException(" : Only SPARQL queries are supported");

        StringTokenizer st = new StringTokenizer(query);
        String type = null;

        while(st.hasMoreTokens()) {
            type = st.nextToken().toLowerCase();
            if (type.equals("select"))
                break;
            else if(type.equals("construct") || type.equals("describe"))
                break;
            else if(type.equals("ask"))
                break;
        }

        flushDelayAdd();
        if(type==null || type.equals("select"))
            return prepareTupleQuery(ql, query, baseURI);
        else if(type.equals("construct") || type.equals("describe"))
            return prepareGraphQuery(ql, query, baseURI);
        else if(type.equals("ask"))
            return prepareBooleanQuery(ql, query, baseURI);
        else
            return new VirtuosoQuery();
    }

    /**
     * Prepares a query that produces sets of value tuples. In case the query
     * contains relative URIs that need to be resolved against an external base
     * URI, one should use
     * {@link #prepareTupleQuery(QueryLanguage, String, String)} instead.
     *
     * @param ql
     *        The query language in which the query is formulated.
     * @param query
     *        The query string.
     * @throws IllegalArgumentException
     *         If the supplied query is not a tuple query.
     * @throws MalformedQueryException
     *         If the supplied query is malformed.
     * @throws UnsupportedQueryLanguageException
     *         If the supplied query language is not supported.
     */
    public TupleQuery prepareTupleQuery(QueryLanguage ql, String query) throws RepositoryException, MalformedQueryException {
        return prepareTupleQuery(ql, query, null);
    }

    /**
     * Prepares a query that produces sets of value tuples.
     *
     * @param ql
     *        The query language in which the query is formulated.
     * @param query
     *        The query string.
     * @param baseURI
     *        The base URI to resolve any relative URIs that are in the query
     *        against, can be <tt>null</tt> if the query does not contain any
     *        relative URIs.
     * @throws IllegalArgumentException
     *         If the supplied query is not a tuple query.
     * @throws MalformedQueryException
     *         If the supplied query is malformed.
     * @throws UnsupportedQueryLanguageException
     *         If the supplied query language is not supported.
     */
    public TupleQuery prepareTupleQuery(QueryLanguage ql, final String query, final String baseURI) throws RepositoryException, MalformedQueryException {
        if (ql != QueryLanguage.SPARQL)
            throw new UnsupportedQueryLanguageException(" : Only SPARQL queries are supported");

        return new VirtuosoTupleQuery() {
            public TupleQueryResult evaluate() throws QueryEvaluationException {
                return executeSPARQLForTupleResult(baseURI, query, getDataset(), getIncludeInferred(), getBindings(), getMaxExecutionTime());
            }

            public void evaluate(TupleQueryResultHandler handler) throws QueryEvaluationException, TupleQueryResultHandlerException {
                executeSPARQLForHandler(baseURI, handler, query, getDataset(), getIncludeInferred(), getBindings(), getMaxExecutionTime());
            }
        };
    }

    /**
     * Prepares queries that produce RDF graphs. In case the query contains
     * relative URIs that need to be resolved against an external base URI, one
     * should use {@link #prepareGraphQuery(QueryLanguage, String, String)}
     * instead.
     *
     * @param ql
     *        The query language in which the query is formulated.
     * @param query
     *        The query string.
     * @throws IllegalArgumentException
     *         If the supplied query is not a graph query.
     * @throws MalformedQueryException
     *         If the supplied query is malformed.
     * @throws UnsupportedQueryLanguageException
     *         If the supplied query language is not supported.
     */
    public GraphQuery prepareGraphQuery(QueryLanguage ql, String query) throws RepositoryException, MalformedQueryException {
        return prepareGraphQuery(ql, query, null);
    }

    /**
     * Prepares queries that produce RDF graphs.
     *
     * @param ql
     *        The query language in which the query is formulated.
     * @param query
     *        The query string.
     * @param baseURI
     *        The base URI to resolve any relative URIs that are in the query
     *        against, can be <tt>null</tt> if the query does not contain any
     *        relative URIs.
     * @throws IllegalArgumentException
     *         If the supplied query is not a graph query.
     * @throws MalformedQueryException
     *         If the supplied query is malformed.
     * @throws UnsupportedQueryLanguageException
     *         If the supplied query language is not supported.
     */
    public GraphQuery prepareGraphQuery(QueryLanguage ql, final String query, final String baseURI) throws RepositoryException, MalformedQueryException {
        if (ql != QueryLanguage.SPARQL)
            throw new UnsupportedQueryLanguageException(" : Only SPARQL queries are supported");

        return new VirtuosoGraphQuery() {
            public GraphQueryResult evaluate() throws QueryEvaluationException {
                return executeSPARQLForGraphResult(baseURI, query, getDataset(), getIncludeInferred(), getBindings(), getMaxExecutionTime());
            }

            public void evaluate(RDFHandler handler) throws QueryEvaluationException, RDFHandlerException {
                executeSPARQLForHandler(baseURI, handler, query, getDataset(), getIncludeInferred(), getBindings(), getMaxExecutionTime());
            }
        };
    }

    /**
     * Prepares <tt>true</tt>/<tt>false</tt> queries. In case the query
     * contains relative URIs that need to be resolved against an external base
     * URI, one should use
     * {@link #prepareBooleanQuery(QueryLanguage, String, String)} instead.
     *
     * @param ql
     *        The query language in which the query is formulated.
     * @param query
     *        The query string.
     * @throws IllegalArgumentException
     *         If the supplied query is not a boolean query.
     * @throws MalformedQueryException
     *         If the supplied query is malformed.
     * @throws UnsupportedQueryLanguageException
     *         If the supplied query language is not supported.
     */
    public BooleanQuery prepareBooleanQuery(QueryLanguage ql, String query) throws RepositoryException, MalformedQueryException {
        return prepareBooleanQuery(ql, query, null);
    }

    /**
     * Prepares <tt>true</tt>/<tt>false</tt> queries.
     *
     * @param ql
     *        The query language in which the query is formulated.
     * @param query
     *        The query string.
     * @param baseURI
     *        The base URI to resolve any relative URIs that are in the query
     *        against, can be <tt>null</tt> if the query does not contain any
     *        relative URIs.
     * @throws IllegalArgumentException
     *         If the supplied query is not a boolean query.
     * @throws MalformedQueryException
     *         If the supplied query is malformed.
     * @throws UnsupportedQueryLanguageException
     *         If the supplied query language is not supported.
     */
    public BooleanQuery prepareBooleanQuery(QueryLanguage ql, final String query, final String baseURI) throws RepositoryException, MalformedQueryException {
        if (ql != QueryLanguage.SPARQL)
            throw new UnsupportedQueryLanguageException(" : Only SPARQL queries are supported");

        return new VirtuosoBooleanQuery() {
            public boolean evaluate() throws QueryEvaluationException {
                return executeSPARQLForBooleanResult(baseURI, query, getDataset(), getIncludeInferred(), getBindings(), getMaxExecutionTime());
            }
        };
    }

    public Update prepareUpdate(QueryLanguage ql, String query) throws RepositoryException, MalformedQueryException {
        return prepareUpdate(ql, query, null);
    }

    public Update prepareUpdate(QueryLanguage ql, final String query, final String baseURI) throws RepositoryException, MalformedQueryException {
        if (ql != QueryLanguage.SPARQL)
            throw new UnsupportedQueryLanguageException(" : Only SPARQL queries are supported");

        return new VirtuosoUpdate() {
            public void execute() throws UpdateExecutionException {
                executeSPARUL(baseURI, query, getDataset(), getIncludeInferred(), getBindings(), -1);
            }
        };
    }

    /**
     * Gets all resources that are used as content identifiers. Care should be
     * taken that the returned {@link RepositoryResult} is closed to free any
     * resources that it keeps hold of.
     *
     * @return a RepositoryResult object containing Resources that are used as
     *         context identifiers.
     */
    public RepositoryResult<Resource> getContextIDs() throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        Vector<Resource> v = new Vector<Resource>();
        String query = "DB.DBA.SPARQL_SELECT_KNOWN_GRAPHS()";
        try {
            java.sql.Statement stmt = createStatement(-1, false);
            ResultSet rs = stmt.executeQuery(query);

            // begin at onset one
            while (rs.next()) {
                Object obj = rs.getObject(1);
                try {
                    Value graphId = castValue(obj);
                    // add that graph to the results
                    v.add((Resource)graphId);
                }
                catch (IllegalArgumentException iiaex) {
                    throw new RepositoryException("VirtuosoRepositoryConnection.getContextIDs() Non-URI context encountered: " + obj);
                }
            }
            rs.close();
            stmt.close();

        }
        catch (Exception e) {
            throw new RepositoryException(": SPARQL execute failed." + "\n" + query, e);
        }
        return createRepositoryResult(v);
    }

    /**
     * Gets all statements with a specific subject, predicate and/or object from
     * the repository. The result is optionally restricted to the specified set
     * of named contexts.
     *
     * @param subj
     *        A Resource specifying the subject, or <tt>null</tt> for a
     *        wildcard.
     * @param pred
     *        A URI specifying the predicate, or <tt>null</tt> for a wildcard.
     * @param obj
     *        A Value specifying the object, or <tt>null</tt> for a wildcard.
     * @param includeInferred
     *        if false, no inferred statements are returned; if true, inferred
     *        statements are returned if available. The default is true.
     * @param contexts
     *        The context(s) to get the data from. Note that this parameter is a
     *        vararg and as such is optional. If no contexts are supplied the
     *        method operates on the entire repository.
     * @return The statements matching the specified pattern. The result object
     *         is a {@link RepositoryResult} object, a lazy Iterator-like object
     *         containing {@link Statement}s and optionally throwing a
     *         {@link RepositoryException} when an error when a problem occurs
     *         during retrieval.
     */
    public RepositoryResult<Statement> getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws RepositoryException {
        contexts = checkContext(contexts);
        return new RepositoryResult<Statement>(selectFromQuadStore(subj, pred, obj, includeInferred, false, contexts));
    }

    /**
     * Checks whether the repository contains statements with a specific subject,
     * predicate and/or object, optionally in the specified contexts.
     *
     * @param subj
     *        A Resource specifying the subject, or <tt>null</tt> for a
     *        wildcard.
     * @param pred
     *        A URI specifying the predicate, or <tt>null</tt> for a wildcard.
     * @param obj
     *        A Value specifying the object, or <tt>null</tt> for a wildcard.
     * @param includeInferred
     *        if false, no inferred statements are considered; if true, inferred
     *        statements are considered if available
     * @param contexts
     *        The context(s) the need to be searched. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are supplied the
     *        method operates on the entire repository.
     * @return true If a matching statement is in the repository in the specified
     *         context, false otherwise.
     */
    public boolean hasStatement(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws RepositoryException {
        contexts = checkContext(contexts);
        CloseableIteration<Statement, RepositoryException> it;
        it = selectFromQuadStore(subj, pred, obj, includeInferred, true, contexts);
        try {
            return it.hasNext();
        } finally {
            it.close();
        }
    }

    /**
     * Checks whether the repository contains the specified statement, optionally
     * in the specified contexts.
     *
     * @param st
     *        The statement to look for. Context information in the statement is
     *        ignored.
     * @param includeInferred
     *        if false, no inferred statements are considered; if true, inferred
     *        statements are considered if available
     * @param contexts
     *        The context(s) to get the data from. Note that this parameter is a
     *        vararg and as such is optional. If no contexts are supplied the
     *        method operates on the entire repository.
     * @return true If the repository contains the specified statement, false
     *         otherwise.
     */
    public boolean hasStatement(Statement st, boolean includeInferred, Resource... contexts) throws RepositoryException {
        return hasStatement(st.getSubject(), st.getPredicate(), st.getObject(), includeInferred, contexts);
    }

    /**
     * Exports all statements with a specific subject, predicate and/or object
     * from the repository, optionally from the specified contexts.
     *
     * @param subj
     *        The subject, or null if the subject doesn't matter.
     * @param pred
     *        The predicate, or null if the predicate doesn't matter.
     * @param obj
     *        The object, or null if the object doesn't matter.
     * @param includeInferred
     *        if false, no inferred statements are returned; if true, inferred
     *        statements are returned if available
     * @param handler
     *        The handler that will handle the RDF data.
     * @param contexts
     *        The context(s) to get the data from. Note that this parameter is a
     *        vararg and as such is optional. If no contexts are supplied the
     *        method operates on the entire repository.
     * @throws RDFHandlerException
     *         If the handler encounters an unrecoverable error.
     */
    public void exportStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, RDFHandler handler, Resource... contexts) throws RepositoryException, RDFHandlerException {
        contexts = checkContext(contexts);
        CloseableIteration<Statement, RepositoryException> it;
        handler.startRDF();

        // Export namespace information
        RepositoryResult<Namespace> nsIt = getNamespaces();
        try {
            while (nsIt.hasNext()) {
                Namespace ns = nsIt.next();
                handler.handleNamespace(ns.getPrefix(), ns.getName());
            }
        }
        finally {
            nsIt.close();
        }

        it = selectFromQuadStore(subj, pred, obj, includeInferred, false, contexts);
        try {
            while (it.hasNext())
                handler.handleStatement(it.next());
        }
        finally {
            it.close();
        }
        handler.endRDF();
    }

    private Resource[] checkDMLContext(Resource... contexts) throws RepositoryException {
        OpenRDFUtil.verifyContextNotNull(contexts);
        if(contexts.length == 1 && contexts[0] == null) {
            contexts = new Resource[] {nilContext};
        }
        else if (contexts.length == 0) {
            contexts = new Resource[] {nilContext};
        }
        return contexts;
    }

    private Resource[] checkContext(Resource... contexts) throws RepositoryException {
        OpenRDFUtil.verifyContextNotNull(contexts);
        if(contexts.length == 1 && contexts[0] == null) {
            contexts = new Resource[] {nilContext};
        }
        else if (contexts.length == 0) {
            contexts = new Resource[0];
        }
        return contexts;
    }


    /**
     * Exports all explicit statements in the specified contexts to the supplied
     * RDFHandler.
     *
     * @param handler
     *        The handler that will handle the RDF data.
     * @param contexts
     *        The context(s) to get the data from. Note that this parameter is a
     *        vararg and as such is optional. If no contexts are supplied the
     *        method operates on the entire repository.
     * @throws RDFHandlerException
     *         If the handler encounters an unrecoverable error.
     */
    public void export(RDFHandler handler, Resource... contexts) throws RepositoryException, RDFHandlerException {
        exportStatements(null, null, null, false, handler, contexts);
    }

    /**
     * Returns the number of (explicit) statements that are in the specified
     * contexts in this repository.
     *
     * @param contexts
     *        The context(s) to get the data from. Note that this parameter is a
     *        vararg and as such is optional. If no contexts are supplied the
     *        method operates on the entire repository.
     * @return The number of explicit statements from the specified contexts in
     *         this repository.
     */
    public long size(Resource... contexts) throws RepositoryException {
        long ret = 0;
        verifyIsOpen();
        flushDelayAdd();

        contexts = checkContext(contexts);
        StringBuilder query = new StringBuilder("select count(*) from (sparql define input:storage \"\" select * ");

        for (Resource context : contexts) {
            query.append("from named <");
            query.append(context.toString());
            query.append("> ");
        }
        query.append("where { graph ?g {?s ?p ?o }})f");
        try {
            java.sql.Statement st = createStatement(-1, false);
            ResultSet rs = st.executeQuery(query.toString());

            if (rs.next())
                ret = rs.getLong(1);
            rs.close();
            st.close();
        }
        catch (Exception e) {
            throw new RepositoryException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }
        return ret;
    }

    /**
     * Returns <tt>true</tt> if this repository does not contain any (explicit)
     * statements.
     *
     * @return <tt>true</tt> if this repository is empty, <tt>false</tt>
     *         otherwise.
     * @throws RepositoryException
     *         If the repository could not be checked to be empty.
     */
    public boolean isEmpty() throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        boolean result;
        String query = "sparql define input:storage \"\" select * where {?s ?o ?p} limit 1";
        try {
            java.sql.Statement stmt = createStatement(-1, false);
            ResultSet rs = stmt.executeQuery(query);
            result = !rs.next();
            rs.close();
            stmt.close();
            return result;
        }
        catch (Exception e) {
            throw new RepositoryException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }
    }


    /**
     * Enables or disables auto-commit mode for the connection. If a connection
     * is in auto-commit mode, then all updates will be executed and committed as
     * individual transactions. Otherwise, the updates are grouped into
     * transactions that are terminated by a call to either {@link #commit} or
     * {@link #rollback}. By default, new connections are in auto-commit mode.
     * <p>
     * <b>NOTE:</b> If this connection is switched to auto-commit mode during a
     * transaction, the transaction is committed.
     *
     * @throws RepositoryException
     *         In case the mode switch failed, for example because a currently
     *         active transaction failed to commit.
     * @see #commit
     * @deprecated since 2.7.0. Use {@link #begin()} instead.
     */
    @Deprecated
    public void setAutoCommit(boolean autoCommit) throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();

        try {
            getQuadStoreConnection().setAutoCommit(autoCommit);
        }
        catch (SQLException e) {
            throw new RepositoryException(e);
        }
    }

    /**
     * Checks whether the connection is in auto-commit mode.
     *
     * @see #setAutoCommit
     * @deprecated since 2.7.0. Use {@link #isActive()} instead.
     */
    @Deprecated
    public boolean isAutoCommit() throws RepositoryException {
        verifyIsOpen();
        try {
            return getQuadStoreConnection().getAutoCommit();
        }
        catch (SQLException e) {
            throw new RepositoryException(e);
        }
    }

    /**
     * Indicates if a transaction is currently active on the connection. A
     * transaction is active if {@link #begin()} has been called, and becomes
     * inactive after {@link #commit()} or {@link #rollback()} has been called.
     *
     * @since 2.7.0
     * @return <code>true</code> iff a transaction is active, <code>false</code>
     *         iff no transaction is active.
     * @throws UnknownTransactionStateException
     *         if the transaction state can not be determined. This can happen
     *         for instance when communication with a repository fails or times
     *         out.
     * @throws RepositoryException
     */
    public boolean isActive() throws RepositoryException {
        verifyIsOpen();
        try {
            return !getQuadStoreConnection().getAutoCommit();
        }
        catch (SQLException e) {
            throw new RepositoryException(e);
        }
    }

    /**
     * Sets the transaction isolation level for the next transaction(s) on this
     * connection. If the level is set to a value that is not supported by the
     * underlying repository, this method will still succeed but a subsequent
     * call to {@link #begin()} will result in an exception.
     *
     * @param level
     *        the transaction isolation level to set.
     * @throws IllegalStateException
     *         if the method is called while a transaction is already active.
     * @since 2.8.0
     */
    public void setIsolationLevel(IsolationLevel level) throws IllegalStateException {
        try {
            if (isActive()) {
                throw new IllegalStateException(
                        "Transaction isolation level can not be modified while transaction is active");
            }
            this.isolationLevel = level;
        }
        catch (UnknownTransactionStateException e) {
            throw new IllegalStateException(
                    "Transaction isolation level can not be modified while transaction state is unknown", e);

        }
        catch (RepositoryException e) {
            throw new IllegalStateException(
                    "Transaction isolation level can not be modified due to repository error", e);
        }
    }

    /**
     * Retrieves the current {@link IsolationLevel transaction isolation level}
     * of the connection.
     *
     * @return the current transaction isolation level.
     * @since 2.8.0
     */
    public IsolationLevel getIsolationLevel() {
        return this.isolationLevel;
    }

    /**
     * Begins a transaction requiring {@link #commit()} or {@link #rollback()} to
     * be called to end the transaction.
     *
     * @throws RepositoryException
     *         If the connection could not start a transaction.
     * @see #isActive()
     * @see #commit()
     * @see #rollback()
     * @since 2.7.0
     */
    public void begin() throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        verifyNotTxnActive("Connection already has an active transaction");

        try {
            Connection conn = getQuadStoreConnection();
            conn.setAutoCommit(false);

            if (isolationLevel == IsolationLevels.READ_UNCOMMITTED)
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            else if (isolationLevel == IsolationLevels.READ_COMMITTED)
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            else if (isolationLevel == IsolationLevels.SNAPSHOT_READ)
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            else if (isolationLevel == IsolationLevels.SNAPSHOT)
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            else if (isolationLevel == IsolationLevels.SERIALIZABLE)
                conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        }
        catch (SQLException e) {
            throw new RepositoryException(e);
        }
    }

    /**
     * Begins a new transaction with the supplied {@link IsolationLevel},
     * requiring {@link #commit()} or {@link #rollback()} to be called to end the
     * transaction.
     *
     * @param level
     *        The {@link IsolationLevel} at which this transaction will operate.
     *        If set to <code>null</code> the default isolation level of the
     *        underlying store will be used. If the specified isolation level is
     *        not supported by the underlying store, it will attempt to use a
     *        supported {@link IsolationLevel#isCompatibleWith(IsolationLevel)
     *        compatible level} instead.
     * @throws RepositoryException
     *         If the connection could not start the transaction. Possible
     *         reasons this may happen are:
     *         <ul>
     *         <li>a transaction is already {@link #isActive() active} on the
     *         current connection.
     *         <li>the specified {@link IsolationLevel} is not supported by the
     *         store, and no compatible level could be found.
     *         </ul>
     * @see #begin()
     * @see #isActive()
     * @see #commit()
     * @see #rollback()
     * @see #setIsolationLevel(IsolationLevel)
     * @since 2.8.0
     */
    public void begin(IsolationLevel level) throws RepositoryException {
        setIsolationLevel(level);
        begin();
    }

    /**
     * Commits all updates that have been performed as part of this connection
     * sofar.
     *
     * @throws RepositoryException
     *         If the connection could not be committed.
     */
    public void commit() throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        try {
            getQuadStoreConnection().commit();
            getQuadStoreConnection().setAutoCommit(true);
        }
        catch (SQLException e) {
            throw new RepositoryException(e);
        }
    }

    /**
     * Rolls back all updates that have been performed as part of this connection
     * sofar.
     *
     * @throws RepositoryException
     *         If the connection could not be rolled back.
     */
    public void rollback() throws RepositoryException {
        verifyIsOpen();
        dropDelayAdd();
        try {
            getQuadStoreConnection().rollback();
            getQuadStoreConnection().setAutoCommit(true);
        }
        catch (SQLException e) {
            throw new RepositoryException("Problem with rollback", e);
        }
    }

    /**
     * Adds RDF data from an InputStream to the repository, optionally to one or
     * more named contexts.
     *
     * @param in
     *        An InputStream from which RDF data can be read.
     * @param baseURI
     *        The base URI to resolve any relative URIs that are in the data
     *        against.
     * @param dataFormat
     *        The serialization format of the data.
     * @param contexts
     *        The contexts to add the data to. If one or more contexts are
     *        supplied the method ignores contextual information in the actual
     *        data. If no contexts are supplied the contextual information in the
     *        input stream is used, if no context information is available the
     *        data is added without any context.
     * @throws IOException
     *         If an I/O error occurred while reading from the input stream.
     * @throws UnsupportedRDFormatException
     *         If no parser is available for the specified RDF format.
     * @throws RDFParseException
     *         If an error was found while parsing the RDF data.
     * @throws RepositoryException
     *         If the data could not be added to the repository, for example
     *         because the repository is not writable.
     */
    public void add(InputStream in, String baseURI, RDFFormat dataFormat, Resource... contexts) throws IOException, RDFParseException, RepositoryException {
        Reader reader = new InputStreamReader(in);
        add(reader, baseURI, dataFormat, contexts);
    }

    /**
     * Adds RDF data from a Reader to the repository, optionally to one or more
     * named contexts. <b>Note: using a Reader to upload byte-based data means
     * that you have to be careful not to destroy the data's character encoding
     * by enforcing a default character encoding upon the bytes. If possible,
     * adding such data using an InputStream is to be preferred.</b>
     *
     * @param reader
     *        A Reader from which RDF data can be read.
     * @param baseURI
     *        The base URI to resolve any relative URIs that are in the data
     *        against.
     * @param dataFormat
     *        The serialization format of the data.
     * @param contexts
     *        The contexts to add the data to. If one or more contexts are
     *        specified the data is added to these contexts, ignoring any context
     *        information in the data itself.
     * @throws IOException
     *         If an I/O error occurred while reading from the reader.
     * @throws UnsupportedRDFormatException
     *         If no parser is available for the specified RDF format.
     * @throws RDFParseException
     *         If an error was found while parsing the RDF data.
     * @throws RepositoryException
     *         If the data could not be added to the repository, for example
     *         because the repository is not writable.
     */
    public synchronized void add(Reader reader, String baseURI, RDFFormat dataFormat, final Resource... contexts) throws IOException, RDFParseException, RepositoryException {
        verifyIsOpen();
        flushDelayAdd();

        final boolean useStatementContext = (contexts != null && contexts.length == 0); // If no context are specified, each statement is added to statement context

        try {
            RDFParser parser = Rio.createParser(dataFormat, getValueFactory());
            parser.setParserConfig(getParserConfig());
            parser.setParseErrorListener(new ParseErrorLogger());

            // set up a handler for parsing the data from reader

            parser.setRDFHandler(new AbstractRDFHandler() {

                int count = 0;
                PreparedStatement ps = null;
                java.sql.Statement st_cmd = null;
                Resource[] _contexts = checkDMLContext(contexts);

                public void startRDF() throws RDFHandlerException {
                    if (!insertBNodeAsVirtuosoIRI) {
                        try {
                            st_cmd = createStatement(-1, false);
                            st_cmd.executeUpdate("connection_set ('RDF_INSERT_TRIPLE_C_BNODES', dict_new(1000))");
                        }
                        catch (SQLException e) {
                            throw new RDFHandlerException("Problem with creation of BNode cache: ", e);
                        }
                    }
                }

                public void endRDF() throws RDFHandlerException {
                    try {
                        if (count > 0)
                            ps = flushDelayAdd_batch(ps, count);
                    }
                    catch (RepositoryException e) {
                        throw new RDFHandlerException("Problem executing query: ", e);
                    }
                    try {
                        if (st_cmd!=null)
                            st_cmd.executeUpdate("connection_set ('RDF_INSERT_TRIPLE_C_BNODES', NULL)");
                    }
                    catch (SQLException e) {
                        throw new RDFHandlerException("Problem with clearing of BNode cache: ", e);
                    }
                    if (ps != null) {
                        try {
                            ps.close();
                        } catch (Exception e) {}
                    }
                    if (st_cmd != null) {
                        try {
                            st_cmd.close();
                        } catch (Exception e) {}
                    }
                    ps = null;
                    st_cmd = null;
                    count = 0;
                }

                public void handleNamespace(String prefix, String name) throws RDFHandlerException {
                    String query = "DB.DBA.XML_SET_NS_DECL(?, ?, 1)";
                    try {
                        PreparedStatement psn = prepareStatement(query, false);
                        psn.setString(1, prefix);
                        psn.setString(2, name);
                        psn.execute();
                        psn.close();
                    }
                    catch (SQLException e) {
                        throw new RDFHandlerException("Problem executing query: " + query, e);
                    }
                }

                public void handleStatement(Statement st) throws RDFHandlerException {
                    try {
                        Resource[] hcontexts;
                        if (st.getContext() != null && useStatementContext) {
                            hcontexts = new Resource[] {st.getContext()};
                        } else {
                            hcontexts = _contexts;
                        }

                        ps = addToQuadStore_batch(ps, st.getSubject(),
                                st.getPredicate(), st.getObject(), hcontexts);
                        count += hcontexts.length;

                        if (count > BATCH_SIZE) {
                            ps = flushDelayAdd_batch(ps, count);
                            count = 0;
                        }
                    }
                    catch(Exception e) {
                        throw new RDFHandlerException(e);
                    }
                }
            });
            parser.parse(reader, baseURI); // parse out each tripled to be handled by the handler above
        }
        catch (Exception e) {
            throw new RepositoryException("Problem parsing triples", e);
        }
    }

    /**
     * Adds the RDF data that can be found at the specified URL to the
     * repository, optionally to one or more named contexts.
     *
     * @param url
     *        The URL of the RDF data.
     * @param baseURI
     *        The base URI to resolve any relative URIs that are in the data
     *        against. This defaults to the value of {@link
     *        java.net.URL#toExternalForm() url.toExternalForm()} if the value is
     *        set to <tt>null</tt>.
     * @param dataFormat
     *        The serialization format of the data.
     * @param contexts
     *        The contexts to add the data to. If one or more contexts are
     *        specified the data is added to these contexts, ignoring any context
     *        information in the data itself.
     * @throws IOException
     *         If an I/O error occurred while reading from the URL.
     * @throws UnsupportedRDFormatException
     *         If no parser is available for the specified RDF format.
     * @throws RDFParseException
     *         If an error was found while parsing the RDF data.
     * @throws RepositoryException
     *         If the data could not be added to the repository, for example
     *         because the repository is not writable.
     */
    public void add(URL url, String baseURI, RDFFormat dataFormat, Resource... contexts) throws IOException, RDFParseException, RepositoryException {
        // add data to Sesame
        if (baseURI == null) {
            baseURI = url.toExternalForm();
        }
        Reader reader = new InputStreamReader(url.openStream());
        try {
            add(reader, baseURI, dataFormat, contexts);
        } finally {
            reader.close();
        }
    }

    /**
     * Adds RDF data from the specified file to a specific contexts in the
     * repository.
     *
     * @param file
     *        A file containing RDF data.
     * @param baseURI
     *        The base URI to resolve any relative URIs that are in the data
     *        against. This defaults to the value of
     *        {@link java.io.File#toURI() file.toURI()} if the value is set to
     *        <tt>null</tt>.
     * @param dataFormat
     *        The serialization format of the data.
     * @param contexts
     *        The contexts to add the data to. Note that this parameter is a
     *        vararg and as such is optional. If no contexts are specified, the
     *        data is added to any context specified in the actual data file, or
     *        if the data contains no context, it is added without context. If
     *        one or more contexts are specified the data is added to these
     *        contexts, ignoring any context information in the data itself.
     * @throws IOException
     *         If an I/O error occurred while reading from the file.
     * @throws UnsupportedRDFormatException
     *         If no parser is available for the specified RDF format.
     * @throws RDFParseException
     *         If an error was found while parsing the RDF data.
     * @throws RepositoryException
     *         If the data could not be added to the repository, for example
     *         because the repository is not writable.
     */
    public void add(File file, String baseURI, RDFFormat dataFormat, Resource... contexts) throws IOException, RDFParseException, RepositoryException {
        if (baseURI == null) {
            // default baseURI to file
            baseURI = file.toURI().toString();
        }
        InputStream reader = new FileInputStream(file);
        try {
            add(reader, baseURI, dataFormat, contexts);
        } finally {
            reader.close();
        }
    }

    /**
     * Adds a statement with the specified subject, predicate and object to this
     * repository, optionally to one or more named contexts.
     *
     * @param subject
     *        The statement's subject.
     * @param predicate
     *        The statement's predicate.
     * @param object
     *        The statement's object.
     * @param contexts
     *        The contexts to add the data to. Note that this parameter is a
     *        vararg and as such is optional. If no contexts are specified, the
     *        data is added to any context specified in the actual data file, or
     *        if the data contains no context, it is added without context. If
     *        one or more contexts are specified the data is added to these
     *        contexts, ignoring any context information in the data itself.
     * @throws RepositoryException
     *         If the data could not be added to the repository, for example
     *         because the repository is not writable.
     */
    public void add(Resource subject, IRI predicate, Value object, Resource... contexts) throws RepositoryException {
        contexts = checkDMLContext(contexts);
        addToQuadStore(subject, predicate, object, contexts);
    }
    public void addQuad(Resource subject, IRI predicate, Value object, Resource context) throws RepositoryException {
        addToQuadStore(subject, predicate, object, context);
    }

    /**
     * Adds the supplied statement to this repository, optionally to one or more
     * named contexts.
     *
     * @param statement
     *        The statement to add.
     * @param contexts
     *        The contexts to add the statements to. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are specified, the
     *        statement is added to any context specified in each statement, or
     *        if the statement contains no context, it is added without context.
     *        If one or more contexts are specified the statement is added to
     *        these contexts, ignoring any context information in the statement
     *        itself.
     * @throws RepositoryException
     *         If the statement could not be added to the repository, for example
     *         because the repository is not writable.
     */
    public void add(Statement statement, Resource... contexts) throws RepositoryException {
        if (contexts != null && contexts.length == 0 &&  statement.getContext() != null) {
            contexts = new Resource[] { statement.getContext() }; // try the context given by the statement
        }
        add(statement.getSubject(), statement.getPredicate(), statement.getObject(), contexts);
    }

    /**
     * Adds the supplied statements to this repository, optionally to one or more
     * named contexts.
     *
     * @param statements
     *        The statements that should be added.
     * @param contexts
     *        The contexts to add the statements to. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are specified,
     *        each statement is added to any context specified in the statement,
     *        or if the statement contains no context, it is added without
     *        context. If one or more contexts are specified each statement is
     *        added to these contexts, ignoring any context information in the
     *        statement itself. ignored.
     * @throws RepositoryException
     *         If the statements could not be added to the repository, for
     *         example because the repository is not writable.
     */
    public synchronized void add(Iterable<? extends Statement> statements, Resource... contexts) throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();

        Iterator<? extends Statement> it = statements.iterator();
        boolean useStatementContext = (contexts != null && contexts.length == 0); // If no context are specified, each statement is added to statement context
        Resource[] _contexts = checkDMLContext(contexts); // otherwise, either use all contexts, or do not specify a context

        int count = 0;
        PreparedStatement ps = null;
        java.sql.Statement st_cmd = null;

        try {
            if (!insertBNodeAsVirtuosoIRI) {
                st_cmd = createStatement(-1, false);
                st_cmd.executeUpdate("connection_set ('RDF_INSERT_TRIPLE_C_BNODES', dict_new(1000))");
            }

            while (it.hasNext()) {
                Statement st = it.next();

                if (st.getContext() != null && useStatementContext) {
                    contexts = new Resource[] {st.getContext()};
                } else {
                    contexts = _contexts;
                }

                ps = addToQuadStore_batch(ps, st.getSubject(),
                        st.getPredicate(), st.getObject(), contexts);
                count += contexts.length;

                if (count > BATCH_SIZE) {
                    ps = flushDelayAdd_batch(ps, count);
                    count = 0;
                }
            }
            if (count > 0)
                ps = flushDelayAdd_batch(ps, count);
            if (st_cmd!=null)
                st_cmd.executeUpdate("connection_set ('RDF_INSERT_TRIPLE_C_BNODES', NULL)");
        }
        catch(Exception e) {
            throw new RepositoryException(e);
        }
        finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {}
            }
            if (st_cmd != null) {
                try {
                    st_cmd.close();
                } catch (Exception e) {}
            }
        }
    }

    /**
     * Adds the supplied statements to this repository, optionally to one or more
     * named contexts.
     *
     * @param statements
     *        The statements to add. In case the iterator is a
     *        {@link CloseableIteration}, it will be closed before this method
     *        returns.
     * @param contexts
     *        The contexts to add the statements to. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are specified,
     *        each statement is added to any context specified in the statement,
     *        or if the statement contains no context, it is added without
     *        context. If one or more contexts are specified each statement is
     *        added to these contexts, ignoring any context information in the
     *        statement itself. ignored.
     * @throws RepositoryException
     *         If the statements could not be added to the repository, for
     *         example because the repository is not writable.
     */
    public synchronized  <E extends Exception> void add(Iteration<? extends Statement, E> statements, Resource... contexts) throws RepositoryException, E {
        verifyIsOpen();
        flushDelayAdd();

        boolean useStatementContext = (contexts != null && contexts.length == 0); // If no context are specified, each statement is added to statement context
        Resource[] _contexts = checkDMLContext(contexts); // otherwise, either use all contexts, or do not specify a context

        int count = 0;
        PreparedStatement ps = null;
        java.sql.Statement st_cmd = null;

        try {
            if (!insertBNodeAsVirtuosoIRI) {
                st_cmd = createStatement(-1, false);
                st_cmd.executeUpdate("connection_set ('RDF_INSERT_TRIPLE_C_BNODES', dict_new(1000))");
            }

            while (statements.hasNext()) {
                Statement st = statements.next();

                if (st.getContext() != null && useStatementContext) {
                    contexts = new Resource[] {st.getContext()};
                } else {
                    contexts = _contexts;
                }

                ps = addToQuadStore_batch(ps, st.getSubject(),
                        st.getPredicate(), st.getObject(), contexts);
                count += contexts.length;

                if (count > BATCH_SIZE) {
                    ps = flushDelayAdd_batch(ps, count);
                    count = 0;
                }
            }

            if (count > 0)
                ps = flushDelayAdd_batch(ps, count);
            if (st_cmd!=null)
                st_cmd.executeUpdate("connection_set ('RDF_INSERT_TRIPLE_C_BNODES', NULL)");
        }
        catch(Exception e) {
            throw new RepositoryException(e);
        }
        finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {}
            }
            if (st_cmd != null) {
                try {
                    st_cmd.close();
                } catch (Exception e) {}
            }
            Iterations.closeCloseable(statements);
        }
    }

    /**
     * Removes the statement(s) with the specified subject, predicate and object
     * from the repository, optionally restricted to the specified contexts.
     *
     * @param subject
     *        The statement's subject, or <tt>null</tt> for a wildcard.
     * @param predicate
     *        The statement's predicate, or <tt>null</tt> for a wildcard.
     * @param object
     *        The statement's object, or <tt>null</tt> for a wildcard.
     * @param contexts
     *        The context(s) to remove the data from. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are supplied the
     *        method operates on the entire repository.
     * @throws RepositoryException
     *         If the statement(s) could not be removed from the repository, for
     *         example because the repository is not writable.
     */
    public void remove(Resource subject, IRI predicate, Value object, Resource... contexts) throws RepositoryException {
        OpenRDFUtil.verifyContextNotNull(contexts);
        verifyIsOpen();
        flushDelayAdd();

        contexts = checkDMLContext(contexts);

        for (Resource context : contexts) removeContext(subject, predicate, object, context);
    }

    /**
     * Removes the supplied statement from the specified contexts in the
     * repository.
     *
     * @param statement
     *        The statement to remove.
     * @param contexts
     *        The context(s) to remove the data from. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are supplied the
     *        method operates on the contexts associated with the statement
     *        itself, and if no context is associated with the statement, on the
     *        entire repository.
     * @throws RepositoryException
     *         If the statement could not be removed from the repository, for
     *         example because the repository is not writable.
     */
    public void remove(Statement statement, Resource... contexts) throws RepositoryException {
        if (contexts != null && contexts.length == 0 &&  statement.getContext() != null) {
            contexts = new Resource[] { statement.getContext() }; // try the context given by the statement
        }
        remove(statement.getSubject(), statement.getPredicate(), statement.getObject(), contexts);
    }

    /**
     * Removes the supplied statements from the specified contexts in this
     * repository.
     *
     * @param statements
     *        The statements that should be removed.
     * @param contexts
     *        The context(s) to remove the data from. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are supplied the
     *        method operates on the contexts associated with the statement
     *        itself, and if no context is associated with the statement, on the
     *        entire repository.
     * @throws RepositoryException
     *         If the statements could not be added to the repository, for
     *         example because the repository is not writable.
     */
    public void remove(Iterable<? extends Statement> statements, Resource... contexts) throws RepositoryException {
        OpenRDFUtil.verifyContextNotNull(contexts);
        verifyIsOpen();
        flushDelayAdd();

        Resource[] _contexts;
        Iterator<? extends Statement> it = statements.iterator();
        int count = 0;
        HashMap<String, StringBuilder> map = new HashMap<String,StringBuilder>();

        while (it.hasNext()) {
            Statement st = it.next();

            if (contexts.length == 0 &&  st.getContext() != null)
                _contexts = new Resource[] { st.getContext() }; // try the context given by the statement
            else
                _contexts = contexts;
            _contexts = checkDMLContext(_contexts);

            for (Resource _context : _contexts) {
                String ctx = _context.toString();
                StringBuilder row = new StringBuilder(256);

                append(st.getSubject(), row, true);
                row.append(' ');
                append(st.getPredicate(), row, true);
                row.append(' ');
                append(st.getObject(), row, true);
                row.append(" .\n");

                StringBuilder data = map.get(ctx);
                if (count > 0 && data != null && data.length() + row.length() > MAX_CMD_SIZE) {
                    removeData(map);
                    map.clear();
                    count = 0;
                    data = null;
                }

                if (data == null)
                    data = new StringBuilder(256);
                data.append(row);
                map.put(ctx, data);
                count++;
            }
        }
        if (count > 0)
            removeData(map);
        map.clear();
    }

    /**
     * Removes the supplied statements from a specific context in this
     * repository, ignoring any context information carried by the statements
     * themselves.
     *
     * @param statements
     *        The statements to remove. In case the iterator is a
     *        {@link CloseableIteration}, it will be closed before this method
     *        returns.
     * @param contexts
     *        The context(s) to remove the data from. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are supplied the
     *        method operates on the contexts associated with the statement
     *        itself, and if no context is associated with the statement, on the
     *        entire repository.
     * @throws RepositoryException
     *         If the statements could not be removed from the repository, for
     *         example because the repository is not writable.
     */
    public <E extends Exception> void remove(Iteration<? extends Statement, E> statements, Resource... contexts) throws RepositoryException, E {
        OpenRDFUtil.verifyContextNotNull(contexts);
        verifyIsOpen();
        flushDelayAdd();

        Resource[] _contexts;
        int count = 0;
        HashMap<String, StringBuilder> map = new HashMap<String,StringBuilder>();

        try {
            while (statements.hasNext()) {
                Statement st = statements.next();

                if (contexts.length == 0 &&  st.getContext() != null)
                    _contexts = new Resource[] { st.getContext() }; // try the context given by the statement
                else
                    _contexts = contexts;
                _contexts = checkDMLContext(_contexts);

                for (Resource _context : _contexts) {
                    String ctx = _context.toString();
                    StringBuilder row = new StringBuilder(256);

                    append(st.getSubject(), row, true);
                    row.append(' ');
                    append(st.getPredicate(), row, true);
                    row.append(' ');
                    append(st.getObject(), row, true);
                    row.append(" .\n");

                    StringBuilder data = map.get(ctx);
                    if (count > 0 && data != null && data.length() + row.length() > MAX_CMD_SIZE) {
                        removeData(map);
                        map.clear();
                        count = 0;
                        data = null;
                    }

                    if (data == null)
                        data = new StringBuilder(256);
                    data.append(row);
                    map.put(ctx, data);
                    count++;
                }
            }
            if (count > 0)
                removeData(map);
            map.clear();
        }
        finally {
            Iterations.closeCloseable(statements);
        }
    }

    /**
     * Removes all statements from a specific contexts in the repository.
     *
     * @param contexts
     *        The context(s) to remove the data from. Note that this parameter is
     *        a vararg and as such is optional. If no contexts are supplied the
     *        method operates on the entire repository.
     * @throws RepositoryException
     *         If the statements could not be removed from the repository, for
     *         example because the repository is not writable.
     */
    public void clear(Resource... contexts) throws RepositoryException {
        OpenRDFUtil.verifyContextNotNull(contexts);
        verifyIsOpen();
        flushDelayAdd();

        contexts = checkDMLContext(contexts);

        clearQuadStore(contexts);
    }

    /**
     * Gets all declared namespaces as a RepositoryResult of {@link Namespace}
     * objects. Each Namespace object consists of a prefix and a namespace name.
     *
     * @return A RepositoryResult containing Namespace objects. Care should be
     *         taken to close the RepositoryResult after use.
     * @throws RepositoryException
     *         If the namespaces could not be read from the repository.
     */
    public RepositoryResult<Namespace> getNamespaces() throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        List<Namespace> namespaceList = new ArrayList<Namespace>();
        String query = "DB.DBA.XML_SELECT_ALL_NS_DECLS (3)";
        try {
            java.sql.Statement stmt = createStatement(-1, false);
            ResultSet rs = stmt.executeQuery(query);

            // begin at onset one
            while (rs.next()) {
                String prefix = rs.getString(1);
                String name = rs.getString(2);
                if (name != null && prefix != null) {
                    Namespace ns = new SimpleNamespace(prefix, name);
                    namespaceList.add(ns);
                }
            }
            rs.close();
            stmt.close();
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
        return createRepositoryResult(namespaceList);// new RepositoryResult<Namespace>(new IteratorWrapper(v.iterator()));
    }

    /**
     * Gets the namespace that is associated with the specified prefix, if any.
     *
     * @param prefix
     *        A namespace prefix.
     * @return The namespace name that is associated with the specified prefix,
     *         or <tt>null</tt> if there is no such namespace.
     * @throws RepositoryException
     *         If the namespace could not be read from the repository.
     */
    public String getNamespace(String prefix) throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        String retVal = null;
        String query = "SELECT __xml_get_ns_uri (?, 3)";
        try {
            PreparedStatement ps = prepareStatement(query, false);
            ps.setString(1, prefix);
            ResultSet rs = ps.executeQuery();

            // begin at onset one
            while (rs.next()) {
                retVal = rs.getString(1);
                break;
            }
            ps.close();
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
        return retVal;
    }

    /**
     * Sets the prefix for a namespace.
     *
     * @param prefix
     *        The new prefix.
     * @param name
     *        The namespace name that the prefix maps to.
     * @throws RepositoryException
     *         If the namespace could not be set in the repository, for example
     *         because the repository is not writable.
     */
    public void setNamespace(String prefix, String name) throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        String query = "DB.DBA.XML_SET_NS_DECL(?, ?, 2)";
        try {
            PreparedStatement ps = prepareStatement(query, false);
            ps.setString(1, prefix);
            ps.setString(2, name);
            ps.execute();
            ps.close();
        }
        catch (SQLException e) {
            throw new RepositoryException("Problem executing query: " + query, e);
        }
    }

    /**
     * Removes a namespace declaration by removing the association between a
     * prefix and a namespace name.
     *
     * @param prefix
     *        The namespace prefix of which the assocation with a namespace name
     *        is to be removed.
     * @throws RepositoryException
     *         If the namespace prefix could not be removed.
     */
    public void removeNamespace(String prefix) throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        String query = "DB.DBA.XML_REMOVE_NS_BY_PREFIX(?, 2)";
        try {
            PreparedStatement ps = prepareStatement(query, false);
            ps.setString(1, prefix);
            ps.execute();
            ps.close();
        }
        catch (SQLException e) {
            throw new RepositoryException("Problem executing query: " + query, e);
        }
    }

    /**
     * Removes all namespace declarations from the repository.
     *
     * @throws RepositoryException
     *         If the namespace declarations could not be removed.
     */
    public void clearNamespaces() throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();
        String query = "DB.DBA.XML_CLEAR_ALL_NS_DECLS(2)";
        try {
            java.sql.Statement stmt = createStatement(-1, true);
            stmt.execute(query);
            stmt.close();
        }
        catch (SQLException e) {
            throw new RepositoryException("Problem executing query: " + query, e);
        }
    }


    protected TupleQueryResult executeSPARQLForTupleResult(String baseURI, String query,
                                                           Dataset dataset, boolean includeInferred, BindingSet bindings,
                                                           int maxQueryTime) throws QueryEvaluationException
    {

        List<String> names = new ArrayList<String>();
        try {
            PreparedStatement stmt = executeSPARQL(baseURI, query, dataset, includeInferred, bindings, maxQueryTime, false);
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();

            // begin at onset one
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String col = rsmd.getColumnName(i);
                if (names.indexOf(col) < 0)
                    names.add(col); // no duplicates
            }

            return new IteratingTupleQueryResult(names, new CloseableIterationBindingSet(stmt, rs));
        }
        catch (Exception e) {
            throw new QueryEvaluationException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }
    }

    protected GraphQueryResult executeSPARQLForGraphResult(String baseURI, String query,
                                                           Dataset dataset, boolean includeInferred, BindingSet bindings,
                                                           int maxQueryTime) throws QueryEvaluationException
    {
//        HashMap<String,Integer> names = new HashMap<String,Integer>();
        try {
            PreparedStatement stmt = executeSPARQL(baseURI, query, dataset, includeInferred, bindings, maxQueryTime, false);
            ResultSet rs = stmt.executeQuery();
//            ResultSetMetaData rsmd = rs.getMetaData();

            // begin at onset one
/**
            for (int i = 1; i <= rsmd.getColumnCount(); i++)
                names.put(rsmd.getColumnName(i), new Integer(i));
**/
            return new IteratingGraphQueryResult(new HashMap<String,String>(), new CloseableIterationGraphResult(stmt, rs));
        }
        catch (Exception e) {
            throw new QueryEvaluationException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }

    }

    protected boolean executeSPARQLForBooleanResult(String baseURI, String query,
                                                    Dataset dataset, boolean includeInferred, BindingSet bindings,
                                                    int maxQueryTime) throws QueryEvaluationException
    {
        boolean result = false;
        try {
            PreparedStatement stmt = executeSPARQL(baseURI, query, dataset, includeInferred, bindings, maxQueryTime, false);
            ResultSet rs = stmt.executeQuery();

            while(rs.next())
            {
                if (rs.getInt(1) == 1)
                    result = true;
            }
            stmt.close();

            return result;
        }
        catch (Exception e) {
            throw new QueryEvaluationException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }
    }


    protected void executeSPARQLForHandler(String baseURI,  TupleQueryResultHandler tqrh,
                                           String query, Dataset dataset, boolean includeInferred,
                                           BindingSet bindings, int maxQueryTime) throws QueryEvaluationException, TupleQueryResultHandlerException
    {
        LinkedList<String> names = new LinkedList<String>();
        try {
            PreparedStatement stmt = executeSPARQL(baseURI, query, dataset, includeInferred, bindings, maxQueryTime, false);
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            // begin at onset one
            for (int i = 1; i <= rsmd.getColumnCount(); i++)
                names.add(rsmd.getColumnName(i));

            tqrh.startQueryResult(names);
            // begin at onset one
            while (rs.next()) {
                QueryBindingSet qbs = new QueryBindingSet();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    // TODO need to parse these into appropriate resource values
                    String col = rsmd.getColumnName(i);
                    Object val = rs.getObject(i);
                    if (val!=null){
                        Value v = castValue(val);
                        qbs.addBinding(col, v);
                    }
                }
                tqrh.handleSolution(qbs);
            }
            tqrh.endQueryResult();
            stmt.close();
        }
        catch (Exception e) {
            throw new QueryEvaluationException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }
    }


    protected void executeSPARQLForHandler(String baseURI, RDFHandler tqrh, String query,
                                           Dataset dataset, boolean includeInferred, BindingSet bindings,
                                           int maxQueryTime) throws QueryEvaluationException, RDFHandlerException
    {
        try {
            PreparedStatement stmt = executeSPARQL(baseURI, query, dataset, includeInferred, bindings, maxQueryTime, false);
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int col_g = -1;
            int col_s = -1;
            int col_p = -1;
            int col_o = -1;

            // begin at onset one
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String label = rsmd.getColumnName(i);
                if (label.equalsIgnoreCase("g"))
                    col_g = i;
                else if (label.equalsIgnoreCase("s"))
                    col_s = i;
                else if (label.equalsIgnoreCase("p"))
                    col_p = i;
                else if (label.equalsIgnoreCase("o"))
                    col_o = i;
            }

            tqrh.startRDF();
            while (rs.next()) {
                Resource sval = null;
                IRI pval = null;
                Value oval = null;
                Resource gval = null;

                if (col_s != -1)
                    sval = (Resource) castValue(rs.getObject(col_s));

                if (col_p != -1)
                    pval = (IRI) castValue(rs.getObject(col_p));

                if (col_o != -1)
                    oval = castValue(rs.getObject(col_o));

                if (col_g != -1)
                    gval = (Resource) castValue(rs.getObject(col_g));

                Statement st = valueFactory.createStatement(sval, pval, oval, gval);
                tqrh.handleStatement(st);
            }
            tqrh.endRDF();
            stmt.close();
        }
        catch (Exception e) {
            throw new QueryEvaluationException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }
    }


    private PreparedStatement executeSPARQL(String baseURI, String query,
                                            Dataset dataset, boolean includeInferred, BindingSet bindings,
                                            int maxQueryTime, boolean isIUD) throws RepositoryException, SQLException
    {
        verifyIsOpen();
        flushDelayAdd();
        List<Value> pstmtParams = new ArrayList<Value>();
        String fixedQuery = fixQuery(false, query, dataset, includeInferred, bindings, pstmtParams, baseURI);
        PreparedStatement stmt = prepareStatement(fixedQuery, maxQueryTime, isIUD);
        setQueryParams(stmt, pstmtParams);
        return stmt;
    }

    protected void executeSPARUL(String baseURI, String query, Dataset dataset,
                                 boolean includeInferred, BindingSet bindings, int maxQueryTime) throws UpdateExecutionException
    {
        try {
            PreparedStatement stmt = executeSPARQL(baseURI, query, dataset, includeInferred, bindings, maxQueryTime, true);
            stmt.execute();
            stmt.close();
        }
        catch (Exception e) {
            throw new UpdateExecutionException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }
    }


    /**
     * Execute SPARUL query on this repository.
     *
     * @param query
     *        The query string.
     * @return A rowUpdateCount.
     * @throws RepositoryException
     *         If the <tt>prepareQuery</tt> method is not supported by this
     *         repository.
     */
    public int executeSPARUL(String query) throws RepositoryException {

        java.sql.Statement stmt = null;
        try {
            verifyIsOpen();
            flushDelayAdd();
            stmt = createStatement(-1, true);
            stmt.execute("sparql\n " + query);
            return stmt.getUpdateCount();
        }
        catch (SQLException e) {
            throw new RepositoryException(": SPARQL execute failed:["+query+"] \n Exception:"+e);
        }
        finally {
            try {
                if (stmt != null)
                    stmt.close();
            } catch (Exception e) {}
        }
    }

    /**
     * Get Reposetory Connection.
     *
     * @return Repository Connection
     */
    public Connection getQuadStoreConnection() {
        return quadStoreConnection;
    }

    /**
     * Set Repository Connection.
     *
     * @param quadStoreConnection
     *        The Repository Connection.
     */
    public void setQuadStoreConnection(Connection quadStoreConnection) {
        this.quadStoreConnection = quadStoreConnection;
    }

    private int getJdbcConcurrency(boolean isIUD) {
        if (isIUD)
            switch(this.concurencyMode) {
                case VirtuosoRepository.CONCUR_PESSIMISTIC:
                    return VirtuosoResultSet.CONCUR_UPDATABLE;
                case VirtuosoRepository.CONCUR_OPTIMISTIC:
                    return VirtuosoResultSet.CONCUR_VALUES;
                default:
                    return VirtuosoResultSet.CONCUR_READ_ONLY;
            }
        else
            return VirtuosoResultSet.CONCUR_READ_ONLY;
    }

    private java.sql.Statement createStatement(int maxQueryTime, boolean isIUD) throws java.sql.SQLException
    {
        java.sql.Statement stmt = quadStoreConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, getJdbcConcurrency(isIUD));
        int timeout = queryTimeout;
        if (timeout > 0)
            stmt.setQueryTimeout(timeout);
        if (maxQueryTime > 0)
            stmt.setQueryTimeout(timeout);
        stmt.setFetchSize(prefetchSize);
        return stmt;
    }

    private java.sql.PreparedStatement prepareStatement(String sql, boolean isIUD) throws java.sql.SQLException
    {
        java.sql.PreparedStatement stmt = quadStoreConnection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, getJdbcConcurrency(isIUD));
        int timeout = queryTimeout;
        if (timeout > 0)
            stmt.setQueryTimeout(timeout);
        stmt.setFetchSize(prefetchSize);
        return stmt;
    }

    private java.sql.PreparedStatement prepareStatement(String sql, int maxQueryTime, boolean isIUD) throws java.sql.SQLException
    {
        java.sql.PreparedStatement stmt = quadStoreConnection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, getJdbcConcurrency(isIUD));
        int timeout = queryTimeout;
        if (timeout > 0)
            stmt.setQueryTimeout(timeout);
        if (maxQueryTime > 0)
            stmt.setQueryTimeout(timeout);
        stmt.setFetchSize(prefetchSize);
        return stmt;
    }

    private void setQueryParams(PreparedStatement stmt, List<Value> params) throws RepositoryException
    {
        int i = 0;
        for (Value value : params) {
            try {
                if (value instanceof Resource)
                    bindResource(stmt, ++i, (Resource)value);
                else
                    bindValue(stmt, ++i, value);
            } catch(SQLException e) {
                throw new RepositoryException("Failed to bind parameter " + value.toString() + " to the query.", e);
            }
        }
    }


    private String substBindings(String query, BindingSet bindings, List<Value> pstmtParams, boolean isSPARUL)  throws RepositoryException
    {
        boolean use_setParams = insertBNodeAsVirtuosoIRI ? false : true;
        StringBuilder tok = new StringBuilder();
        StringBuilder buf = new StringBuilder();
        String delim = " \t\n\r\f,)(;.}{";
        int inCurly = 0;
        int i = 0;
        char ch;
        boolean afterFROM = false;
        int qlen = query.length();

        while( i < qlen) {
            ch = query.charAt(i++);
            if (ch == '\\') {
                buf.append(ch);
                tok.append(ch);
                if (i < qlen) {
                    ch = query.charAt(i++);
                    buf.append(ch);
                    tok.append(ch);
                }

            } else if (ch == '"' || ch == '\'') {
                tok.setLength(0);
                char end = ch;
                buf.append(ch);
                while (i < qlen) {
                    ch = query.charAt(i++);
                    buf.append(ch);
                    if (ch == end)
                        break;
                }
            } else if ( ch == '{' ) {
                inCurly++;
                buf.append(ch);
                tok.setLength(0);
            } else if ( ch == '{' ) {
                inCurly--;
                buf.append(ch);
                tok.setLength(0);
            } else  if ( ch == '?' ) {  //Parameter
                tok.setLength(0);
                String varData = null;
                int j = i;
                while(j < qlen && delim.indexOf(query.charAt(j)) < 0) j++;
                if (j != i) {
                    boolean useBackSlash = (isSPARUL || inCurly > 0);
                    String varName = query.substring(i, j);
                    Value val = bindings.getValue(varName);
                    if (val != null) {
                        if (use_setParams) {
                            if (inCurly>0) { 
                                // in triple pattern
                            pstmtParams.add(val);
                            if (val instanceof Resource)
                                varData = "`iri(??)`";
                            else
                                varData = "`bif:__rdf_long_from_batch_params(??,??,??)`";
                        } else {
                                if (isSPARUL || afterFROM)
                                    varData = stringForValue(val, useBackSlash);
                                else
                                    varData = stringForValue(val, useBackSlash)+" AS ?"+varName;
                            }
                        } else {
                            if (inCurly==0 && !isSPARUL && !afterFROM) //for values in SELECT before triple pattern
                                varData = stringForValue(val, useBackSlash)+" AS ?"+varName;
                            else
                                varData = stringForValue(val, useBackSlash);
                        }

                        i=j;
                    }
                }
                if (varData != null)
                    buf.append(varData);
                else
                    buf.append(ch);
            } else {
                buf.append(ch);
                if (delim.indexOf(ch) < 0) {
                    tok.append(ch);
                } else {
                    if (tok.length()==4 
                        && (tok.charAt(0)=='F' || tok.charAt(0)=='f')
                        && tok.toString().equalsIgnoreCase("FROM")
                       )
                        afterFROM = true;
                    tok.setLength(0);
                }
            }
        }
        return buf.toString();
    }


    private String fixQuery(boolean isSPARUL, String query, Dataset dataset, boolean includeInferred, BindingSet bindings, List<Value> pstmtParams, String baseURI)  throws RepositoryException
    {
        boolean added_def_graph = false;
        Set <IRI> list;
        String removeGraph = null;
        String insertGraph = null;

        if (dataset != null)
        {
            //TODO update later, when support of new defines will be added
            list = dataset.getDefaultRemoveGraphs();
            if (list!=null)
            {
                if (list.size()>1)
                    throw new RepositoryException("Only ONE DefaultRemoveGraph is supported");

                Iterator<IRI> it = list.iterator();
                while(it.hasNext())
                {
                    removeGraph = " <"+it.next().toString()+"> ";
                    break;
                }
            }

            IRI g = dataset.getDefaultInsertGraph();
            if (g!=null)
                insertGraph = " <"+g.toString()+"> ";
        }

        query = SubstGraphs(query, insertGraph, removeGraph);

        StringBuilder ret = new StringBuilder("sparql\n");

        if (includeInferred && ruleSet!=null && ruleSet.length() > 0)
            ret.append("define input:inference '"+ruleSet+"'\n ");

        if (includeInferred && macroLib!=null && macroLib.length() > 0)
            ret.append("define input:macro-lib <"+macroLib+">\n ");

        if (dataset != null)
        {
            list = dataset.getDefaultGraphs();
            if (list != null)
            {
                Iterator<IRI> it = list.iterator();
                while(it.hasNext())
                {
                    IRI v = it.next();
                    ret.append(" define input:default-graph-uri <" + v.toString() + "> \n");
                    added_def_graph = true;
                }
            }

            list = dataset.getNamedGraphs();
            if (list != null)
            {
                Iterator<IRI> it = list.iterator();
                while(it.hasNext())
                {
                    IRI v = it.next();
                    ret.append(" define input:named-graph-uri <" + v.toString() + "> \n");
                }
            }
        }

	if (!added_def_graph && useDefGraphForQueries)
            ret.append(" define input:default-graph-uri <" + defGraph + "> \n");

        if (baseURI!=null && baseURI.length()>0)
            ret.append(" BASE <" + baseURI + "> \n");

        ret.append(substBindings(query, bindings, pstmtParams, isSPARUL));
        return ret.toString();
    }


    private String SubstGraphs(String query, String gInsert, String gDelete)
    {
        ArrayList<String> lst = new ArrayList<String>(16);
        StringBuilder buf = new StringBuilder();
        String delim = "{} \t\n\r\f";
        int i = 0;
        char ch;
        int qlen = query.length();

        while( i < qlen) {
            ch = query.charAt(i++);

            if (delim.indexOf(ch)>=0) {
                if (buf.length()>0) {
                    lst.add(buf.toString());
                    buf.setLength(0);
                }
                lst.add(""+ch);
            }
            else if (ch == '\\') {
                buf.append(ch);
                if (i < qlen)
                    buf.append(query.charAt(i++));

            }
            else if (ch == '"' || ch == '\'') {
                char end = ch;
                buf.append(ch);
                while (i < qlen) {
                    ch = query.charAt(i++);
                    buf.append(ch);
                    if (ch == end)
                        break;
                }

            } else {
                buf.append(ch);
            }
        }

        if (buf.length()>0)
            lst.add(buf.toString());

        if (gInsert!=null)
            fixTermOp(lst, "INSERT", "INTO", gInsert);
        if (gDelete!=null)
            fixTermOp(lst, "DELETE", "FROM", gDelete);

        buf.setLength(0);
        for(i=0; i<lst.size(); i++)
            buf.append(lst.get(i));

        return buf.toString();
    }

    /**
     * NOTES:
     * if WITH exists, it doesn't use addTerm
     * if GRAPH exists, it doesn't use addTerm
     * if INSERT INTO exists, it doesn't use addTerm
     * if DELETE FROM exists, it doesn't use addTerm
     **/
    private void fixTermOp(ArrayList<String> lst, String term, String subTerm, String addTerm)
    {
        int i;
        boolean WITH_used = false;
        boolean subTerm_used = false;
        boolean GRAPH_used = false;
        int in_term = -1;
        int term_cb_start = -1;

        for(i=0; i<lst.size(); i++) {
            String t = lst.get(i);

            if (t.equalsIgnoreCase("WITH") && in_term==-1) {
                WITH_used = true;
            }
            else if (t.equalsIgnoreCase(term)) {
                in_term = 0;
            }
            else if (t.equalsIgnoreCase(subTerm) && in_term==0) {
                subTerm_used = true;
            }
            else if (t.equals("{")) {
                if (in_term >=0) in_term++;

                if (in_term == 1)
                    term_cb_start = i;
            }
            else if (t.equals("}")) {
                if (in_term == 1)
                    in_term = -1;
                else
                    in_term--;
            }
            else if (t.equalsIgnoreCase("GRAPH")){
                if (in_term == 1)
                    GRAPH_used = true;
            }
        }

        if (addTerm!=null && !WITH_used && !subTerm_used && !GRAPH_used
                && term_cb_start!=-1) {
            lst.add(term_cb_start, " "+subTerm + addTerm);
        }
    }


    private synchronized void addToQuadStore(Resource subject, IRI predicate, Value object, Resource... contexts) throws RepositoryException
    {
        if (contexts.length == 0)
            return;

        try {
            boolean isAutoCommit = getQuadStoreConnection().getAutoCommit();

            if (psInsert == null)
                psInsert = prepareStatement(S_BATCH_INSERT, true);

            if (!insertBNodeAsVirtuosoIRI) {
                if (psInsert_BNode == null)
                    psInsert_BNode = prepareStatement(S_TTLP_INSERT, true);

                Object bn_s = null;
                Object bn_o = null;

                if (subject instanceof BNode)
                    bn_s = "_:"+((BNode)subject).getID().replace(':','_').replace('-','z').replace('/','y');
                if (object instanceof BNode) {
                    bn_o = "_:"+((BNode)object).getID().replace(':','_').replace('-','z').replace('/','y');
                }

                if (bn_s!=null || bn_o!=null) {
                    addToQuadStore_BNode(
                            bn_s!=null?bn_s:subject,
                            predicate,
                            bn_o!=null?bn_o:object, contexts);
                    psInsertBNodeCount += contexts.length;
                } else {
                    addToQuadStore_asURI(subject, predicate, object, contexts);
                    psInsertCount += contexts.length;
                }

            } else {
                addToQuadStore_asURI(subject, predicate, object, contexts);
                psInsertCount += contexts.length;
            }

            if (!isAutoCommit && useLazyAdd) {
                if (psInsertCount >= BATCH_SIZE || psInsertBNodeCount >= BATCH_SIZE)
                    flushDelayAdd();
            } else {
                flushDelayAdd();
            }
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
    }


    private synchronized void addToQuadStore_BNode(Object subject, IRI predicate,
                                                   Object object, Resource... contexts) throws RepositoryException
    {
        if (contexts.length == 0)
            return;

        verifyIsOpen();
        try {
            int transactional = quadStoreConnection.getAutoCommit()?0:1;

            for (Resource context : contexts) {

                String ctx = context.stringValue();
                StringBuilder sb = new StringBuilder(256);
                append(subject, sb, true);
                sb.append(' ');
                append(predicate, sb, true);
                sb.append(' ');
                append(object, sb, true);
                sb.append(" .\n");

                psInsert_BNode.setString(1, sb.toString());
                psInsert_BNode.setString(2, ctx);
                psInsert_BNode.setInt(3, transactional);
                psInsert_BNode.addBatch();
            }
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
    }


    private synchronized void addToQuadStore_asURI(Resource subject, IRI predicate,
                                                   Value object, Resource... contexts) throws RepositoryException
    {
        verifyIsOpen();

        try {
            for (Resource context : contexts) {
                bindParams(psInsert, subject, predicate, object, context);
                psInsert.addBatch();
            }
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
    }


    private void bindParams(PreparedStatement ps,
                            Resource subject, IRI predicate, Value object, Resource context) throws SQLException, RepositoryException
    {
        int flags = 0;

        if (!insertBNodeAsVirtuosoIRI && (object instanceof BNode))
            flags = 15;

        flags |= (subject instanceof BNode) ?0x0100:0;
        flags |= (object instanceof BNode) ?0x0200:0;

        ps.setString(1, subject.toString());
        ps.setString(2, predicate.toString());

        if (object instanceof Resource)
        {
            ps.setString(3,  object.toString());
            ps.setNull(4, java.sql.Types.VARCHAR);
        }
        else if (object instanceof Literal)
        {
            Literal lit = (Literal) object;
            Optional<String> lang = lit.getLanguage();
            ps.setString(3, lit.getLabel());

            if (lang.isPresent())
            {
                ps.setString(4, lang.get());
                flags |= 2;

            }
            else if (lit.getDatatype() != null)
            {
                IRI ltype = lit.getDatatype();

                if (insertStringLiteralAsSimple && ltype.equals(XMLSchema.STRING)) {
                    ps.setNull(4, java.sql.Types.VARCHAR);
                    flags |= 1;
                } else {
                  ps.setString(4, ltype.toString());

                  if (ltype.equals(XMLSchema.INTEGER))
                    flags |= 5;
                  else if (ltype.equals(XMLSchema.FLOAT))
                    flags |= 6;
                  else if (ltype.equals(XMLSchema.DOUBLE))
                    flags |= 7;
                  else if (ltype.equals(XMLSchema.DECIMAL))
                    flags |= 8;
                  else
                    flags |= 3;
                }
            }
            else
            {
                ps.setNull(4, java.sql.Types.VARCHAR);
                flags |= 1;
            }
        }
        else
        {
            throw new RepositoryException("Unknown value type: " + object.getClass());
        }

        ps.setInt(5, flags);

        ps.setString(6, context.toString());
    }


    private synchronized PreparedStatement addToQuadStore_batch(PreparedStatement ps,
                                                                Resource subject,
                                                                IRI predicate,
                                                                Value object,
                                                                Resource... contexts) throws RepositoryException
    {
        verifyIsOpen();

        try {
            if (ps == null)
                ps = prepareStatement(VirtuosoRepositoryConnection.S_BATCH_INSERT, true);

            for (Resource context : contexts) {
                bindParams(ps, subject, predicate, object, context);
                ps.addBatch();
            }
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
        return ps;
    }



    private synchronized PreparedStatement flushDelayAdd_batch(PreparedStatement ps,
                                                               int psCount) throws RepositoryException
    {
        try {
            if (psCount > 0 && ps!=null) {
                ps.executeBatch();
                ps.clearBatch();
                if (useReprepare) {
                    try{
                        ps.close();
                    } catch(Exception e){}
                    ps = null;
                }
            }
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
        return ps;
    }


    private synchronized PreparedStatement dropDelayAdd_batch(PreparedStatement ps,
                                                              int psCount) throws RepositoryException
    {
        try {
            if (psCount > 0 && ps!=null) {
                ps.clearBatch();
                if (useReprepare) {
                    try{
                        ps.close();
                    } catch(Exception e){}
                    ps = null;
                }
            }
        } catch (Exception e) {
            throw new RepositoryException(e);
        }
        return ps;
    }


    private synchronized void flushDelayAdd() throws RepositoryException
    {
        psInsert = flushDelayAdd_batch(psInsert, psInsertCount);
        psInsertCount = 0;
        if (psInsert_BNode!=null && psInsertBNodeCount > 0)
            try {
                psInsert_BNode.executeBatch();
                psInsert_BNode.clearBatch();
            }
            catch (Exception e) {
                throw new RepositoryException(e);
            }
        psInsertBNodeCount = 0;
    }

    private synchronized void dropDelayAdd() throws RepositoryException
    {
        psInsert = dropDelayAdd_batch(psInsert, psInsertCount);
        psInsertCount = 0;
        if (psInsertBNodeCount > 0 && psInsert_BNode!=null)
            try {
                psInsert_BNode.clearBatch();
            } catch (Exception e) {
                throw new RepositoryException(e);
            }
        psInsertBNodeCount = 0;
    }


    private void append(Object value, StringBuilder sb, boolean inTriplePattern)
            throws RepositoryException
    {
        if (value instanceof Resource) {
            append((Resource)value, sb, inTriplePattern);
        }
        else if (value instanceof Literal) {
            append((Literal)value, sb, inTriplePattern);
        }
        else if (value instanceof String) {
            sb.append((String)value);
        }
        else {
            throw new RepositoryException("Unknown value type: " + value.getClass());
        }
    }

    private void append(Resource resource, StringBuilder sb, boolean inTriplePattern)
            throws RepositoryException
    {
        if (resource instanceof IRI) {
            append((IRI)resource, sb, inTriplePattern);
        }
        else if (resource instanceof BNode) {
            append((BNode)resource, sb, inTriplePattern);
        }
        else {
            throw new RepositoryException("Unknown resource type: " + resource.getClass());
        }
    }

    private void append(IRI uri, StringBuilder sb, boolean inTriplePattern)
            throws RepositoryException
    {
        sb.append("<");
        escapeString(uri.toString(), sb);
        sb.append(">");
    }


    private void append(BNode bNode, StringBuilder sb, boolean inTriplePattern)
            throws RepositoryException
    {
        String bid = bNode.getID();
        if (bid.startsWith("nodeID://")) {
            if (inTriplePattern)
                sb.append("`");

            sb.append("iri('");
            sb.append(bid);
            sb.append("')");

            if (inTriplePattern)
                sb.append("`");
        } else {
            if (insertBNodeAsVirtuosoIRI) {
                sb.append("<");
                sb.append(bNode.toString());
                sb.append(">");
            } else {
                sb.append(bNode.toString());
            }
        }
    }


    private void append(Literal lit, StringBuilder sb, boolean inTriplePattern)
            throws RepositoryException
    {
        sb.append("\"");
        escapeString(lit.getLabel(), sb);
        sb.append("\"");

        if (lit.getDatatype() != null) {
            // Append the literal's datatype
            IRI ltype = lit.getDatatype();
            if (!(insertStringLiteralAsSimple && ltype.equals(XMLSchema.STRING))) {
                sb.append("^^");
                append(ltype, sb, inTriplePattern);
            }
        }
        else if (lit.getLanguage() != null) {
            // Append the literal's language
            sb.append("@");
            sb.append(lit.getLanguage());
        }
    }

    private String BNode2String(BNode bNode)
    {
        String bid = bNode.getID();
        if (bid.startsWith("nodeID://"))
            return bid;
        else
            return bNode.toString();
    }

    private void escapeString(String label, StringBuilder sb)
            throws RepositoryException
    {
        int labelLength = label.length();

        for (int i = 0; i < labelLength; i++) {
            char c = label.charAt(i);
            int cInt = c;

            if (c == '\\') {
                sb.append("\\\\");
            }
            else if (c == '"') {
                sb.append("\\\"");
            }
            else if (c == '\n') {
                sb.append("\\n");
            }
            else if (c == '\r') {
                sb.append("\\r");
            }
            else if (c == '\t') {
                sb.append("\\t");
            }
            else if (
                    cInt >= 0x0 && cInt <= 0x8 ||
                            cInt == 0xB || cInt == 0xC ||
                            cInt >= 0xE && cInt <= 0x1F ||
                            cInt >= 0x7F && cInt <= 0xFFFF)
            {
                sb.append("\\u");
                sb.append(toHexString(cInt, 4));
            }
            else if (cInt >= 0x10000 && cInt <= 0x10FFFF) {
                sb.append("\\U");
                sb.append(toHexString(cInt, 8));
            }
            else {
                sb.append(c);
            }
        }
    }

    private String toHexString(int decimal, int stringLength) {
        StringBuilder sb = new StringBuilder(stringLength);
        String hexVal = Integer.toHexString(decimal).toUpperCase();

        int nofZeros = stringLength - hexVal.length();
        for (int i = 0; i < nofZeros; i++)
            sb.append('0');

        sb.append(hexVal);
        return sb.toString();
    }



    private void clearQuadStore(Resource[] contexts) throws RepositoryException {

        if (contexts!=null && contexts.length > 0)
            try {
                String [] graphs = new String[contexts.length];
                PreparedStatement ps = prepareStatement(S_CLEAR_GRAPH, true);
                for (int i = 0; i < contexts.length; i++)
                    graphs[i] = contexts[i].stringValue();

                Array gArray = quadStoreConnection.createArrayOf ("VARCHAR", graphs);
                ps.setArray (1, gArray);
                ps.executeUpdate ();
                ps.close();
                gArray.free();
            }
            catch (Exception e) {
                throw new RepositoryException(e);
            }
    }


    private CloseableIteration<Statement, RepositoryException> selectFromQuadStore(Resource subject, IRI predicate, Value object, boolean includeInferred, boolean hasOnly, Resource... contexts) throws RepositoryException {
        verifyIsOpen();
        flushDelayAdd();

        ResultSet rs = null;
        StringBuilder query = new StringBuilder("sparql ");

        if (includeInferred && ruleSet != null && ruleSet.length() > 0)
            query.append("define input:inference '"+ruleSet+"' ");

        if (includeInferred && macroLib!=null && macroLib.length() > 0)
            query.append("define input:macro-lib <"+macroLib+">\n ");

        query.append("select * ");

        for (Resource context : contexts) {

            query.append("from named <");
            query.append(context.toString());
            query.append("> ");
        }

        query.append("where { graph ?g {");

        query.append(' ');
        if (subject != null)
            query.append("`iri(??)`");
        else
            query.append("?s");

        query.append(' ');
        if (predicate != null)
            query.append("`iri(??)`");
        else
            query.append("?p");

        query.append(' ');
        if (object != null)
            query.append("`bif:__rdf_long_from_batch_params(??,??,??)`");
        else
            query.append("?o");

        query.append(" }}");
        if (hasOnly)
            query.append(" LIMIT 1");

        PreparedStatement ps;
        try {
            ps = prepareStatement(query.toString(), false);
            int col = 1;

            if (subject != null)
                bindResource(ps, col++, subject);
            if (predicate != null)
                bindURI(ps, col++, predicate);
            if (object != null)
                bindValue(ps, col, object);

            rs = ps.executeQuery();
        }
        catch (Exception e) {
            throw new RepositoryException(getClass().getCanonicalName() + ": SPARQL execute failed." + "\n" + query.toString() + "[" + e + "]", e);
        }

        return new CloseableIterationStmt(ps, rs, subject, predicate, object);
    }



    private void removeData(Map<String,StringBuilder> data) throws RepositoryException
    {
        java.sql.Statement stmt = null;
        try {
            stmt = createStatement(-1, true);
            for(Map.Entry<String,StringBuilder> e : data.entrySet()) {

                StringBuilder sb = new StringBuilder(256);
                sb.append("sparql define output:format '_JAVA_' DELETE FROM <");
                sb.append(e.getKey());
                sb.append("> { ");
                sb.append(e.getValue().toString());
                sb.append(" }");

                stmt.execute(sb.toString());
            }
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
        finally {
            try {
                if (stmt!=null)
                    stmt.close();
            } catch (Exception e) {}
        }
    }


    private void removeContext(Resource subject, IRI predicate, Value object, Resource context) throws RepositoryException
    {
        try {

            if (subject == null && predicate == null && object == null && context != null) {
                String  query = "sparql clear graph iri(??)";

                PreparedStatement ps = prepareStatement(query, true);
                ps.setString(1, context.toString());
                ps.execute();
                ps.close();

            } else if (subject != null && predicate != null && object != null && context != null) {

                PreparedStatement ps = prepareStatement(VirtuosoRepositoryConnection.S_DELETE, true);

                ps.setString(1, context.toString());
                bindResource(ps, 2, subject);
                bindURI(ps, 3, predicate);
                bindValue(ps, 4, object);
                ps.execute();
                ps.close();

            } else {

                if (context == null)
                    throw new RepositoryException("Context can't be NULL");

                StringBuilder stm = new StringBuilder();

                stm.append(' ');
                if (subject != null)
                    stm.append("`iri(??)`");
                else
                    stm.append("?s");

                stm.append(' ');
                if (predicate != null)
                    stm.append("`iri(??)`");
                else
                    stm.append("?p");

                stm.append(' ');
                if (object != null)
                    stm.append("`bif:__rdf_long_from_batch_params(??,??,??)`");
                else
                    stm.append("?o");

                String query = "sparql delete from <"+context+"> { "+
                        stm.toString()+" } where { "+stm.toString()+" }";

                java.sql.PreparedStatement ps = prepareStatement(query, true);
                int col = 1;

                if (subject != null)
                    bindResource(ps, col++, subject);
                if (predicate != null)
                    bindURI(ps, col++, predicate);
                if (object != null) {
                    bindValue(ps, col, object);
                    col +=3;
                }

                if (subject != null)
                    bindResource(ps, col++, subject);
                if (predicate != null)
                    bindURI(ps, col++, predicate);
                if (object != null)
                    bindValue(ps, col, object);

                ps.execute();
                ps.close();
            }
        }
        catch (Exception e) {
            throw new RepositoryException(e);
        }
    }


    // Used for Remove and Select
    private void bindResource(PreparedStatement ps, int col, Resource n) throws SQLException {
        if (n == null)
            return;
        if (n instanceof BNode)
            ps.setString(col, BNode2String((BNode)n));
        else
            ps.setString(col, n.toString());
    }


    private void bindURI(PreparedStatement ps, int col, IRI n) throws SQLException {
        if (n == null)
            return;
        ps.setString(col, n.toString());
    }


    private void bindValue(PreparedStatement ps, int col, Value n) throws SQLException {
        if (n == null)
            return;
        if (n instanceof IRI) {
            ps.setInt(col, 1);
            ps.setString(col+1, n.toString());
            ps.setNull(col+2, java.sql.Types.VARCHAR);
        }
        else if (n instanceof BNode) {
            ps.setInt(col, 1);  // must be 1 for search
            ps.setString(col+1, BNode2String((BNode)n));
            ps.setNull(col+2, java.sql.Types.VARCHAR);
        }
        else if (n instanceof Literal) {
            Literal lit = (Literal) n;
            Optional<String> lang = lit.getLanguage();
            if (lang.isPresent()) {
                ps.setInt(col, 5);
                ps.setString(col+1, lit.getLabel());
                ps.setString(col+2, lang.get());
            }
            else if (lit.getDatatype() != null) {
                IRI ltype = lit.getDatatype();
                if (!(insertStringLiteralAsSimple && ltype.equals(XMLSchema.STRING))) {
                    ps.setInt(col, 4);
                    ps.setString(col+1, lit.getLabel());
                    ps.setString(col+2, ltype.toString());
                } else {
                    ps.setInt(col, 3);
                    ps.setString(col+1, lit.getLabel());
                    ps.setNull(col+2, java.sql.Types.VARCHAR);
                }
            }
            else {
                ps.setInt(col, 3);
                ps.setString(col+1, lit.getLabel());
                ps.setNull(col+2, java.sql.Types.VARCHAR);
            }
        }
        else {
            ps.setInt(col, 3);
            ps.setString(col+1, n.toString());
            ps.setNull(col+2, java.sql.Types.VARCHAR);
        }
    }



    private String stringForValue(Value n, boolean inTriplePattern)  throws RepositoryException {
        StringBuilder sb = new StringBuilder(256);
        append(n, sb, inTriplePattern);
        return sb.toString();
    }


    private Value castValue(Object val) throws RepositoryException {
        if (val == null)
            return null;
        if (val instanceof ExtendedString) {
            ExtendedString ves = (ExtendedString) val;
            String valueString = ves.toString();
            if (ves.getIriType() == ExtendedString.IRI && (ves.getStrType() & 0x01)==0x01) {
                if (valueString.startsWith("_:")) {
                    valueString = valueString.substring(2);
                    return valueFactory.createBNode(valueString);
                }
                try {
                    if (valueString.indexOf(':') < 0)
                        return valueFactory.createIRI(":" + valueString);
                    else
                        return valueFactory.createIRI(valueString);
                }
                catch (IllegalArgumentException iaex) {
                    throw new RepositoryException("VirtuosoRepositoryConnection().castValue() Invalid value from Virtuoso: \"" + valueString + "\"", iaex);
                }
            }
            else if (ves.getIriType() == ExtendedString.BNODE) {
                try {
                    return valueFactory.createBNode(valueString);
                }
                catch (IllegalArgumentException iaex) {
                    throw new RepositoryException("VirtuosoRepositoryConnection().castValue() Invalid value from Virtuoso: \"" + valueString + "\"", iaex);
                }
            }
            else {
                try {
                    return valueFactory.createLiteral(valueString);
                }
                catch (IllegalArgumentException iaex) {
                    throw new RepositoryException("VirtuosoRepositoryConnection().castValue() Invalid value from Virtuoso: \"" + valueString + "\", STRTYPE = " + ves.getIriType(), iaex);
                }
            }
        }
        else if (val instanceof RdfBox) {
            RdfBox rb = (RdfBox) val;
            String rb_val = rb.toString();

            if (rb.getLang() != null) {
                return valueFactory.createLiteral(rb_val, rb.getLang());
            }
            else if (rb.getType() != null) {
                String rb_type = rb.getType();
                if (rb_val.length()==1 && (rb_val.charAt(0)=='1' || rb_val.charAt(0)=='0')) {
                    if (rb_type.equals("http://www.w3.org/2001/XMLSchema#boolean"))
                        return valueFactory.createLiteral(rb_val.charAt(0)=='1'?true:false); //  return getRepository().getValueFactory().createLiteral(rb_val.charAt(0)=='1'?"true":"false", this.getRepository().getValueFactory().createURI(rb_type));
                }
                return valueFactory.createLiteral(rb_val, valueFactory.createIRI(rb_type));
            }
            else {
                return getRepository().getValueFactory().createLiteral(rb_val);
            }
        }
        else if (val instanceof java.lang.Long) {
            return valueFactory.createLiteral(((Long) val).longValue());
        }
        else if (val instanceof java.lang.Integer) {
            return valueFactory.createLiteral(((Integer) val).intValue());
        }
        else if (val instanceof java.lang.Short) {
            return valueFactory.createLiteral(((Short) val).intValue());
        }
        else if (val instanceof java.lang.Float) {
            return valueFactory.createLiteral(((Float) val).floatValue());
        }
        else if (val instanceof java.lang.Double) {
            return valueFactory.createLiteral(((Double) val).doubleValue());
        }
        else if (val instanceof java.math.BigDecimal) {
            IRI type = valueFactory.createIRI("http://www.w3.org/2001/XMLSchema#decimal");
            return valueFactory.createLiteral(val.toString(), type);
        }
        else if (val instanceof java.sql.Blob) {
            IRI type = valueFactory.createIRI("http://www.w3.org/2001/XMLSchema#hexBinary");
            return valueFactory.createLiteral(val.toString(), type);
        }
        else if (val instanceof VirtuosoDate) {
            IRI type = valueFactory.createIRI("http://www.w3.org/2001/XMLSchema#date");
            return valueFactory.createLiteral(((VirtuosoDate)val).toXSD_String(), type);
        }
        else if (val instanceof VirtuosoTimestamp) {
            IRI type = valueFactory.createIRI("http://www.w3.org/2001/XMLSchema#dateTime");
            return valueFactory.createLiteral(((VirtuosoTimestamp)val).toXSD_String(), type);
        }
        else if (val instanceof VirtuosoTime) {
            IRI type = valueFactory.createIRI("http://www.w3.org/2001/XMLSchema#time");
            return valueFactory.createLiteral(((VirtuosoTime)val).toXSD_String(), type);
        }
        else if (val instanceof java.sql.Date) {
            IRI type = valueFactory.createIRI("http://www.w3.org/2001/XMLSchema#date");
            return valueFactory.createLiteral(val.toString(), type);
        }
        else if (val instanceof java.sql.Timestamp) {
            IRI type = valueFactory.createIRI("http://www.w3.org/2001/XMLSchema#dateTime");
            return valueFactory.createLiteral(Timestamp2String((java.sql.Timestamp)val), type);
        }
        else if (val instanceof java.sql.Time) {
            IRI type = valueFactory.createIRI("http://www.w3.org/2001/XMLSchema#time");
            return valueFactory.createLiteral(val.toString(), type);
        }
        else { // if(val instanceof String) {
            try {
                return getRepository().getValueFactory().createLiteral(val.toString());
            }
            catch (IllegalArgumentException iaex2) {
                throw new RepositoryException("VirtuosoRepositoryConnection().castValue() Could not parse resource: " + val, iaex2);
            }
        }
    }


    /**
     * Creates a RepositoryResult for the supplied element set.
     */
    protected <E> RepositoryResult<E> createRepositoryResult(Iterable<? extends E> elements) {
        return new RepositoryResult<E>(new CloseableIteratorIteration<E, RepositoryException>(elements.iterator()));
    }


    private void verifyIsOpen() throws RepositoryException {
        try {
            if (this.getQuadStoreConnection().isClosed())
                throw new IllegalStateException("Connection has been closed");
        }
        catch (SQLException e) {
            throw new RepositoryException(e);
        }
    }


    protected void verifyNotTxnActive(String msg)
            throws RepositoryException
    {
        if (!isAutoCommit()) {
            throw new RepositoryException(msg);
        }
    }

    /**
     protected void verifyTxnActive()
     throws StoreException
     {
     if (isAutoCommit()) {
     throw new RepositoryException("Connection does not have an active transaction");
     }
     }
     **/

    public abstract class CloseableIterationBase<E, X extends Exception> implements CloseableIteration<E, X>
    {
        E	  v_row;
        boolean	  v_finished = false;
        boolean	  v_prefetched = false;
        Resource  subject;
        IRI       predicate;
        Value 	  object;
        ResultSet v_rs;
        java.sql.Statement v_stmt;

        public CloseableIterationBase(java.sql.Statement stmt, ResultSet rs, Resource subject, IRI predicate, Value object)
        {
            v_stmt = stmt;
            v_rs = rs;
            this.subject = subject;
            this.predicate = predicate;
            this.object = object;
        }


        protected abstract X createException(Exception e);

        public boolean hasNext() throws X
        {
            if (!v_finished && !v_prefetched)
                moveForward();
            return !v_finished;
        }

        public E next() throws X
        {
            if (!v_finished && !v_prefetched)
                moveForward();

            v_prefetched = false;

            if (v_finished)
                throw new NoSuchElementException();

            return v_row;
        }

        public void remove() throws X
        {
            throw new UnsupportedOperationException();
        }

        public void close() throws X
        {
            if (!v_finished)
            {
                try
                {
                    v_rs.close();
                    v_stmt.close();
                }
                catch (SQLException e)
                {
                    throw createException(e);
                }
            }
            v_finished = true;
        }

        protected void finalize() throws Throwable
        {
            super.finalize();
            if (!v_finished)
                try {
                    close();
                } catch (Exception e) {}
        }

        protected void moveForward() throws X
        {
            try
            {
                if (!v_finished && v_rs.next())
                {
                    extractRow();
                    v_prefetched = true;
                }
                else
                    close();
            }
            catch (Exception e)
            {
                throw createException(e);
            }
        }

        protected abstract void extractRow() throws Exception;
    }


    public class CloseableIterationStmt extends CloseableIterationBase<Statement, RepositoryException> {

        int col_g = -1;
        int col_s = -1;
        int col_p = -1;
        int col_o = -1;

        public CloseableIterationStmt(java.sql.Statement stmt, ResultSet rs, Resource subject, IRI predicate, Value object) throws RepositoryException
        {
            super(stmt, rs, subject, predicate, object);
            try {
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String label = rsmd.getColumnName(i);
                    if (label.equalsIgnoreCase("g"))
                        col_g = i;
                    else if (label.equalsIgnoreCase("s"))
                        col_s = i;
                    else if (label.equalsIgnoreCase("p"))
                        col_p = i;
                    else if (label.equalsIgnoreCase("o"))
                        col_o = i;
                }
            } catch (Exception e) {
                throw createException(e);
            }
        }

        protected RepositoryException createException(Exception e) {
            return new RepositoryException(e);
        }

        protected void extractRow() throws Exception
        {
            Resource _graph = null;
            Resource _subject = subject;
            IRI _predicate = predicate;
            Value _object = object;
            Object val = null;

            try {
                if (col_g != -1) {
                    val = v_rs.getObject(col_g);
                    _graph = (Resource) castValue(val);
                }
            }
            catch (ClassCastException ccex) {
                throw new RepositoryException("Unexpected resource type encountered. Was expecting Resource: " + val, ccex);
            }

            if (_subject == null && col_s != -1)
                try {
                    val = v_rs.getObject(col_s);
                    _subject = (Resource) castValue(val);
                }
                catch (ClassCastException ccex) {
                    throw new RepositoryException("Unexpected resource type encountered. Was expecting Resource: " + val, ccex);
                }

            if (_predicate == null && col_p != -1)
                try {
                    val = v_rs.getObject(col_p);
                    _predicate = (IRI) castValue(val);
                }
                catch (ClassCastException ccex) {
                    throw new RepositoryException("Unexpected resource type encountered. Was expecting URI: " + val, ccex);
                }

            if (_object == null && col_o != -1)
                _object = castValue(v_rs.getObject(col_o));

            v_row = valueFactory.createStatement(_subject,_predicate,_object,_graph);
        }
    }



    public class CloseableIterationBindingSet extends CloseableIterationBase<BindingSet, QueryEvaluationException> {

        ResultSetMetaData rsmd;

        public CloseableIterationBindingSet(java.sql.Statement stmt, ResultSet rs) throws QueryEvaluationException
        {
            super(stmt, rs, null, null, null);
            try {
                rsmd = rs.getMetaData();
            } catch (Exception e) {
                throw createException(e);
            }
        }

        protected QueryEvaluationException createException(Exception e) {
            return new QueryEvaluationException(e);
        }

        protected void extractRow() throws Exception
        {
            v_row = new QueryBindingSet();
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String col = rsmd.getColumnName(i);
                Object val = v_rs.getObject(i);
                if (val!=null) {
                    Value v = castValue(val);
                    ((QueryBindingSet)v_row).setBinding(col, v);
                }
            }
        }
    }


    public class CloseableIterationGraphResult extends CloseableIterationBase<Statement, QueryEvaluationException> {

        int col_g = -1;
        int col_s = -1;
        int col_p = -1;
        int col_o = -1;

        public CloseableIterationGraphResult(java.sql.Statement stmt, ResultSet rs) throws QueryEvaluationException
        {
            super(stmt, rs, null, null, null);

            try {
                ResultSetMetaData rsmd = rs.getMetaData();

                // begin at onset one
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String label = rsmd.getColumnName(i);
                    if (label.equalsIgnoreCase("G"))
                        col_g = i;
                    else if (label.equalsIgnoreCase("S"))
                        col_s = i;
                    else if (label.equalsIgnoreCase("P"))
                        col_p = i;
                    else if (label.equalsIgnoreCase("O"))
                        col_o = i;
                }
            } catch (Exception e) {
                throw createException(e);
            }
        }

        protected QueryEvaluationException createException(Exception e) {
            return new QueryEvaluationException(e);
        }

        protected void extractRow() throws Exception
        {
            Resource sval = null;
            IRI pval = null;
            Value oval = null;
            Resource gval = null;

            if (col_s != -1)
                sval = (Resource) castValue(v_rs.getObject(col_s));

            if (col_p != -1)
                pval = (IRI) castValue(v_rs.getObject(col_p));

            if (col_o != -1)
                oval = castValue(v_rs.getObject(col_o));

            if (col_g != -1)
                gval = (Resource) castValue(v_rs.getObject(col_g));

            v_row = valueFactory.createStatement(sval,pval,oval,gval);
        }
    }


    private String Timestamp2String(java.sql.Timestamp v)
    {
        GregorianCalendar cal = new GregorianCalendar();
        int timezone = cal.get(Calendar.ZONE_OFFSET)/60000; //min

        StringBuilder sb = new StringBuilder();
        DateFormat formatter= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String nanosString;
        String timeZoneString = null;
        String zeros = "000000000";
        int nanos = v.getNanos();

        sb.append(formatter.format(v));

        if (nanos == 0) {
//            nanosString = "000";
            nanosString = "";
        } else {
            nanosString = Integer.toString(nanos);

            // Add leading zeros
            nanosString = zeros.substring(0, (9-nanosString.length())) +
                    nanosString;

            // Truncate trailing zeros
            char[] nanosChar = new char[nanosString.length()];
            nanosString.getChars(0, nanosString.length(), nanosChar, 0);
            int truncIndex = 8;
            while (nanosChar[truncIndex] == '0') {
                truncIndex--;
            }

            nanosString = new String(nanosChar, 0, truncIndex + 1);
        }

        if (nanosString.length()>0) {
            sb.append(".");
            sb.append(nanosString);
        }

        sb.append(timezone>0?'+':'-');

        int tz = Math.abs(timezone);
        int tzh = tz/60;
        int tzm = tz%60;

        if (tzh < 10)
            sb.append('0');

        sb.append(tzh);
        sb.append(':');

        if (tzm < 10)
            sb.append('0');

        sb.append(tzm);
        return sb.toString();
    }



}