File: VirtuosoConnection.java

package info (click to toggle)
virtuoso-opensource 6.1.6%2Bdfsg2-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 260,060 kB
  • ctags: 123,765
  • sloc: ansic: 652,532; sql: 458,419; xml: 282,834; java: 61,031; sh: 40,031; cpp: 36,890; cs: 25,240; php: 12,692; yacc: 9,523; lex: 7,018; makefile: 6,157; jsp: 4,484; awk: 1,643; perl: 1,013; ruby: 1,003; python: 326
file content (2362 lines) | stat: -rw-r--r-- 82,325 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
/*
 *  $Id$
 *
 *  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
 *  project.
 *
 *  Copyright (C) 1998-2012 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.jdbc2;

import java.sql.*;
import java.net.*;
import java.io.*;
import java.util.*;
#ifdef SSL
#undef sun
import java.security.*;
import java.security.cert.*;
import javax.net.ssl.*;
#if JDK_VER < 14
import com.sun.net.ssl.*;
#endif
#endif
import openlink.util.*;
import java.util.Vector;
#if JDK_VER >= 16
import openlink.util.OPLHeapNClob;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
#endif

/**
 * The VirtuosoConnection class is an implementation of the Connection interface
 * in the JDBC API which represents a database connection. A connection to the
 * Virtuoso DBMS can be made with :
 * <pre>
 *   <code>Connection connection = DriverManager.getConnection(url,username,userpassword)</code>
 * </pre>
 * , in the case you use a URL like <code>jdbc:virtuoso://<i>host</i>:<i>port</i></code> or
 * <pre>
 *   <code>Connection connection = DriverManager.getConnection(url)</code>
 * </pre>
 * , in the case you use a URL like
 * <code>jdbc:virtuoso://<i>host</i>:<i>port</i>/UID=<i>username</i>/PWD=<i>userpassword</i></code>
 *
 * @version 1.0 (JDBC API 2.0 implementation)
 * @see java.sql.Connection
 * @see java.sql.DriverManager#getConnection
 * @see virtuoso.jdbc2.VirtuosoStatement
 * @see virtuoso.jdbc2.VirtuosoPreparedStatement
 * @see virtuoso.jdbc2.VirtuosoCallableStatement
 * @see virtuoso.jdbc2.VirtuosoDatabaseMetaData
 */
public class VirtuosoConnection implements Connection
{
   // Buffered TCP socket stream
   private Socket socket;

   private VirtuosoInputStream in;

   private VirtuosoOutputStream out;

   // Hash table from future id to the VirtuosoFuture instance
#if JDK_VER >= 16
   private Hashtable<Integer,VirtuosoFuture> futures;
#else
   private Hashtable futures;
#endif

   // Serial number of last issued future, 0 is first
   private int req_no, con_no;
   private static int global_con_no = 0;

   // String sent by server as answer to "SCON" RPC
   protected String qualifier;
   private String version;
   private int _case;
   protected openlink.util.Vector client_defaults;
   protected openlink.util.Vector client_charset;
#if JDK_VER >= 16
   protected Hashtable<Character,Byte> client_charset_hash;
#else
   protected Hashtable client_charset_hash;
#endif
   protected SQLWarning warning = null;

   // String sent by server as answer to "caller_identification" RPC
   private String peer_name;

   // Flag which represent if transactions are in auto-commit mode
   private boolean auto_commit = true;

   // Flag is set if the connection participates in a global transaction.
   private boolean global_transaction = false;

   // The url of the database which the connection is associated
   private String url;

   // The login used to connect to the database.
   private String user, password, pwdclear;

#ifdef SSL
   // The SSL parameters
   private String keystore_pass, keystore_cert, keystore_path;
   private String ssl_provider;
#endif

   // The transaction isolation
   private int trxisolation = Connection.TRANSACTION_REPEATABLE_READ;

   // The read mode
   private boolean readOnly = false;

   // The timeout for I/O
   protected int timeout_def = 60;
   protected int timeout = 0;
   protected int txn_timeout = 0;

   protected int fbs = VirtuosoTypes.DEFAULTPREFETCH;

   // utf8_encoding for statements
   protected boolean utf8_execs = false;

   // set if the connection is managed through VirtuosoPooledConnection;
#if JDK_VER >= 14
   protected VirtuosoPooledConnection pooled_connection = null;
   protected VirtuosoXAConnection xa_connection = null;
#endif

   protected String charset;
   protected boolean charset_utf8 = false;


   
#if JDK_VER >= 16
   protected Hashtable<Integer,String> rdf_type_hash = null;
   protected Hashtable<Integer,String> rdf_lang_hash = null;
   protected Hashtable<String,Integer> rdf_type_rev = null;
   protected Hashtable<String,Integer> rdf_lang_rev = null;

  private LRUCache<String,VirtuosoPreparedStatement> pStatementCache;
  private boolean  useCachePrepStatements = false;
  private Vector<VhostRec> hostList = new Vector<VhostRec>();
#else
   protected Hashtable rdf_type_hash = null;
   protected Hashtable rdf_lang_hash = null;
   protected Hashtable rdf_type_rev = null;
   protected Hashtable rdf_lang_rev = null;

  private Vector hostList = new Vector();
#endif
   protected boolean rdf_type_loaded = false;
   protected boolean rdf_lang_loaded = false;

  private boolean useRoundRobin;
  // The pingStatement to know if the connection is still available
  private PreparedStatement pingStatement = null;


   protected class VhostRec
   {
     protected String host;
     protected int port;

     protected VhostRec(String _host, String _port)  throws VirtuosoException
     {
       host = _host;
       try {
         port = Integer.parseInt(_port);
       } catch(NumberFormatException e) {
         throw new VirtuosoException("Wrong port number : " + e.getMessage(),VirtuosoException.BADFORMAT);
       }
     }

     protected VhostRec(String _host, int _port)  throws VirtuosoException
     {
       host = _host;
       port = _port;
     }
   }


#if JDK_VER >= 16
   protected Vector<VhostRec> parse_vhost(String vhost, String _host, int _port) throws VirtuosoException
   {
     Vector<VhostRec> hostlist =  new Vector<VhostRec>();
#else
   protected Vector parse_vhost(String vhost, String _host, int _port) throws VirtuosoException
   {
     Vector hostlist =  new Vector();
#endif

     String port = Integer.toString(_port);
     String attr = null;
     StringBuffer buff = new StringBuffer();

     for (int i = 0; i < vhost.length(); i++) {
       char c = vhost.charAt(i);

       switch (c) {
         case ',':
           String val = buff.toString().trim();
           if (attr == null) {
             attr = val;
             val  = port;
           }
	   if (attr != null && attr.length() > 0)
              hostlist.add(new VhostRec(attr, val));
	   attr = null;
	   buff.setLength(0);
	   break;
         case ':':
	   attr = buff.toString().trim();
	   buff.setLength(0);
	   break;
         default:
	   buff.append(c);
	   break;
       }
     }

     String val = buff.toString().trim();
     if (attr == null) {
       attr = val;
       val  = port;
     }
     if (attr != null && attr.length() > 0) {
       hostlist.add(new VhostRec(attr, val));
     }

     if (hostlist.size() == 0)
       hostlist.add(new VhostRec(_host, _port));

     return hostlist;
   }


   private synchronized int getNextRoundRobinHostIndex()
   {
     int indexRange = hostList.size();
     return (int)(Math.random() * indexRange);
   }


   /**
    * Constructs a new connection to Virtuoso database and makes the
    * connection.
    *
    * @param url	The JDBC URL for the connection.
    * @param host	The name of the host on which the database resides.
    * @param port The port number on which Virtuoso is listening.
    * @param prop The properties to use for making the connection (user, password).
    * @exception	virtuoso.jdbc2.VirtuosoException	An error occurred during the
    * connection.
    */
   VirtuosoConnection(String url, String host, int port, Properties prop) throws VirtuosoException
   {
      int sendbs = 32768;
      int recvbs = 32768;

      hostList = parse_vhost(prop.getProperty("_vhost", ""), host, port);

      // Set some variables
      this.req_no = 0;
      this.url = url;
      this.con_no = global_con_no++;
      // Check properties
      if (prop.get("charset") != null)
      {
	charset = (String)prop.get("charset");
	//System.out.println ("VirtuosoConnection " + charset);
	if (charset.indexOf("UTF-8") != -1) // special case all will go as UTF-8
	{
	    this.charset = null;
	    this.charset_utf8 = true;
	    //utf8_execs = true;
	}
      }
      user = (String)prop.get("user");
      if(user == null || user.equals(""))
         user = "anonymous";
      password = (String)prop.get("password");
      if (password == null)
         password = "";
      if (prop.get("timeout") != null)
	 timeout = Integer.parseInt(prop.getProperty("timeout"));
      pwdclear = (String)prop.get("pwdclear");
      if(prop.get("sendbs") != null)
	  sendbs = Integer.parseInt(prop.getProperty("sendbs"));
      if (sendbs <= 0)
          sendbs = 32768;
      if(prop.get("recvbs") != null)
          recvbs = Integer.parseInt(prop.getProperty("recvbs"));
      if (recvbs <= 0)
          recvbs = 32768;
      if (prop.get("fbs") != null)
          fbs = Integer.parseInt(prop.getProperty("fbs"));
      if (fbs <= 0)
          fbs = VirtuosoTypes.DEFAULTPREFETCH;;
      //System.err.println ("3PwdClear is " + pwdclear);
#ifdef SSL
      keystore_cert = (String)prop.get("certificate");
      keystore_pass = (String)prop.get("keystorepass");
      keystore_path = (String)prop.get("keystorepath");
      ssl_provider = (String)prop.get("provider");
#endif
      if(pwdclear == null)
         pwdclear = "0";
      //System.err.println ("4PwdClear is " + pwdclear);
      // Create the hash table
#if JDK_VER >= 16
      futures = new Hashtable<Integer,VirtuosoFuture>();
      // RDF box type & lang
      rdf_type_hash = new Hashtable<Integer,String> ();
      rdf_lang_hash = new Hashtable<Integer,String> ();
      rdf_type_rev = new Hashtable<String,Integer> ();
      rdf_lang_rev = new Hashtable<String,Integer> ();
#else
      futures = new Hashtable();
      // RDF box type & lang
      rdf_type_hash = new Hashtable ();
      rdf_lang_hash = new Hashtable ();
      rdf_type_rev = new Hashtable ();
      rdf_lang_rev = new Hashtable ();
#endif

#if JDK_VER >= 16
      useCachePrepStatements = getBoolAttr(prop, "usepstmtpool", false);
      int poolSize = getIntAttr(prop, "pstmtpoolsize", 25);
      createCaches(poolSize);
#endif

      useRoundRobin = getBoolAttr(prop, "roundrobin", false);
      if (hostList.size() <= 1)
        useRoundRobin = false;

      // Connect to the database
      connect(host,port,(String)prop.get("database"), sendbs, recvbs, (prop.get("log_enable") != null ? (Integer.parseInt(prop.getProperty("log_enable"))) : -1));

      pingStatement = prepareStatement("select 1");
   }

   public boolean isConnectionLost() 
   {
     try{
	pingStatement.setQueryTimeout(1);
        pingStatement.execute();
        return false;
     } catch (Exception e ) {
        return true;
     } 
   }

   protected int getIntAttr(java.util.Properties info, String key, int def)
   {
     int ret = def;
     String val = info.getProperty(key);

     try {
	if (val != null && val.length() > 0)
	  ret = Integer.parseInt(val);
     } catch (NumberFormatException e) {
	ret = def;
     }
     return ret;
   }

   protected boolean getBoolAttr(java.util.Properties info, String key, boolean def)
   {
     boolean ret = def;

     String val = info.getProperty(key);
     if (val != null && val.length() > 0) {
       char c = val.charAt(0);
       return (c == 'Y' || c == 'y' || c == '1');
     } else {
       return def;
     }
   }

   /**
    * Connect to the Virtuoso database and set streams.
    *
    * @param host	The name of the host on which the database resides.
    * @param port 	The port number on which Virtuoso is listening.
    * @param database 	The database to connect to.
    * @exception	virtuoso.jdbc2.VirtuosoException	An error occurred during the
    * connection.
    */
   private void connect(String host, int port,String db, int sendbs, int recvbs, int log_enable) throws VirtuosoException
   {
      // Connect to the database
      int hostIndex = 0;
      int startIndex = 0;

      if (hostList.size() > 1 && useRoundRobin)
        startIndex = hostIndex = getNextRoundRobinHostIndex();

      while(true)
      {
        try {
          if (hostList.size() == 0) {
            connect(host, port, sendbs, recvbs);
          } else {
            VhostRec v = (VhostRec)hostList.elementAt(hostIndex);
            connect(v.host, v.port, sendbs, recvbs);
          }
          break;
        } catch (VirtuosoException e) {

          if (e.getErrorCode() != VirtuosoException.IOERROR)
            throw e;

          hostIndex++;

          if (useRoundRobin) {
            if (hostList.size() == hostIndex)
              hostIndex = 0;

            if (hostIndex == startIndex)
              throw e;
          }
          else if (hostList.size() == hostIndex) { /* Failover mode last rec*/
            throw e;
          }
        }
      }

      // Set database with statement
      if(db!=null) new VirtuosoStatement(this).executeQuery("use "+db);
      //System.out.println  ("log enable="+log_enable);
      if (log_enable >= 0 && log_enable <= 3)
        new VirtuosoStatement(this).executeQuery("log_enable ("+log_enable+")");
   }


   private long cdef_param (openlink.util.Vector cdefs, String name, long deflt)
     {
       int len = cdefs != null ? cdefs.size() : 0;
       int inx;
       //System.err.println ("cdef_param: Searching " + name + " in " + cdefs.toString());
       for (inx = 0; inx < len; inx += 2)
	 if (name.equals ((String) cdefs.elementAt (inx)))
	   {
	     //System.err.println ("cdef_param: Found value=" + ((Number)cdefs.elementAt (inx + 1)).longValue());
	     return (((Number)cdefs.elementAt (inx + 1)).longValue());
	   }
       //System.err.println ("cdef_param: NOT Found default=" + deflt);
       return deflt;
     }

   /**
    * Connect to the Virtuoso database and set streams.
    *
    * @param host	The name of the host on which the database resides.
    * @param port 	The port number on which Virtuoso is listening.
    * @exception	virtuoso.jdbc2.VirtuosoException	An error occurred during the
    * connection.
    */
  private void connect(String host, int port, int sendbs, int recvbs) throws VirtuosoException
   {
      try
      {
         // Establish the connection
#ifdef SSL
	if(keystore_cert != null)
	  {
	    //System.out.println ("Will do SSL");
	    if(ssl_provider != null && ssl_provider.length() != 0)
	      {
		//System.out.println ("SSL Provider " + ssl_provider);
		Security.addProvider((Provider)(Class.forName(ssl_provider).newInstance()));
	      }
	    else
	      java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
	    if(keystore_cert.length() == 0)
	      {
		/* Connection without authentication  */
		//System.setProperty ("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
		/*javax.net.ssl.SSLSocketFactory sf =
		    (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();*/
		/*javax.net.ssl.SSLSocket sock = null;*/
		//System.out.println ("init(): Creating derived X509TrustManager");

		X509TrustManager tm = new MyX509TrustManager();
		KeyManager []km = null;
		TrustManager []tma = {
		  tm
		};

		//System.out.println ("init(): Calling SSLContext.getInstance");
		SSLContext sc = SSLContext.getInstance("TLS");
		//System.out.println ("init(): Calling sc.init");
		sc.init(km,tma,new java.security.SecureRandom());
		//System.out.println ("init(): Calling sc.getSocketFactory");
		SSLSocketFactory sf1 = sc.getSocketFactory();
		//System.out.println ("No auth conn");
		socket = sf1.createSocket(host, port);
		//System.out.println ("after create sock");
	      }
	    else
	      {
		//System.out.println ("Auth conn" + keystore_cert);
		/* Connection with authentication  */
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		SSLContext ssl_ctx = SSLContext.getInstance("TLS");
		KeyStore ks = KeyStore.getInstance("JKS");

		ks.load(new FileInputStream((keystore_path!=null) ? keystore_path : System.getProperty("user.home") + System.getProperty("file.separator") + ".keystore"),
		    (keystore_pass!= null) ? keystore_pass.toCharArray() : new String("").toCharArray());
		kmf.init(ks, (keystore_pass!= null) ? keystore_pass.toCharArray() : new String("").toCharArray());
		ssl_ctx.init(kmf.getKeyManagers(), null, null);

		socket = ((SSLSocketFactory)ssl_ctx.getSocketFactory()).createSocket(host, port);
	      }
	    /* Begin the handshake client/server  */
	    ((SSLSocket)socket).startHandshake();
	  }
	else
#endif
	 socket = new Socket(host,port);

	 if (timeout > 0)
	   socket.setSoTimeout(timeout*1000);
	 socket.setTcpNoDelay(true);
#if JDK_VER >= 12
         socket.setReceiveBufferSize(recvbs);
         socket.setSendBufferSize(sendbs);
#endif

         // Get streams corresponding to the socket
         in = new VirtuosoInputStream(this,socket, recvbs);
	 out = new VirtuosoOutputStream(this,socket, sendbs);
         // RPC caller identification
	 synchronized (this)
	   {
	     Object [] caller_id_args = new Object[1];
	     caller_id_args[0] = null;
	     VirtuosoFuture future = getFuture(VirtuosoFuture.callerid,caller_id_args, timeout);
	     openlink.util.Vector result_future = (openlink.util.Vector)future.nextResult().firstElement();
	     peer_name = (String)(result_future.elementAt(1));

	     if (result_future.size() > 2)
	       {
		 openlink.util.Vector caller_id_opts = (openlink.util.Vector)result_future.elementAt(2);
		 //System.err.println ("caller_id_opts is " + caller_id_opts.toString());
		 int pwd_clear_code = (int) cdef_param (caller_id_opts, "SQL_ENCRYPTION_ON_PASSWORD", -1);
		 switch (pwd_clear_code)
		   {
		     case 1: pwdclear = "cleartext"; break;
		     case 2: pwdclear = "encrypt"; break;
		     case 0: pwdclear = "digest"; break;
		   }
	       }
	     // Remove the future reference
	     removeFuture(future);
	     // RPC login
	     Object[] args = new Object[3];
	     args[0] = user;
	     //System.err.println ("5PwdClear is " + pwdclear);
	     if (pwdclear != null && pwdclear.equals ("cleartext"))
	       {
		 //System.err.println ("1");
		 args[1] = password;
	       }
	     else if (pwdclear != null && pwdclear.equals ("encrypt"))
	       {
		 //System.err.println ("2");
		 args[1] = MD5.pwd_magic_encrypt (user, password);
	       }
	     else
	       {
		 //System.err.println ("def");
		 args[1] = MD5.md5_digest (user, password, peer_name);
	       }
	     //System.err.println ("pass is " + args[1]);


	     args[2] = VirtuosoTypes.version;
	     future = getFuture(VirtuosoFuture.scon,args, this.timeout);
	     result_future = (openlink.util.Vector)future.nextResult();
	     // Check if it's a login answer
	     if(!(result_future.firstElement() instanceof Short))
	       {
		 result_future = (openlink.util.Vector)result_future.firstElement();
		 switch(((Number)result_future.firstElement()).shortValue())
		   {
		     case VirtuosoTypes.QA_LOGIN:
			 // Set some values
			 qualifier = (String)result_future.elementAt(1);
			 version = (String)result_future.elementAt(2);
                         int con_db_gen = Integer.parseInt (version.substring(6));
                         if (con_db_gen < 2303)
	                   {
			     throw new VirtuosoException (
			       "Old server version", VirtuosoException.MISCERROR);
	                   }

			 _case = ((Number)result_future.elementAt(3)).intValue();
			 if (result_future.size() > 3)
			   client_defaults = (openlink.util.Vector)(result_future.elementAt (4));
			 else
			   client_defaults = null;
			 Object obj = null;
			 if (result_future.size() > 4)
			   obj = result_future.elementAt (5);
			 if (obj instanceof openlink.util.Vector)
			   {
			     client_charset = (openlink.util.Vector)obj;
			     String table = (String)client_charset.elementAt (1);
#if JDK_VER >= 16
			     client_charset_hash = new Hashtable<Character,Byte> (256);
#else
			     client_charset_hash = new Hashtable (256);
#endif
			     for (int i = 0; i < 255; i++)
			       {
				 if (i < table.length())
				   {
				     //System.err.println ("Mapping1 " + ((int)table.charAt(i)) + "=" + (i + 1));
				     client_charset_hash.put (
					 new Character (table.charAt(i)),
					 new Byte ((byte) (i + 1)));
				   }
				 else
				   {
				     //System.err.println ("Mapping2 " + (i + 1) + "=" + (i + 1));
				     client_charset_hash.put (
					 new Character ((char) (i + 1)),
					 new Byte ((byte) (i + 1)));
				   }
			       }
			   }
			 else
			   client_charset = null;
			 //System.err.println ("LOGIN RPC:");
			 //System.err.println ("qualifier: " + qualifier);
			 //System.err.println ("version: " + version);
			 //System.err.println ("case: " + _case);
			 //System.err.print ("client_defaults: ");
			 //System.err.println (client_defaults.toString());
			 //System.err.print ("client_charset: ");
			 //if (client_charset != null)
			 //  System.err.println (client_charset.elementAt(0).toString());
			 //else
			 //  System.err.println ("<NULL>");

			 if (timeout <= 0) {
			   timeout = (int) (cdef_param (client_defaults, "SQL_QUERY_TIMEOUT", timeout_def * 1000) / 1000);
			   //System.err.println ("timeout = " + timeout);
			 }
                         if (timeout > 0)
			   socket.setSoTimeout(timeout*1000);

			 if (txn_timeout <= 0) {
			   txn_timeout = (int) (cdef_param (client_defaults, "SQL_TXN_TIMEOUT", txn_timeout * 1000)/ 1000);
			   //System.err.println ("txn timeout = " + txn_timeout);
			 }

			 if (trxisolation <= 0) {
			   trxisolation = (int) cdef_param (client_defaults, "SQL_TXN_ISOLATION", trxisolation);
			   //System.err.println ("txn isolation = " + trxisolation);
			 }

			 utf8_execs = cdef_param (client_defaults, "SQL_UTF8_EXECS", 0) != 0;
			 //System.err.println ("utf8_execs = " + utf8_execs);
			 if (!utf8_execs && cdef_param (client_defaults, "SQL_NO_CHAR_C_ESCAPE", 0) != 0)
			   throw new VirtuosoException (
			       "Not using UTF-8 encoding of SQL statements, " +
			       "but processing character escapes also disabled",
			       VirtuosoException.MISCERROR);
			 //System.err.println ("version=[" + version + " ver=" + version.substring (6, 10));
			 //if ((new Integer (version.substring (6, 10))).intValue() > 2143)
			 //  utf8_execs = true;

			 break;
		     case VirtuosoTypes.QA_ERROR:
			 // Remove the future reference
			 removeFuture(future);
			 // Throw an exception
			 throw new VirtuosoException((String)result_future.elementAt(1) + " " + (String)result_future.elementAt(2),VirtuosoException.NOLICENCE);
		     default:
			 // Remove the future reference
			 removeFuture(future);
			 // Throw an exception
			 throw new VirtuosoException(result_future.toString(),VirtuosoException.UNKNOWN);
		   }
		 ;
	       }
	     else
	       {
		 // Remove the future reference
		 removeFuture(future);
		 throw new VirtuosoException("Bad login.",VirtuosoException.BADLOGIN);
	       }
	     // Remove the future reference
	     removeFuture(future);
	   }
      }
      catch(NoClassDefFoundError e)
      {
         throw new VirtuosoException("Class not found: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
      catch(IOException e)
      {
         throw new VirtuosoException("Connection failed: " + e.getMessage(),VirtuosoException.IOERROR);
      }
#ifdef SSL
      catch(ClassNotFoundException e)
      {
         throw new VirtuosoException("Class not found: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
      catch(InstantiationException e)
      {
         throw new VirtuosoException("Class cannot be created: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
      catch(IllegalAccessException e)
      {
         throw new VirtuosoException("Class cannot be accessed: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
      catch(NoSuchAlgorithmException e)
      {
         throw new VirtuosoException("Encryption failed: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
      catch(KeyStoreException e)
      {
         throw new VirtuosoException("Encryption failed: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
      catch(KeyManagementException e)
      {
         throw new VirtuosoException("Encryption failed: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
      catch(CertificateException e)
      {
         throw new VirtuosoException("Encryption failed: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
      catch(UnrecoverableKeyException e)
      {
         throw new VirtuosoException("Encryption failed: " + e.getMessage(),VirtuosoException.MISCERROR);
      }
#endif
   }

   /**
    * Send an object to be sent on the output stream.
    *
    * @param obj  The object to send.
    * @exception virtuoso.jdbc2.VirtuosoException An internal error occurred.
    */
   protected void write_object(Object obj) throws IOException, VirtuosoException
   {
     if (VirtuosoFuture.rpc_log != null)
       {
	 synchronized (VirtuosoFuture.rpc_log)
	   {
	     VirtuosoFuture.rpc_log.print ("(conn " + hashCode() + ") OUT ");
	     VirtuosoFuture.rpc_log.println (obj != null ? obj.toString() : "<null>");
	     VirtuosoFuture.rpc_log.flush();
	   }
       }
#if JDK_VER >= 14
    try {
        out.write_object(obj);
        out.flush();
    } catch (IOException ex) {
        if (pooled_connection != null) {
            VirtuosoException vex =
                new VirtuosoException(
                    "Connection failed: " + ex.getMessage(),
                    VirtuosoException.IOERROR);
            pooled_connection.sendErrorEvent(vex);
            throw vex;
        } else {
            throw ex;
        }
    } catch (VirtuosoException ex) {
        if (pooled_connection != null) {
            int code = ex.getErrorCode();
            if (code == VirtuosoException.DISCONNECTED
                || code == VirtuosoException.IOERROR) {
            	pooled_connection.sendErrorEvent(ex);
            }
        }
        throw ex;
    }
#else
    out.write_object(obj);
    out.flush();
#endif
   }

   protected void write_bytes(byte [] bytes) throws IOException, VirtuosoException
   {
#if JDK_VER >= 14
    try {
        for (int k = 0; k < bytes.length; k++)
            out.write(bytes[k]);
        out.flush();
    } catch (IOException ex) {
        if (pooled_connection != null) {
            VirtuosoException vex =
                new VirtuosoException(
                    "Connection failed: " + ex.getMessage(),
                    VirtuosoException.IOERROR);
            pooled_connection.sendErrorEvent(vex);
            throw vex;
        } else {
            throw ex;
        }
    }
#else
    for (int k = 0; k < bytes.length; k++)
        out.write(bytes[k]);
    out.flush();
#endif
   }

   /**
    * Start an RPC function call by sending a VirtuosoFuture request.
    *
    * @param rpcname	The name of the RPC function.
    * @param args		The array of arguments.
    * @return VirtuosoFuture	The future instance.
    * @exception java.io.IOException	An IO error occurred.
    * @exception virtuoso.jdbc2.VirtuosoException An internal error occurred.
    */
   protected VirtuosoFuture getFuture(String rpcname, Object[] args, int timeout)
       throws IOException, VirtuosoException
   {
     VirtuosoFuture fut = null;
     int this_req_no;
     if (futures == null)
       throw new VirtuosoException ("Activity on a closed connection", "IM001", VirtuosoException.SQLERROR);
     synchronized (futures)
       {
	 this_req_no = req_no;
	 req_no += 1;
       }
     // Create a VirtuosoFuture instance
     fut = new VirtuosoFuture(this,rpcname,args,this_req_no, timeout);
     // Set the request id and put it into the hash table
     futures.put(new Integer(this_req_no),fut);
     return fut;
   }

   protected void clearFutures() 
   {
     if (futures != null) 
        synchronized (futures)
        {
	  futures.clear();
        }
   }

   /**
    * Remove a future from the hashtable.
    *
    * @param fut  The future to remove.
    */
   protected void removeFuture(VirtuosoFuture fut)
   {
     if (futures != null)
       futures.remove(new Integer(fut.hashCode()));
   }

   /**
    * Method uses to read messages and dispatch them between their future owner.
    *
    * @return boolean	True if a message was dispatching.
    * @exception java.io.IOException	A stream error occurred.
    * @exception virtuoso.jdbc2.VirtuosoException An internal error occurred.
    */
   protected boolean read_request() throws IOException, VirtuosoException
   {
     if (futures == null)
       throw new VirtuosoException ("Activity on a closed connection", "IM001", VirtuosoException.SQLERROR);
     //System.out.println ("req start");
     Object _result;
#if JDK_VER >= 14
     try {
        _result = in.read_object();
     } catch (IOException ex) {
        if (pooled_connection != null) {
            VirtuosoException vex =
                new VirtuosoException(
                    "Connection failed: " + ex.getMessage(),
                    VirtuosoException.IOERROR);
            pooled_connection.sendErrorEvent(vex);
            throw vex;
        } else {
            throw ex;
        }
     } catch (VirtuosoException ex) {
        if (pooled_connection != null) {
            int code = ex.getErrorCode();
            if (code == VirtuosoException.DISCONNECTED
                || code == VirtuosoException.IOERROR) {
                pooled_connection.sendErrorEvent(ex);
            }
        }
        throw ex;
     }
#else
    _result = in.read_object();
#endif
     //System.out.println ("req end");
     if (VirtuosoFuture.rpc_log != null)
       {
	 synchronized (VirtuosoFuture.rpc_log)
	   {
	     VirtuosoFuture.rpc_log.print ("(conn " + hashCode() + ") IN ");
	     VirtuosoFuture.rpc_log.println (_result != null ? _result.toString() : "<null>");
	     VirtuosoFuture.rpc_log.flush();
	   }
       }

     try
       {
	 openlink.util.Vector result = (openlink.util.Vector)_result;
	 Object tag = result.firstElement();

	 // Check the validity of the message
	 //if(!(tag instanceof Short)) return false;
	 if(((Short)tag).shortValue() != VirtuosoTypes.DA_FUTURE_ANSWER && ((Short)tag).shortValue() != VirtuosoTypes.DA_FUTURE_PARTIAL_ANSWER)
	   return false;
	 // Then put the message into the corresponding future queue
	 //System.out.println("---------------> read_reqest for "+((Number)result.elementAt(1)).intValue());
	 VirtuosoFuture fut = (VirtuosoFuture)futures.get(new Integer(((Number)result.elementAt(1)).intValue()));
	 if(fut == null)
	   return false;
	 fut.putResult(result.elementAt(2));
	 // Set the complete status
	 fut.complete(((Short)tag).shortValue() == VirtuosoTypes.DA_FUTURE_ANSWER);
	 return true;
       }
     catch (ClassCastException e)
       {
         if (VirtuosoFuture.rpc_log != null)
           {
             synchronized (VirtuosoFuture.rpc_log)
               {
                 VirtuosoFuture.rpc_log.println ("(conn " + hashCode() + ") **** runtime2 " +
                     e.getClass().getName() + " in read_request");
                 e.printStackTrace(VirtuosoFuture.rpc_log);
		 VirtuosoFuture.rpc_log.flush();
               }
           }
         throw new Error (e.getClass().getName() + ":" + e.getMessage());
       }
   }

   /**
    * Method uses to get the url of this connection.
    *
    * @return String	The url.
    */
   protected String getURL()
   {
      return url;
   }

   /**
    * Method uses to get the user name of this connection.
    *
    * @return String	The user name.
    */
   protected String getUserName()
   {
      return user;
   }

   /**
    * Method uses to get the qualifier name of this connection.
    *
    * @return String	The qualifier name.
    */
   protected String getQualifierName()
   {
      return qualifier;
   }

   /**
    * Method uses to get the version of the database.
    *
    * @return String	The version number.
    */
   protected String getVersion()
   {
      return version;
   }

   protected int getVersionNum ()
     {
       try
	 {
	   return (new Integer (version.substring (6, 10))).intValue();
	 }
       catch (Exception e)
	 {
	   return 1619;
	 }
     }

   /**
    * Method uses to get the case.
    *
    * @return int The case.
    */
   protected int getCase()
   {
      return _case;
   }

   /**
    * Method uses to get the I/O timeout.
    *
    * @return int	the time out.
    */
   protected int getTimeout()
   {
      return timeout;
   }

   // --------------------------- JDBC 1.0 ------------------------------
   /**
    * Clears all the warnings reported on this Connection object.
    * Virtuoso doesn't generate warnings, so this function does nothing, but we
    * must declare it to be compliant with the JDBC API.
    *
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#clearWarnings
    */
   public void clearWarnings() throws VirtuosoException
   {
       warning = null;
   }

   /**
    * Close the current connection previously established with Virtuoso DBMS.
    *
    * @exception virtuoso.jdbc2.VirtuosoException An error occurred during the connection.
    * @see java.sql.Connection#close
    */
   public void close() throws VirtuosoException
   {
      try
      {
         // Is already closed ?
         if(isClosed())
            throw new VirtuosoException("The connection is already closed.",VirtuosoException.DISCONNECTED);
         // Try to close all about the connection : socket and streams.
         if(!in.isClosed())
         {
            in.close();
            in = null;
         }
         if(!out.isClosed())
         {
            out.close();
            out = null;
         }
         if(socket != null)
         {
            socket.close();
            socket = null;
         }
#if JDK_VER >= 16
         pStatementCache.clear();
#endif
         // Clear some variables
         user = url = password = null;
         futures = null;
#if JDK_VER >= 14
         pooled_connection = null;
         xa_connection = null;
#endif
      }
      catch(IOException e)
      {
      }
   }

   /**
    * Makes all changes made since the previous
    * commit/rollback permanent and releases any database locks
    * currently held by the Connection. This method should be
    * used only when auto-commit mode has been disabled.
    *
    * @exception virtuoso.jdbc2.VirtuosoException An internal error occurred.
    * @see java.sql.Connection#commit
    */
   public synchronized void commit() throws VirtuosoException
   {
      if (global_transaction)
	throw new VirtuosoException("Cannot commit while in global transaction.", VirtuosoException.BADPARAM);
      try
      {
	// RPC transaction
	Object[] args = new Object[2];
	args[0] = new Long(VirtuosoTypes.SQL_COMMIT);
	args[1] = null;
	VirtuosoFuture fut = getFuture(VirtuosoFuture.transaction,args, this.timeout);
	openlink.util.Vector trsres = fut.nextResult();
	//System.err.println ("commit returned " + trsres.toString());
	Object _err = (trsres == null) ? null: ((openlink.util.Vector)trsres).firstElement();
	if (_err instanceof openlink.util.Vector)
	  {
	    openlink.util.Vector err = (openlink.util.Vector) _err;
	    throw new VirtuosoException ((String) (err.elementAt (2)),
		(String) (err.elementAt (1)), VirtuosoException.SQLERROR);
	  }
	// Remove the future reference
	removeFuture(fut);
      }
      catch(IOException e)
      {
         throw new VirtuosoException("Connection failed: " + e.getMessage(),VirtuosoException.IOERROR);
      }
   }

   /**
    * Creates a Statement object to send SQL statements to
    * the Virtuoso DBMS. SQL statements without parameters are normally
    * executed using Statement objects. If the same SQL statement
    * is executed many times, it is more efficient to use a PreparedStatement.
    * Result sets created using the returned Statement will have
    * forward-only type, and read-only concurrency, by default.
    *
    * @return Statement  A new Statement object.
    * @exception VirtuosoException  A database access error occurred.
    * @see java.sql.Connection#createStatement
    * @see virtuoso.jdbc2.VirtuosoStatement
    */
   public Statement createStatement() throws VirtuosoException
   {
      return createStatement(VirtuosoResultSet.TYPE_FORWARD_ONLY,VirtuosoResultSet.CONCUR_READ_ONLY);
   }

   /**
    * Returns the current auto-commit state.
    *
    * @return boolean   The current state of auto-commit mode.
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#setAutoCommit
    */
   public boolean getAutoCommit() throws VirtuosoException
   {
      return auto_commit;
   }

   /**
    * Gets the metadata regarding this connection's database.
    * A Connection's database is able to provide information
    * describing its tables, its supported SQL grammar, its stored
    * procedures, the capabilities of this connection, and so on. This
    * information is made available through a DatabaseMetaData
    * object.
    *
    * @return a DatabaseMetaData object for this Connection
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#getMetaData
    * @see virtuoso.jdbc2.VirtuosoDatabaseMetaData
    */
   public DatabaseMetaData getMetaData() throws VirtuosoException
   {
      return new VirtuosoDatabaseMetaData(this);
   }

   /**
    * Retrieves the first warning reported by calls on this Connection.
    * Subsequent Connection warnings will be chained to this
    * SQLWarning. Virtuoso doesn't generate warnings, so this function
    * returns always null.
    *
    * @return SQLWarning   The first SQLWarning or null (must be null for the moment)
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just implementation).
    * @see java.sql.Connection#getWarnings
    */
   public SQLWarning getWarnings() throws VirtuosoException
   {
      return warning;
   }

   /**
    * Attempts to change the transaction isolation level to the one given.
    * The constants defined in the interface <code>Connection</code>
    * are the possible transaction isolation levels.
    *
    * @param level one of the TRANSACTION_* isolation values with the
    * exception of TRANSACTION_NONE; some databases may not support
    * other values
    * @exception virtuoso.jdbc2.VirtuosoException An internal error occurred.
    * @see java.sql.Connection#setTransactionIsolation
    */
   public void setTransactionIsolation(int level) throws VirtuosoException
   {
      // Check and set parameters
      if(level == Connection.TRANSACTION_READ_UNCOMMITTED || level == Connection.TRANSACTION_READ_COMMITTED || level == Connection.TRANSACTION_REPEATABLE_READ || level == Connection.TRANSACTION_SERIALIZABLE)
         trxisolation = level;
      else
         throw new VirtuosoException("Bad parameters.",VirtuosoException.BADPARAM);
   }

   /**
    * Gets this Connection's current transaction isolation level.
    *
    * @return the current TRANSACTION_* mode value
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#getTransactionIsolation
    */
   public int getTransactionIsolation() throws VirtuosoException
   {
      return trxisolation;
   }

   /**
    * Checks if the connection is closed.
    *
    * @return boolean   True if the connection is closed, false if it's still open.
    */
   public boolean isClosed()
   {
      return
         (socket == null)
         || (in == null || in.isClosed())
         || (out == null || out.isClosed())
         ;
   }

   /**
    * Creates a CallableStatement object to call database stored procedures.
    * Result sets created using the returned CallableStatement will have
    * forward-only type and read-only concurrency, by default.
    *
    * @param sql a SQL statement that may contain one or more '?'
    * parameter placeholders. Typically this  statement is a JDBC
    * function call escape string.
    * @return a new CallableStatement object containing the
    * pre-compiled SQL statement
    * @exception virtuoso.jdbc2.VirtuosoException An internal error occurred.
    * @see java.sql.Connection#prepareCall
    * @see virtuoso.jdbc2.VirtuosoCallableStatement
    */
   public CallableStatement prepareCall(String sql) throws VirtuosoException
   {
      return prepareCall(sql,VirtuosoResultSet.TYPE_FORWARD_ONLY,VirtuosoResultSet.CONCUR_READ_ONLY);
   }

   /**
    * Creates a PreparedStatement object to send parameterized SQL statements to the database.
    * Result sets created using the returned PreparedStatement will have
    * forward-only type and read-only concurrency, by default.
    *
    * @param sql a SQL statement that may contain one or more '?' IN parameter placeholders
    * @return PreparedStatement  A new PreparedStatement object.
    * @exception VirtuosoException  A database access error occurs.
    * @see java.sql.Connection#prepareStatement
    * @see virtuoso.jdbc2.VirtuosoPreparedStatement
    */
   public PreparedStatement prepareStatement(String sql) throws VirtuosoException
   {
      return prepareStatement(sql,VirtuosoResultSet.TYPE_FORWARD_ONLY,VirtuosoResultSet.CONCUR_READ_ONLY);
   }

   /**
    * Drops all changes made since the previous commit/rollback and releases
    * any database locks currently held by this Connection.
    * This method should be used only when auto-commit has been disabled.
    *
    * @exception virtuoso.jdbc2.VirtuosoException An internal error occurred.
    * @see java.sql.Connection#rollback
    */
   public synchronized void rollback() throws VirtuosoException
   {
      if (global_transaction)
	throw new VirtuosoException("Cannot rollback while in global transaction.", VirtuosoException.BADPARAM);
      try
      {
         // RPC transaction
         Object[] args = new Object[2];
         args[0] = new Long(VirtuosoTypes.SQL_ROLLBACK);
         args[1] = null;
         VirtuosoFuture fut = getFuture(VirtuosoFuture.transaction,args, this.timeout);
         openlink.util.Vector trsres = fut.nextResult();
	 //System.err.println ("rollback returned " + trsres.toString());
	 Object _err = (trsres == null) ? null: ((openlink.util.Vector)trsres).firstElement();
	 if (_err instanceof openlink.util.Vector)
	   {
	     openlink.util.Vector err = (openlink.util.Vector) _err;
	     throw new VirtuosoException ((String) (err.elementAt (2)),
		 (String) (err.elementAt (1)), VirtuosoException.SQLERROR);
	   }
         // Remove the future reference
         if(fut!=null) removeFuture(fut);
      }
      catch(IOException e)
      {
         throw new VirtuosoException("Connection failed: " + e.getMessage(),VirtuosoException.IOERROR);
      }
   }

   /**
    * Sets this connection's auto-commit mode.
    * By default, new connections are in auto-commit mode.
    *
    * @param autoCommit True enables auto-commit; false disables it.
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#setAutoCommit
    */
   public void setAutoCommit(boolean autoCommit) throws VirtuosoException
   {
      if (autoCommit && global_transaction)
	throw new VirtuosoException("Cannot set autocommit mode while in global transaction.", VirtuosoException.BADPARAM);
      this.auto_commit = autoCommit;
   }

   // --------------------------- JDBC 2.0 ------------------------------
   /**
    * Creates a Statement object that will generate ResultSet
    * objects with the given type and concurrency.
    * This method is the same as the createStatement method above, but it
    * allows the default result set type and result set concurrency type
    * to be overridden.
    *
    * @param resultSetType A result set type; see VirtuosoResultSet.TYPE_XXX
    * @param resultSetConcurrency   A concurrency type; see VirtuosoResultSet.CONCUR_XXX
    * @return Statement  A new Statement object.
    * @exception VirtuosoException  A database access error occurs.
    * @see java.Connection#createStatement
    * @see virtuoso.jdbc2.VirtuosoStatement
    */
   public Statement createStatement(int resultSetType, int resultSetConcurrency) throws VirtuosoException
   {
      return new VirtuosoStatement(this,resultSetType,resultSetConcurrency);
   }

   /**
    * Creates a CallableStatement object that will generate
    * ResultSet objects with the given type and concurrency.
    * This method is the same as the createStatement method above, but it
    * allows the default result set type and result set concurrency type
    * to be overridden.
    *
    * @param resultSetType a result set type; see VirtuosoResultSet.TYPE_XXX
    * @param resultSetConcurrency a concurrency type; see VirtuosoResultSet.CONCUR_XXX
    * @return a new CallableStatement object containing the
    * pre-compiled SQL statement
    * @exception VirtuosoException  A database access error occurs.
    * @see java.sql.Connection#prepareCall
    * @see virtuoso.jdbc2.VirtuosoCallableStatement
    */
   public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws VirtuosoException
   {
      return new VirtuosoCallableStatement(this,sql,resultSetType,resultSetConcurrency);
   }

   /**
    * Creates a PreparedStatement object that will generate
    * ResultSet objects with the given type and concurrency.
    * This method is the same as the prepareStatement method
    * above, but it allows the default result set
    * type and result set concurrency type to be overridden.
    *
    * @param sql a SQL statement that may contain one or more '?' IN
    *            parameter placeholders
    * @param resultSetType a result set type; see VirtuosoResultSet.TYPE_XXX
    * @param resultSetConcurrency a concurrency type; see VirtuosoResultSet.CONCUR_XXX
    * @return a new CallableStatement object containing the
    * pre-compiled SQL statement
    * @exception VirtuosoException  A database access error occurs.
    * @see java.sql.Connection#prepareCall
    * @see virtuoso.jdbc2.VirtuosoPreparedStatement
    */
   public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws VirtuosoException
   {
#if JDK_VER >= 16
     if (useCachePrepStatements) {
       VirtuosoPreparedStatement ps = null;
       synchronized(pStatementCache) {
         ps = pStatementCache.remove(""+resultSetType+"#"
                                       +resultSetConcurrency+"#"
        			       +sql);
         if (ps != null) {
           ps.setClosed(false);
           ps.clearParameters();
         } else {
           ps = new VirtuosoPreparedStatement(this, sql, resultSetType,
           		resultSetConcurrency);
           ps.isCached = true;
         }
       }
       return ps;

     }
     else
#endif
     {
       return new VirtuosoPreparedStatement(this,sql,resultSetType,resultSetConcurrency);
     }
   }

   // --------------------------- Object ------------------------------
   /**
    * Returns a hash code value for the object.
    *
    * @return int	The hash code value.
    */
   public int hashCode()
   {
      return con_no;
   }

   /**
    * Method runs when the garbage collector want to erase the object
    */
   public void finalize() throws Throwable
   {
      close();
   }

   // --------------------------- Not yet ------------------------------
   /**
    * Check if the connection is in read-only mode.
    *
    * @return boolean   True if connection is read-only and false otherwise.
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#isReadOnly
    */
   public boolean isReadOnly() throws VirtuosoException
   {
      return readOnly;
   }

   /**
    * Puts this connection in read-only mode.
    *
    * @param readOnly   True enables read-only mode; false disables it.
    * @exception virtuoso.jdbc2.VirtuosoException An internal error occurred.
    * @see java.sql.Connection#setReadOnly
    */
   public void setReadOnly(boolean readOnly) throws VirtuosoException
   {
     this.readOnly = readOnly;
   }

   /**
    * Converts the given SQL statement into the system's native SQL grammar.
    * A driver may convert the JDBC sql grammar into its system's
    * native SQL grammar prior to sending it; this method returns the
    * native form of the statement that the driver would have sent.
    *
    * @param sql a SQL statement that may contain one or more '?'
    * parameter placeholders
    * @return the native form of this statement
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#nativeSQL
    */
   public String nativeSQL(String sql) throws VirtuosoException
   {
      return "";
   }

   /**
    * Sets a catalog name in order to select
    * a subspace of this Connection's database in which to work.
    * If the driver does not support catalogs, it will
    * silently ignore this request.
    *
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#setCatalog
    */
   public void setCatalog(String catalog) throws VirtuosoException
   {
   }

   /**
    * Returns the Connection's current catalog name.
    *
    * @return the current catalog name or null
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just an implementation question).
    * @see java.sql.Connection#getCatalog
    */
   public String getCatalog() throws VirtuosoException
   {
      return qualifier;
   }

#if JDK_VER >= 12
   /**
    * Gets the type map object associated with this connection.
    * Unless the application has added an entry to the type map,
    * the map returned will be empty.
    *
    * @return the <code>java.util.Map</code> object associated
    *         with this <code>Connection</code> object
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just implementation).
    * @see java.sql.Connection#getTypeMap
    */
#if JDK_VER >= 16
   public java.util.Map<String, Class<?>> getTypeMap() throws VirtuosoException
#else
   public Map getTypeMap() throws VirtuosoException
#endif
   {
      return null;
   }

   /**
    * Installs the given type map as the type map for
    * this connection.  The type map will be used for the
    * custom mapping of SQL structured types and distinct types.
    *
    * @param the <code>java.util.Map</code> object to install
    *        as the replacement for this <code>Connection</code>
    *        object's default type map
    * @exception virtuoso.jdbc2.VirtuosoException No errors returned (just implementation).
    * @see java.sql.Connection#setTypeMap
    */
#if JDK_VER >= 16
   public void setTypeMap(java.util.Map<String,Class<?>> map) throws VirtuosoException
#else
   public void setTypeMap(Map map) throws VirtuosoException
#endif
   {
   }
#endif

   protected void setSocketTimeout (int timeout) throws VirtuosoException
     {
      try
	{
	  //System.err.println ("timeout = " + timeout);
	  if (timeout != -1)
	    socket.setSoTimeout (timeout * 1000);
	}
      catch (java.net.SocketException e)
	{
	  throw new VirtuosoException ("Unable to set socket timeout : " + e.getMessage(),
	      "S1000", VirtuosoException.MISCERROR);
	}
     }

   protected VirtuosoExplicitString escapeSQL (String sql) throws VirtuosoException
     {
       VirtuosoExplicitString sql1;
       //System.out.println ("in escapeSQL SQL charset = " + this.charset);
       if (this.charset != null)
	 {
	   //System.out.println ("in escapeSQL SQL len = " + sql.length());
	   //System.out.println ("in escapeSQL SQL aref(15) = " + ((int)sql.charAt(15)));
	   byte [] bytes = charsetBytes(sql);
	   sql1 = new VirtuosoExplicitString (bytes, VirtuosoTypes.DV_STRING);
	   return sql1;
	 }
       if (this.charset_utf8)
       {
	  sql1 = new VirtuosoExplicitString (sql, VirtuosoTypes.DV_STRING, this);
	  return sql1;
       }
       if (this.utf8_execs)
	 {
	   /* use UTF8 encodings */
	   try
	     {
	       byte [] bytes = (new String ("\n--utf8_execs=yes\n" + sql)).getBytes("UTF8");
	       sql1 = new VirtuosoExplicitString (bytes, VirtuosoTypes.DV_STRING);
	     }
	   catch (java.io.UnsupportedEncodingException e)
	     {
	       sql1 = new VirtuosoExplicitString ("\n--utf8_execs=yes\n" + sql,
		   VirtuosoTypes.DV_STRING, this);
	     }
	 }
       else
	 {
           /* use \x encoding */
	   sql1 = new VirtuosoExplicitString ("", VirtuosoTypes.DV_STRING, null);
	   sql1.cli_wide_to_escaped (sql, this.client_charset_hash);
	 }
       return sql1;
     }

   protected VirtuosoExplicitString escapeSQLString (String sql) throws VirtuosoException
     {
       VirtuosoExplicitString sql1;
       //System.out.println ("in escapeSQLString SQL charset = " + this.charset);
       if (this.charset != null)
	 {
	   byte [] bytes = charsetBytes(sql);
	   sql1 = new VirtuosoExplicitString (bytes,  VirtuosoTypes.DV_STRING);
	   return sql1;
	 }
       if (this.utf8_execs)
	 {
	   /* use UTF8 encodings */
	   try
	     {
	       byte [] bytes = sql.getBytes("UTF8");
	       sql1 = new VirtuosoExplicitString (bytes, VirtuosoTypes.DV_STRING);
	     }
	   catch (java.io.UnsupportedEncodingException e)
	     {
	       sql1 = new VirtuosoExplicitString (sql,
		   VirtuosoTypes.DV_STRING, this);
	     }
	 }
       else
	 {
           /* use \x encoding */
	   sql1 = new VirtuosoExplicitString ("", VirtuosoTypes.DV_STRING, null);
	   sql1.cli_wide_to_escaped (sql, this.client_charset_hash);
	 }
       return sql1;
     }

   protected byte[] charsetBytes1(String source, String from, String to) throws VirtuosoException
    {
       byte ans[] = new byte[0];
       //System.err.println ("charsetBytes1(" + from + " , " + to);
       //System.err.println ("charsetBytes1 src len=" + source.length());
       ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream( source.length() );
       try
	 {
	   OutputStreamWriter outputWriter = new OutputStreamWriter(byteArrayOutputStream, from);
	   outputWriter.write(source, 0, source.length());
	   outputWriter.flush();
	   byte[] bytes = byteArrayOutputStream.toByteArray();
	   ans = bytes;
	   //System.err.println ("charsetBytes1 ret len=" + ans.length);
	   /*
	      BufferedReader bufferedReader =
	      (new BufferedReader( new InputStreamReader( new ByteArrayInputStream(bytes), "8859_1")));
	      ans = bufferedReader.readLine();
	    */
	 }
       catch (Exception e)
	 {
	   throw new VirtuosoException (
	       "InternationalizationHelper: UnsupportedEncodingException: " + e,
	       VirtuosoException.CASTERROR);
	 }
       return ans;
    }

   protected byte[] charsetBytes(String source) throws VirtuosoException
     {
       //System.out.println ("In charsetBytes len=" + source.length() + "aref(0)" + ((int)source.charAt (0)));
       if (source == null)
	 return null;
       return charsetBytes1(source, this.charset, "8859_1");
     }

   protected String uncharsetBytes(String source) throws VirtuosoException
     {
       if (source == null)
	 return null;
       //System.err.println ("uncharsetBytes src len=" + source.length());
       ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream( source.length() );
       try
	 {
	   OutputStreamWriter outputWriter = new OutputStreamWriter(byteArrayOutputStream, "8859_1");
	   outputWriter.write(source, 0, source.length());
	   outputWriter.flush();
	   byte[] bytes = byteArrayOutputStream.toByteArray();
	   BufferedReader bufferedReader =
	       (new BufferedReader( new InputStreamReader( new ByteArrayInputStream(bytes), this.charset)));
	   StringBuffer buf = new StringBuffer();
	   char cbuf [] = new char[4096];
	   int read;
	   while (0 < (read = bufferedReader.read (cbuf)))
	     buf.append (cbuf, 0, read);
	   //System.err.println ("uncharsetBytes1 ret len=" + buf.length());
	   return buf.toString();
	 }
       catch (Exception e)
	 {
	   throw new VirtuosoException (
	       "InternationalizationHelper: UnsupportedEncodingException: " + e,
	       VirtuosoException.CASTERROR);
	 }
     }

#if JDK_VER >= 14
   /* JDK 1.4 functions */

   /**
    * supports only <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> for now
    * @exception virtuoso.jdbc2.VirtuosoException if the holdability is not the supported one
    */
   protected void checkHoldability (int holdability) throws SQLException
     {
       if (holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT)
         throw new VirtuosoException ("Unable to hold cursors over commit", "IM001",
 	   VirtuosoException.NOTIMPLEMENTED);
       else if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT)
         throw new VirtuosoException ("Invalid holdability value", "22023",
 	   VirtuosoException.BADPARAM);
     }

   /**
    * calls checkHoldability
    * @see java.sql.Connection#checkHoldability
    */
   public void setHoldability (int holdability) throws SQLException
     {
       checkHoldability (holdability);
     }

   public int getHoldability() throws SQLException
     {
       return ResultSet.CLOSE_CURSORS_AT_COMMIT;
     }

   /**
    * @exception virtuoso.jdbc2.VirtuosoException allways thrown : savepoints not supported
    */
   public Savepoint setSavepoint() throws SQLException
     {
       throw new VirtuosoException ("Savepoints not supported", "IM001",
         VirtuosoException.NOTIMPLEMENTED);
     }

   /**
    * @exception virtuoso.jdbc2.VirtuosoException allways thrown : savepoints not supported
    */
   public Savepoint setSavepoint(String name) throws SQLException
     {
       throw new VirtuosoException ("Savepoints not supported", "IM001",
         VirtuosoException.NOTIMPLEMENTED);
     }

   /**
    * @exception virtuoso.jdbc2.VirtuosoException allways thrown : savepoints not supported
    */
   public void rollback(Savepoint savepoint) throws SQLException
     {
       throw new VirtuosoException ("Savepoints not supported", "IM001",
         VirtuosoException.NOTIMPLEMENTED);
     }

   /**
    * @exception virtuoso.jdbc2.VirtuosoException allways thrown : savepoints not supported
    */
   public void releaseSavepoint(Savepoint savepoint) throws SQLException
     {
       throw new VirtuosoException ("Savepoints not supported", "IM001",
         VirtuosoException.NOTIMPLEMENTED);
     }

   /**
    * calls checkHoldability and then normal createStatement
    * @see java.sql.Connection#checkHoldability
    */
   public Statement createStatement(int resultSetType,
       int resultSetConcurrency,
       int resultSetHoldability) throws SQLException
     {
       checkHoldability (resultSetHoldability);
       return createStatement (resultSetType, resultSetConcurrency);
     }

   /**
    * calls checkHoldability and then normal prepareStatement
    * @see java.sql.Connection#checkHoldability
    */
   public PreparedStatement prepareStatement(String sql,
       int resultSetType,
       int resultSetConcurrency,
       int resultSetHoldability) throws SQLException
     {
       checkHoldability (resultSetHoldability);
       return prepareStatement (sql, resultSetType, resultSetConcurrency);
     }

   /**
    * calls checkHoldability and then normal prepareCall
    * @see java.sql.Connection#checkHoldability
    */
   public CallableStatement prepareCall(String sql,
       int resultSetType,
       int resultSetConcurrency,
       int resultSetHoldability) throws SQLException
     {
       checkHoldability (resultSetHoldability);
       return prepareCall (sql, resultSetType, resultSetConcurrency);
     }

   /**
    * <code>autoGeneratedKeys</code> ignored
    */
   public PreparedStatement prepareStatement(String sql,
       int autoGeneratedKeys) throws SQLException
     {
       return prepareStatement (sql);
     }

   /**
    * <code>columnIndexes ignored</code> ignored
    */
   public PreparedStatement prepareStatement(String sql,
       int[] columnIndexes) throws SQLException
     {
       return prepareStatement (sql);
     }

   /**
    * <code>columnNames ignored</code> ignored
    */
   public PreparedStatement prepareStatement(String sql,
       String[] columnNames) throws SQLException
     {
       return prepareStatement (sql);
     }

#if JDK_VER >= 16
    //------------------------- JDBC 4.0 -----------------------------------
    /**
     * Constructs an object that implements the <code>Clob</code> interface. The object
     * returned initially contains no data.  The <code>setAsciiStream</code>,
     * <code>setCharacterStream</code> and <code>setString</code> methods of
     * the <code>Clob</code> interface may be used to add data to the <code>Clob</code>.
     * @return An object that implements the <code>Clob</code> interface
     * @throws SQLException if an object that implements the
     * <code>Clob</code> interface can not be constructed, this method is
     * called on a closed connection or a database access error occurs.
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this data type
     *
     * @since 1.6
     */
  public Clob createClob() throws SQLException
  {
    return new VirtuosoBlob();
  }

    /**
     * Constructs an object that implements the <code>Blob</code> interface. The object
     * returned initially contains no data.  The <code>setBinaryStream</code> and
     * <code>setBytes</code> methods of the <code>Blob</code> interface may be used to add data to
     * the <code>Blob</code>.
     * @return  An object that implements the <code>Blob</code> interface
     * @throws SQLException if an object that implements the
     * <code>Blob</code> interface can not be constructed, this method is
     * called on a closed connection or a database access error occurs.
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this data type
     *
     * @since 1.6
     */
  public Blob createBlob() throws SQLException
  {
    return new VirtuosoBlob();
  }

    /**
     * Constructs an object that implements the <code>NClob</code> interface. The object
     * returned initially contains no data.  The <code>setAsciiStream</code>,
     * <code>setCharacterStream</code> and <code>setString</code> methods of the <code>NClob</code> interface may
     * be used to add data to the <code>NClob</code>.
     * @return An object that implements the <code>NClob</code> interface
     * @throws SQLException if an object that implements the
     * <code>NClob</code> interface can not be constructed, this method is
     * called on a closed connection or a database access error occurs.
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this data type
     *
     * @since 1.6
     */
  public NClob createNClob() throws SQLException
  {
    return new VirtuosoBlob();
  }

    /**
     * Constructs an object that implements the <code>SQLXML</code> interface. The object
     * returned initially contains no data. The <code>createXmlStreamWriter</code> object and
     * <code>setString</code> method of the <code>SQLXML</code> interface may be used to add data to the <code>SQLXML</code>
     * object.
     * @return An object that implements the <code>SQLXML</code> interface
     * @throws SQLException if an object that implements the <code>SQLXML</code> interface can not
     * be constructed, this method is
     * called on a closed connection or a database access error occurs.
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this data type
     * @since 1.6
     */
  public SQLXML createSQLXML() throws SQLException
  {
     throw new VirtuosoFNSException ("createSQLXML()  not supported", VirtuosoException.NOTIMPLEMENTED);
  }

        /**
	 * Returns true if the connection has not been closed and is still valid.
	 * The driver shall submit a query on the connection or use some other
	 * mechanism that positively verifies the connection is still valid when
	 * this method is called.
	 * <p>
	 * The query submitted by the driver to validate the connection shall be
	 * executed in the context of the current transaction.
	 *
	 * @param timeout -		The time in seconds to wait for the database operation
	 * 						used to validate the connection to complete.  If
	 * 						the timeout period expires before the operation
	 * 						completes, this method returns false.  A value of
	 * 						0 indicates a timeout is not applied to the
	 * 						database operation.
	 * <p>
	 * @return true if the connection is valid, false otherwise
         * @exception SQLException if the value supplied for <code>timeout</code>
         * is less then 0
         * @since 1.6
	 * <p>
	 * @see java.sql.DatabaseMetaData#getClientInfoProperties
	 */
   public boolean isValid(int timeout) throws SQLException
   {
     throw new VirtuosoFNSException ("isValid(timeout)  not supported", VirtuosoException.NOTIMPLEMENTED);
   }

	/**
	 * Sets the value of the client info property specified by name to the
	 * value specified by value.
	 * <p>
	 * Applications may use the <code>DatabaseMetaData.getClientInfoProperties</code>
	 * method to determine the client info properties supported by the driver
	 * and the maximum length that may be specified for each property.
	 * <p>
	 * The driver stores the value specified in a suitable location in the
	 * database.  For example in a special register, session parameter, or
	 * system table column.  For efficiency the driver may defer setting the
	 * value in the database until the next time a statement is executed or
	 * prepared.  Other than storing the client information in the appropriate
	 * place in the database, these methods shall not alter the behavior of
	 * the connection in anyway.  The values supplied to these methods are
	 * used for accounting, diagnostics and debugging purposes only.
	 * <p>
	 * The driver shall generate a warning if the client info name specified
	 * is not recognized by the driver.
	 * <p>
	 * If the value specified to this method is greater than the maximum
	 * length for the property the driver may either truncate the value and
	 * generate a warning or generate a <code>SQLClientInfoException</code>.  If the driver
	 * generates a <code>SQLClientInfoException</code>, the value specified was not set on the
	 * connection.
	 * <p>
	 * The following are standard client info properties.  Drivers are not
	 * required to support these properties however if the driver supports a
	 * client info property that can be described by one of the standard
	 * properties, the standard property name should be used.
	 * <p>
	 * <ul>
	 * <li>ApplicationName	-	The name of the application currently utilizing
	 * 				the connection</li>
	 * <li>ClientUser	-	The name of the user that the application using
	 * 				the connection is performing work for.  This may
	 * 				not be the same as the user name that was used
	 * 				in establishing the connection.</li>
	 * <li>ClientHostname	-	The hostname of the computer the application
	 * 				using the connection is running on.</li>
	 * </ul>
	 * <p>
	 * @param name		The name of the client info property to set
	 * @param value		The value to set the client info property to.  If the
	 * 			value is null, the current value of the specified
	 * 			property is cleared.
	 * <p>
	 * @throws	SQLClientInfoException if the database server returns an error while
	 * 		setting the client info value on the database server or this method
         * is called on a closed connection
	 * <p>
	 * @since 1.6
	 */
  public void setClientInfo(String name, String value) throws SQLClientInfoException
  {
    Map<String, ClientInfoStatus> fail = new HashMap<String, ClientInfoStatus>();
    fail.put(name, ClientInfoStatus.REASON_UNKNOWN_PROPERTY);
    throw new SQLClientInfoException("ClientInfo property not supported", fail);
  }

   /**
     * Sets the value of the connection's client info properties.  The
     * <code>Properties</code> object contains the names and values of the client info
     * properties to be set.  The set of client info properties contained in
     * the properties list replaces the current set of client info properties
     * on the connection.  If a property that is currently set on the
     * connection is not present in the properties list, that property is
     * cleared.  Specifying an empty properties list will clear all of the
     * properties on the connection.  See <code>setClientInfo (String, String)</code> for
     * more information.
     * <p>
     * If an error occurs in setting any of the client info properties, a
     * <code>SQLClientInfoException</code> is thrown. The <code>SQLClientInfoException</code>
     * contains information indicating which client info properties were not set.
     * The state of the client information is unknown because
     * some databases do not allow multiple client info properties to be set
     * atomically.  For those databases, one or more properties may have been
     * set before the error occurred.
     * <p>
     *
     * @param properties the list of client info properties to set
     * <p>
     * @see java.sql.Connection#setClientInfo(String, String) setClientInfo(String, String)
     * @since 1.6
     * <p>
     * @throws SQLClientInfoException if the database server returns an error while
     * 		setting the clientInfo values on the database server or this method
     * is called on a closed connection
     * <p>
     */
  public void setClientInfo(Properties properties) throws SQLClientInfoException
  {
    if (properties == null || properties.size() == 0)
      return;

    Map<String, ClientInfoStatus> fail = new HashMap<String, ClientInfoStatus>();

    Iterator<String> i = properties.stringPropertyNames().iterator();
    while (i.hasNext()) {
      fail.put(i.next(), ClientInfoStatus.REASON_UNKNOWN_PROPERTY);
    }
    throw new SQLClientInfoException("ClientInfo property not supported", fail);
  }

	/**
	 * Returns the value of the client info property specified by name.  This
	 * method may return null if the specified client info property has not
	 * been set and does not have a default value.  This method will also
	 * return null if the specified client info property name is not supported
	 * by the driver.
	 * <p>
	 * Applications may use the <code>DatabaseMetaData.getClientInfoProperties</code>
	 * method to determine the client info properties supported by the driver.
	 * <p>
	 * @param name		The name of the client info property to retrieve
	 * <p>
	 * @return 			The value of the client info property specified
	 * <p>
	 * @throws SQLException		if the database server returns an error when
	 * 							fetching the client info value from the database
         *or this method is called on a closed connection
	 * <p>
	 * @since 1.6
	 * <p>
	 * @see java.sql.DatabaseMetaData#getClientInfoProperties
	 */
  public String getClientInfo(String name) throws SQLException
  {
    return null;
  }

	/**
	 * Returns a list containing the name and current value of each client info
	 * property supported by the driver.  The value of a client info property
	 * may be null if the property has not been set and does not have a
	 * default value.
	 * <p>
	 * @return	A <code>Properties</code> object that contains the name and current value of
	 * 			each of the client info properties supported by the driver.
	 * <p>
	 * @throws 	SQLException if the database server returns an error when
	 * 			fetching the client info values from the database
         * or this method is called on a closed connection
	 * <p>
	 * @since 1.6
	 */
  public Properties getClientInfo() throws SQLException
  {
    return null;
  }

/**
  * Factory method for creating Array objects.
  *<p>
  * <b>Note: </b>When <code>createArrayOf</code> is used to create an array object
  * that maps to a primitive data type, then it is implementation-defined
  * whether the <code>Array</code> object is an array of that primitive
  * data type or an array of <code>Object</code>.
  * <p>
  * <b>Note: </b>The JDBC driver is responsible for mapping the elements
  * <code>Object</code> array to the default JDBC SQL type defined in
  * java.sql.Types for the given class of <code>Object</code>. The default
  * mapping is specified in Appendix B of the JDBC specification.  If the
  * resulting JDBC type is not the appropriate type for the given typeName then
  * it is implementation defined whether an <code>SQLException</code> is
  * thrown or the driver supports the resulting conversion.
  *
  * @param typeName the SQL name of the type the elements of the array map to. The typeName is a
  * database-specific name which may be the name of a built-in type, a user-defined type or a standard  SQL type supported by this database. This
  *  is the value returned by <code>Array.getBaseTypeName</code>
  * @param elements the elements that populate the returned object
  * @return an Array object whose elements map to the specified SQL type
  * @throws SQLException if a database error occurs, the JDBC type is not
  *  appropriate for the typeName and the conversion is not supported, the typeName is null or this method is called on a closed connection
  * @throws SQLFeatureNotSupportedException  if the JDBC driver does not support this data type
  * @since 1.6
  */
  public Array createArrayOf(String typeName, Object[] elements) throws SQLException
  {
    throw new VirtuosoFNSException ("createArrayOf(typeName, elements)  not supported", VirtuosoException.NOTIMPLEMENTED);
  }

/**
  * Factory method for creating Struct objects.
  *
  * @param typeName the SQL type name of the SQL structured type that this <code>Struct</code>
  * object maps to. The typeName is the name of  a user-defined type that
  * has been defined for this database. It is the value returned by
  * <code>Struct.getSQLTypeName</code>.

  * @param attributes the attributes that populate the returned object
  *  @return a Struct object that maps to the given SQL type and is populated with the given attributes
  * @throws SQLException if a database error occurs, the typeName is null or this method is called on a closed connection
  * @throws SQLFeatureNotSupportedException  if the JDBC driver does not support this data type
  * @since 1.6
  */
  public Struct createStruct(String typeName, Object[] attributes) throws SQLException
  {
    throw new VirtuosoFNSException ("createStruct(typeName, attributes)  not supported", VirtuosoException.NOTIMPLEMENTED);
  }


    /**
     * Returns an object that implements the given interface to allow access to
     * non-standard methods, or standard methods not exposed by the proxy.
     *
     * If the receiver implements the interface then the result is the receiver
     * or a proxy for the receiver. If the receiver is a wrapper
     * and the wrapped object implements the interface then the result is the
     * wrapped object or a proxy for the wrapped object. Otherwise return the
     * the result of calling <code>unwrap</code> recursively on the wrapped object
     * or a proxy for that result. If the receiver is not a
     * wrapper and does not implement the interface, then an <code>SQLException</code> is thrown.
     *
     * @param iface A Class defining an interface that the result must implement.
     * @return an object that implements the interface. May be a proxy for the actual implementing object.
     * @throws java.sql.SQLException If no object found that implements the interface
     * @since 1.6
     */
  public <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException
  {
    if(isClosed())
      throw new VirtuosoException("The connection is already closed.",VirtuosoException.DISCONNECTED);
    try {
      // This works for classes that aren't actually wrapping anything
      return iface.cast(this);
    } catch (ClassCastException cce) {
      throw new VirtuosoException ("Unable to unwrap to "+iface.toString(), "22023", VirtuosoException.BADPARAM);
    }
  }

    /**
     * Returns true if this either implements the interface argument or is directly or indirectly a wrapper
     * for an object that does. Returns false otherwise. If this implements the interface then return true,
     * else if this is a wrapper then return the result of recursively calling <code>isWrapperFor</code> on the wrapped
     * object. If this does not implement the interface and is not a wrapper, return false.
     * This method should be implemented as a low-cost operation compared to <code>unwrap</code> so that
     * callers can use this method to avoid expensive <code>unwrap</code> calls that may fail. If this method
     * returns true then calling <code>unwrap</code> with the same argument should succeed.
     *
     * @param iface a Class defining an interface.
     * @return true if this implements the interface or directly or indirectly wraps an object that does.
     * @throws java.sql.SQLException  if an error occurs while determining whether this is a wrapper
     * for an object with the given interface.
     * @since 1.6
     */
  public boolean isWrapperFor(java.lang.Class<?> iface) throws java.sql.SQLException
  {
    if(isClosed())
      throw new VirtuosoException("The connection is closed.",VirtuosoException.DISCONNECTED);

    // This works for classes that aren't actually wrapping anything
    return iface.isInstance(this);
  }

  private void createCaches(int cacheSize)
  {
    pStatementCache = new LRUCache<String,VirtuosoPreparedStatement>(cacheSize) {
	protected boolean removeEldestEntry(java.util.Map.Entry eldest) {
	  if (this.maxSize <= 1) {
	    return false;
	  }

	  boolean remove = super.removeEldestEntry(eldest);

	  if (remove) {
	    VirtuosoPreparedStatement ps =
	        (VirtuosoPreparedStatement)eldest.getValue();
	    ps.isCached = false;
	    ps.setClosed(false);

	    try {
	      ps.close();
	    } catch (SQLException ex) {
	    }
	  }

	  return remove;
	}
    };
  }


  protected void recacheStmt(VirtuosoPreparedStatement ps) throws SQLException
  {
    if (ps.isPoolable()) {
      synchronized (pStatementCache) {
        pStatementCache.put(""+ps.getResultSetType()+"#"
        		      +ps.getResultSetConcurrency()+"#"
        		      +ps.sql, ps);
      }
    }
  }

#endif
#endif


    /* Global XA transaction support */

    boolean getGlobalTransaction() {
	   if (VirtuosoFuture.rpc_log != null)
	   {
	       synchronized (VirtuosoFuture.rpc_log)
	       {
		   VirtuosoFuture.rpc_log.println ("VirtuosoConnection.getGlobalTransaction () (con=" + this.hashCode() + ") :" + global_transaction);
		   VirtuosoFuture.rpc_log.flush();
	       }
	   }
        return global_transaction;
    }

    void setGlobalTransaction(boolean value) {
	   if (VirtuosoFuture.rpc_log != null)
	   {
	       synchronized (VirtuosoFuture.rpc_log)
	       {
		   VirtuosoFuture.rpc_log.println ("VirtuosoConnection.getGlobalTransaction (" + value + ") (con=" + this.hashCode() + ") :" + global_transaction);
		   VirtuosoFuture.rpc_log.flush();
	       }
	   }
        global_transaction = value;
    }

    protected void setWarning (SQLWarning warn)
    {
	warn.setNextWarning (warning);
	warning = warn;
    }

    protected VirtuosoException notify_error (Throwable e)
    {
	VirtuosoException vex;
	if (!(e instanceof VirtuosoException))
	{
	    vex = new VirtuosoException(e.getMessage(), VirtuosoException.IOERROR);
#if JDK_VER >= 14
	    vex.initCause (e);
#endif
	}
	else
	    vex = (VirtuosoException) e;
#if JDK_VER >= 14
        if (pooled_connection != null && isCriticalError(vex)) {
            pooled_connection.sendErrorEvent(vex);
	}
#endif
	return vex;
    }

    public static boolean isCriticalError(SQLException ex)
    {
      if (ex == null)
        return false;
      String SQLstate = ex.getSQLState();
      if (SQLstate != null && SQLstate.startsWith("08") 
          && SQLstate != "08C04" 
          && SQLstate != "08C03" 
          && SQLstate != "08001"
          && SQLstate != "08003"
          && SQLstate != "08006"
          && SQLstate != "08007"
          )
        return true;

      int vendor = ex.getErrorCode();
      if (vendor == VirtuosoException.DISCONNECTED
          || vendor == VirtuosoException.IOERROR
          || vendor == VirtuosoException.BADLOGIN
          || vendor == VirtuosoException.BADTAG
          || vendor == VirtuosoException.CLOSED
          || vendor == VirtuosoException.EOF
          || vendor == VirtuosoException.NOLICENCE
          || vendor == VirtuosoException.UNKNOWN)
        return true;
      else
        return false;
    }

}

#ifdef SSL
class MyX509TrustManager implements X509TrustManager
{

  public boolean isClientTrusted(java.security.cert.X509Certificate[] chain)
    {
      return true;
    }

  public boolean isServerTrusted(java.security.cert.X509Certificate[] chain)
    {
      return true;
    }

#if JDK_VER < 14
  public java.security.cert.X509Certificate[] getAcceptedIssuers()
    {
      return null;
    }
#endif

#if JDK_VER >= 14
  /* JDK 1.4 fucntions */
  /**
   * note - ALLWAYS true - means no effective certificate check
   */
  public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
    {
    }
  /**
   * note - ALLWAYS true - means no effective certificate check
   */
  public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
    {
    }

  /**
   * note - empty CA list
   */
  public X509Certificate[] getAcceptedIssuers()
    {
      return null;
    }
#endif
}
#endif