-
Notifications
You must be signed in to change notification settings - Fork 33
/
CommDBManager.java
1614 lines (1377 loc) · 61.5 KB
/
CommDBManager.java
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
/*
* Copyright (c) 2000, 2020 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020 Payara Services Ltd.
* Copyright (c) 2021, 2022 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.messaging.jmq.jmsserver.persist.jdbc.comm;
import com.sun.messaging.jmq.io.MQAddress;
import com.sun.messaging.jmq.util.log.Logger;
import com.sun.messaging.jmq.util.StringUtil;
import com.sun.messaging.jmq.util.Password;
import com.sun.messaging.jmq.jmsserver.util.*;
import com.sun.messaging.jmq.jmsserver.config.*;
import com.sun.messaging.jmq.jmsserver.Globals;
import com.sun.messaging.jmq.jmsserver.resources.*;
import com.sun.messaging.jmq.jmsserver.persist.api.Store;
import com.sun.messaging.jmq.jmsserver.persist.jdbc.Util;
import com.sun.messaging.jmq.jmsserver.BrokerStateHandler;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.net.*;
import java.lang.reflect.*;
import javax.sql.*;
/**
* A supper DB manager class to be used by different JDBC stores
*/
public abstract class CommDBManager {
private static final String JDBC_STORE_TYPE = Store.JDBC_STORE_TYPE;
private static final String TABLEOPTION_NAME_VARIABLE = "tableoption";
private static final String TABLE_NAME_VARIABLE = "name";
private static final String INDEX_NAME_VARIABLE = "index";
private static final String LOGIN_TIMEOUT_PROP_SUFFIX = ".loginTimeout";
private static final String TRANSACTION_RETRY_MAX_PROP_SUFFIX = ".transaction.retry.max";
private static final String TRANSACTION_RETRY_DELAY_PROP_SUFFIX = ".transaction.retry.delay";
public static final int TRANSACTION_RETRY_MAX_DEFAULT = 5;
public static final long TRANSACTION_RETRY_DELAY_DEFAULT = 2000;
private static final int CONNECTION_RETRY_MAX_DEFAULT = 60;
private static final long CONNECTION_RETRY_DELAY_DEFAULT = 5000; // millisec
private static final String CONNECTION_RETRY_MAX_PROP_SUFFIX = ".connection.retry.max";
private static final String CONNECTION_RETRY_DELAY_PROP_SUFFIX = ".connection.retry.delay";
private static final String CONNECTION_RETRY_REGEX_PROP_SUFFIX = ".connection.retry.regex";
private static final String SQL_RETRIABLE_ERROR_CODES_PROP_SUFFIX = ".sqlRetriableErrorCodes";
protected static final String VENDOR_PROP_SUFFIX = ".dbVendor";
protected static final String FALLBACK_USER_PROP_SUFFIX = ".user";
protected static final String FALLBACK_PWD_PROP_SUFFIX = ".password";
private static final String USE_DERIVEDTABLE_FOR_UNIONSUBQUERIES_SUFFIX = ".useDerivedTableForUnionSubQueries";
private static final String UNKNOWN_VENDOR = "unknown";
private static final boolean DEFAULT_NEEDPASSWORD = false;
private String vendor = null;
private String vendorPropPrefix = null;
private String tablePropPrefix = null;
private String vendorProp = null;
private String driverProp = null;
private String openDBUrlProp = null;
private String createDBUrlProp = null;
private String closeDBUrlProp = null;
private String userProp = null;
private String passwordProp = null;
private String needPasswordProp = null;
public int txnRetryMax; // Max number of retry
public long txnRetryDelay; // Number of milliseconds to wait between retry
public int connRetryMax = CONNECTION_RETRY_MAX_DEFAULT;
public long connRetryDelay = CONNECTION_RETRY_DELAY_DEFAULT;
// database connection
private String driver = null;
private String openDBUrl = null;
private String createDBUrl = null;
protected String closeDBUrl = null;
private String user = null;
private String password = null;
private boolean isDataSource = false;
private boolean isPoolDataSource = false;
private Object dataSource = null;
protected boolean isOracle = false;
protected boolean isOraDriver = false;
protected boolean isMysql = false;
private boolean isDerby = false;
private boolean isDB2 = false;
private boolean isPostgreSQL = false;
private boolean supportBatch = false;
private boolean supportGetGeneratedKey = false;
private String dbProductName = null;
private String dbProductVersion = null;
private int dbProductMajorVersion = -1;
private int sqlStateType = DatabaseMetaData.sqlStateSQL99;
private boolean useDerivedTableForUnionSubQueries = false;
protected String tableSuffix = null;
protected BrokerConfig config = Globals.getConfig();
protected BrokerResources br = Globals.getBrokerResources();
protected Logger logger = Globals.getLogger();
private boolean isJDBC4 = true;
private boolean isClosing = false;
// HashMap of database tables. table name->TableSchema
protected HashMap tableSchemas = new HashMap();
private ArrayList<String> reconnectPatterns = new ArrayList<>();
private static final String DEFAULT_CONNECTION_RETRY_PATTERN = "(?s).*";
private ArrayList<Integer> sqlRetriableErrorCodes = new ArrayList<>();
private Integer loginTimeout = null;
protected void initDBMetaData() throws BrokerException {
int maxTableNameLength = 0;
Connection conn = null;
Exception myex = null;
try {
conn = getConnection(true);
DatabaseMetaData dbMetaData = conn.getMetaData();
dbProductName = dbMetaData.getDatabaseProductName();
dbProductVersion = dbMetaData.getDatabaseProductVersion();
dbProductMajorVersion = dbMetaData.getDatabaseMajorVersion();
supportBatch = dbMetaData.supportsBatchUpdates();
sqlStateType = dbMetaData.getSQLStateType();
maxTableNameLength = dbMetaData.getMaxTableNameLength();
String driverv = dbMetaData.getDriverVersion();
supportGetGeneratedKey = dbMetaData.supportsGetGeneratedKeys();
// Check to see if we're using an Oracle driver so
// we know how to deal w/ Oracle LOB handling!
isOraDriver = "oracle".equalsIgnoreCase(dbProductName);
String logMsg = new StringBuilder(256).append(getLogStringTag() + "DBManager: database product name=").append(dbProductName)
.append(", database version number=").append(dbProductVersion).append(", driver version number=").append(driverv)
.append(", supports batch updates=").append(supportBatch).append(", supports getGeneratedKey=").append(supportGetGeneratedKey).toString();
logger.log(Logger.FORCE, getLogStringTag() + dbProductName + ", " + dbProductVersion + ", " + driverv);
logger.log((Store.getDEBUG() ? Logger.INFO : Logger.DEBUG), logMsg);
} catch (SQLException e) {
myex = e;
logger.log(Logger.WARNING, BrokerResources.X_GET_METADATA_FAILED, e);
} finally {
closeSQLObjects(null, null, conn, myex);
}
if (maxTableNameLength > 0) {
checkMaxTableNameLength(maxTableNameLength);
}
}
protected abstract boolean getDEBUG();
protected abstract boolean isStoreInited();
protected abstract String getLogStringTag();
protected abstract String getJDBCPropPrefix();
protected abstract String getStoreTypeProp();
protected abstract String getCreateStoreProp();
protected abstract boolean getCreateStorePropDefault();
protected abstract void checkMaxTableNameLength(int maxlenAllowed) throws BrokerException;
@Override
public String toString() {
return "CommDBManager";
}
protected boolean isJDBC4() {
return isJDBC4;
}
protected void setJDBC4(boolean b) {
isJDBC4 = b;
}
public String getOpenDBUrlProp() {
return openDBUrlProp;
}
public String getOpenDBUrl() {
return openDBUrl;
}
public String getVendorProp() {
return vendorProp;
}
public String getVendor() {
return vendor;
}
public List<String> getReconnectPatterns() {
return reconnectPatterns;
}
private ConfigListener cfgListener = new ConfigListener() {
@Override
public void validate(String name, String value) throws PropertyUpdateException {
if (name.equals(getJDBCPropPrefix() + CONNECTION_RETRY_DELAY_PROP_SUFFIX)) {
long v = -1L;
try {
v = Long.parseLong(value);
} catch (Exception e) {
throw new PropertyUpdateException(br.getString(BrokerResources.X_BAD_PROPERTY_VALUE, name + "=" + value), e);
}
if (v < 0L) {
throw new PropertyUpdateException(name + "=" + value);
}
}
}
@Override
public boolean update(String name, String value) {
BrokerConfig cfg = Globals.getConfig();
if (name.equals(getJDBCPropPrefix() + CONNECTION_RETRY_DELAY_PROP_SUFFIX)) {
connRetryDelay = cfg.getLongProperty(getJDBCPropPrefix() + CONNECTION_RETRY_DELAY_PROP_SUFFIX);
} else if (name.equals(getJDBCPropPrefix() + CONNECTION_RETRY_MAX_PROP_SUFFIX)) {
connRetryMax = cfg.getIntProperty(getJDBCPropPrefix() + CONNECTION_RETRY_MAX_PROP_SUFFIX);
}
return true;
}
};
protected void initDBManagerProps() throws BrokerException {
String JDBC_PROP_PREFIX = getJDBCPropPrefix();
String name = JDBC_PROP_PREFIX + USE_DERIVEDTABLE_FOR_UNIONSUBQUERIES_SUFFIX;
useDerivedTableForUnionSubQueries = config.getBooleanProperty(name, false);
if (useDerivedTableForUnionSubQueries) {
logger.log(logger.INFO, name + "=true");
}
name = JDBC_PROP_PREFIX + LOGIN_TIMEOUT_PROP_SUFFIX;
String strv = config.getProperty(name);
if (strv != null) {
try {
int v = Integer.parseInt(strv);
if (v < 0) {
String emsg = Globals.getBrokerResources().getKString(BrokerResources.X_BAD_PROPERTY_VALUE, name + "=" + strv);
throw new BrokerException(emsg);
}
loginTimeout = Integer.valueOf(v);
logger.log(logger.INFO, name + "=" + strv);
} catch (Exception e) {
if (e instanceof BrokerException) {
throw (BrokerException) e;
}
String emsg = Globals.getBrokerResources().getKString(BrokerResources.X_BAD_PROPERTY_VALUE, name + "=" + strv) + ": " + e;
logger.log(Logger.ERROR, emsg, e);
throw new BrokerException(emsg);
}
}
txnRetryMax = config.getIntProperty(JDBC_PROP_PREFIX + TRANSACTION_RETRY_MAX_PROP_SUFFIX, TRANSACTION_RETRY_MAX_DEFAULT);
txnRetryDelay = config.getLongProperty(JDBC_PROP_PREFIX + TRANSACTION_RETRY_DELAY_PROP_SUFFIX, TRANSACTION_RETRY_DELAY_DEFAULT);
if (txnRetryDelay < 0L) {
txnRetryDelay = TRANSACTION_RETRY_DELAY_DEFAULT;
}
connRetryMax = config.getIntProperty(JDBC_PROP_PREFIX + CONNECTION_RETRY_MAX_PROP_SUFFIX, CONNECTION_RETRY_MAX_DEFAULT);
logger.log(logger.INFO, JDBC_PROP_PREFIX + CONNECTION_RETRY_MAX_PROP_SUFFIX + "=" + connRetryMax);
connRetryDelay = config.getLongProperty(JDBC_PROP_PREFIX + CONNECTION_RETRY_DELAY_PROP_SUFFIX, CONNECTION_RETRY_DELAY_DEFAULT);
if (connRetryDelay < 0L) {
connRetryDelay = CONNECTION_RETRY_DELAY_DEFAULT;
}
logger.log(logger.INFO, JDBC_PROP_PREFIX + JDBC_PROP_PREFIX + CONNECTION_RETRY_DELAY_PROP_SUFFIX + "=" + connRetryDelay);
Globals.getConfig().addListener(JDBC_PROP_PREFIX + CONNECTION_RETRY_MAX_PROP_SUFFIX, cfgListener);
Globals.getConfig().addListener(JDBC_PROP_PREFIX + CONNECTION_RETRY_DELAY_PROP_SUFFIX, cfgListener);
// get store type and double check that 'jdbc' is specified
String type = config.getProperty(getStoreTypeProp());
if (type == null || !type.equals(JDBC_STORE_TYPE)) {
type = (type == null ? "" : type);
throw new BrokerException(br.getKString(BrokerResources.E_NOT_JDBC_STORE_TYPE, getStoreTypeProp() + "=" + type, JDBC_STORE_TYPE));
}
vendorProp = JDBC_PROP_PREFIX + VENDOR_PROP_SUFFIX;
vendor = config.getProperty(vendorProp, UNKNOWN_VENDOR);
vendorPropPrefix = JDBC_PROP_PREFIX + "." + vendor;
tablePropPrefix = vendorPropPrefix + ".table";
// get jdbc driver property
driverProp = vendorPropPrefix + ".driver";
driver = config.getProperty(driverProp);
if (driver == null || (driver.length() == 0)) {
// try fallback prop
String fallbackProp = JDBC_PROP_PREFIX + ".driver";
driver = config.getProperty(fallbackProp);
if (driver == null || (driver.length() == 0)) {
throw new BrokerException(br.getKString(BrokerResources.E_NO_JDBC_DRIVER_PROP, driverProp));
}
driverProp = fallbackProp;
}
logger.log(logger.FORCE, driverProp + "=" + driver);
// get open database url property (optional for DataSource)
openDBUrlProp = vendorPropPrefix + ".opendburl";
openDBUrl = config.getProperty(openDBUrlProp);
if (openDBUrl == null || (openDBUrl.length() == 0)) {
// try fallback prop
String fallbackProp = JDBC_PROP_PREFIX + ".opendburl";
openDBUrl = config.getProperty(fallbackProp);
if (openDBUrl != null && openDBUrl.trim().length() > 0) {
openDBUrlProp = fallbackProp;
}
}
openDBUrl = StringUtil.expandVariables(openDBUrl, config);
if (openDBUrl != null) {
logger.log(logger.FORCE, openDBUrlProp + "=" + openDBUrl);
}
//
// optional properties
//
// get create database url property
createDBUrlProp = vendorPropPrefix + ".createdburl";
createDBUrl = config.getProperty(createDBUrlProp);
if (createDBUrl == null || (createDBUrl.length() == 0)) {
// try fallback prop
String fallbackProp = JDBC_PROP_PREFIX + ".createdburl";
createDBUrl = config.getProperty(fallbackProp);
if (createDBUrl != null) {
createDBUrlProp = fallbackProp;
}
}
createDBUrl = StringUtil.expandVariables(createDBUrl, config);
if (createDBUrl != null) {
logger.log(logger.FORCE, createDBUrlProp + "=" + createDBUrl);
}
// get url to shutdown database
closeDBUrlProp = vendorPropPrefix + ".closedburl";
closeDBUrl = config.getProperty(closeDBUrlProp);
if (closeDBUrl == null || (closeDBUrl.length() == 0)) {
// try fallback prop
String fallbackProp = JDBC_PROP_PREFIX + ".closedburl";
closeDBUrl = config.getProperty(fallbackProp);
if (closeDBUrl != null) {
closeDBUrlProp = fallbackProp;
}
}
closeDBUrl = StringUtil.expandVariables(closeDBUrl, config);
if (closeDBUrl != null) {
logger.log(logger.FORCE, closeDBUrlProp + "=" + closeDBUrl);
}
// user name to open connection
userProp = vendorPropPrefix + ".user";
user = config.getProperty(userProp);
if (user == null) {
// try fallback prop
user = config.getProperty(JDBC_PROP_PREFIX + FALLBACK_USER_PROP_SUFFIX);
if (user != null) {
userProp = JDBC_PROP_PREFIX + FALLBACK_USER_PROP_SUFFIX;
}
}
String regex = vendorPropPrefix + CONNECTION_RETRY_REGEX_PROP_SUFFIX;
int i = 1;
String p = null;
String v = null;
while (true) {
p = regex + "." + i++;
v = config.getProperty(p);
if (v == null) {
break;
}
try {
"A".matches(v);
reconnectPatterns.add(v);
logger.log(logger.INFO, p + "=" + v);
} catch (Exception e) {
throw new BrokerException("[" + p + "=" + v + "]: " + e.toString(), e);
}
}
if (reconnectPatterns.size() == 0) {
reconnectPatterns.add(DEFAULT_CONNECTION_RETRY_PATTERN);
logger.log(logger.INFO, regex + "=" + DEFAULT_CONNECTION_RETRY_PATTERN);
}
String sqlRetriablesp = vendorPropPrefix + SQL_RETRIABLE_ERROR_CODES_PROP_SUFFIX;
String sqlRetriablesv = config.getProperty(sqlRetriablesp);
List<String> sqlRetriables = config.getList(sqlRetriablesp);
if (sqlRetriables != null && sqlRetriables.size() > 0) {
logger.log(logger.INFO, sqlRetriablesp + "=" + sqlRetriablesv);
Integer val = null;
for (String ecode : sqlRetriables) {
try {
val = Integer.valueOf(ecode);
sqlRetriableErrorCodes.add(val);
} catch (Exception e) {
String[] eargs = { ecode, sqlRetriablesp + "=" + sqlRetriablesv, e.toString() };
logger.log(logger.WARNING, br.getKString(br.W_IGNORE_VALUE_IN_PROPERTY_LIST, eargs));
}
}
}
initTableSuffix();
}
public boolean isRetriableSQLErrorCode(int errorCode) {
return sqlRetriableErrorCodes.contains(Integer.valueOf(errorCode));
}
protected abstract void initTableSuffix() throws BrokerException;
protected void initDBDriver() throws BrokerException {
String JDBC_PROP_PREFIX = getJDBCPropPrefix();
// load jdbc driver
try {
Class driverCls = null;
Object driverObj = null;
if (Globals.isNucleusManagedBroker()) {
driverObj = Globals.getHabitat().getService(DataSource.class, driver);
if (driverObj == null) {
driverObj = Globals.getHabitat().getService(ConnectionPoolDataSource.class, driver);
}
if (driverObj == null && isMysql()) {
driverObj = Globals.getHabitat().getService(java.sql.Driver.class, "com.mysql.jdbc.Driver");
}
if (driverObj == null) {
throw new ClassNotFoundException(driver);
}
driverCls = driverObj.getClass();
} else {
driverCls = Class.forName(driver);
driverObj = driverCls.getDeclaredConstructor().newInstance();
}
// Check if driver is a DataSource
if (driverObj instanceof ConnectionPoolDataSource) {
isDataSource = true;
isPoolDataSource = true;
} else if (driverObj instanceof DataSource) {
isDataSource = true;
} else {
// Not using DataSource make sure driver's url is specified
if (openDBUrl == null || (openDBUrl.length() == 0)) {
throw new BrokerException(br.getKString(BrokerResources.E_NO_DATABASE_URL_PROP, openDBUrlProp));
}
}
// Initialize DataSource properties
if (isDataSource) {
dataSource = driverObj;
initDataSource(driverCls, dataSource);
} else {
initDriverManager();
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException | NoSuchMethodException e) {
throw new BrokerException(br.getKString(BrokerResources.E_CANNOT_LOAD_JDBC_DRIVER, driver), e);
} catch (BrokerException e) {
throw e;
}
// password to open connection; do this last because we want to init
// the datasource to get the url that might be needed in getPassword()
password = getPassword();
// verify dbVendor is not unknown, i.e. upgrading from old store
if (UNKNOWN_VENDOR.equals(vendor)) {
// need to figure out the vendor
Connection conn = null;
String dbName = null;
try {
conn = getNewConnection(true);
DatabaseMetaData dbMetaData = conn.getMetaData();
dbName = dbMetaData.getDatabaseProductName();
} catch (Exception e) {
// Ignore error for now!
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
if ("oracle".equalsIgnoreCase(dbName)) {
vendor = "oracle";
vendorPropPrefix = JDBC_PROP_PREFIX + "." + vendor;
tablePropPrefix = vendorPropPrefix + ".table";
} else {
throw new BrokerException(br.getKString(BrokerResources.E_NO_DATABASE_VENDOR_PROP, getJDBCPropPrefix() + VENDOR_PROP_SUFFIX));
}
}
if (vendor.equalsIgnoreCase("oracle")) {
isOracle = true;
} else if (vendor.equalsIgnoreCase("mysql")) {
isMysql = true;
} else if (vendor.equalsIgnoreCase("derby")) {
isDerby = true;
} else if (vendor.equalsIgnoreCase("postgresql")) {
isPostgreSQL = true;
} else if (vendor.equalsIgnoreCase("db2")) {
isDB2 = true;
}
}
public boolean isUseDerivedTableForUnionSubQueries() {
return useDerivedTableForUnionSubQueries;
}
public boolean isPoolDataSource() {
return isPoolDataSource;
}
public Hashtable getDebugState() {
Hashtable ht = new Hashtable();
ht.put("vendor", "" + vendor);
ht.put("user", "" + user);
ht.put("isDataSource", Boolean.valueOf(isDataSource));
ht.put("isPoolDataSource", Boolean.valueOf(isPoolDataSource));
ht.put("supportBatch", Boolean.valueOf(supportBatch));
ht.put("supportGetGeneratedKey", Boolean.valueOf(supportGetGeneratedKey));
ht.put("sqlStateType", String.valueOf(sqlStateType));
ht.put("isJDBC4", Boolean.valueOf(isJDBC4));
return ht;
}
public TableSchema getTableSchema(String tableName) throws BrokerException {
HashMap schemas = getTableSchemas();
TableSchema tableSchema = (TableSchema) schemas.get(tableName);
if (tableSchema == null || tableSchema.tableSQL.length() == 0) {
throw new BrokerException(br.getKString(BrokerResources.E_NO_JDBC_TABLE_PROP, tableName, getJDBCPropPrefix() + VENDOR_PROP_SUFFIX));
}
return tableSchema;
}
public abstract boolean hasSupplementForCreateDrop(String tableName);
protected void createTableSupplement(Statement stmt, TableSchema tableSchema, String tableName) throws BrokerException {
String sql = tableSchema.afterCreateSQL;
if (sql == null) {
return;
}
logger.logToAll(Logger.INFO, br.getKString(br.I_EXEC_CREATE_TABLE_SUPPLEMENT, sql, tableName));
try {
int cnt = executeUpdateStatement(stmt, sql);
if (cnt != 0 || stmt.getWarnings() != null) {
String emsg = "[" + sql + "]: " + stmt.getWarnings() + "(return=" + cnt + ")";
logger.log(logger.ERROR, emsg);
throw new BrokerException(emsg);
}
} catch (Throwable t) {
if (t instanceof BrokerException) {
throw (BrokerException) t;
}
String emsg = "[" + sql + "]: " + t.getMessage();
logger.logStack(logger.ERROR, emsg, t);
throw new BrokerException(emsg);
}
}
/**
* subclass must override this if not no-op
*/
public void dropOldTableSupplement(Statement stmt, String oldTableName, boolean throwException) throws BrokerException {
}
public void dropTableSupplement(Statement stmt, TableSchema tableSchema, String tableName, boolean throwException) throws BrokerException {
String sql = tableSchema.afterDropSQL;
if (sql == null) {
return;
}
logger.logToAll(Logger.INFO, br.getKString(br.I_EXEC_DROP_TABLE_SUPPLEMENT, sql, tableName));
try {
int cnt = executeUpdateStatement(stmt, sql);
if (cnt != 0 || stmt.getWarnings() != null) {
String emsg = "[" + sql + "]: " + stmt.getWarnings() + "(return=" + cnt + ")";
throw new BrokerException(emsg);
}
} catch (Throwable t) {
BrokerException ex = null;
if (t instanceof BrokerException) {
ex = (BrokerException) t;
} else {
String emsg = "[" + sql + "]: " + t.getMessage();
ex = new BrokerException(emsg);
}
if (throwException) {
logger.logStack(logger.WARNING, ex.getMessage(), t);
throw ex;
}
logger.log(logger.INFO, ex.getMessage());
}
}
/**
* Get a database connection using the CREATEDB_URL.
*/
public Connection connectToCreate() throws BrokerException {
if (createDBUrl == null) {
throw new BrokerException(br.getKString(BrokerResources.E_NO_DATABASE_URL_PROP, createDBUrlProp));
}
// make database connection
Connection conn = null;
try {
if (user == null) {
conn = DriverManager.getConnection(createDBUrl);
} else {
conn = DriverManager.getConnection(createDBUrl, user, password);
}
conn.setAutoCommit(false);
} catch (SQLException e) {
if (conn != null) {
try {
conn.close();
} catch (SQLException sqe) {
logger.logStack(Logger.WARNING, "Unable to close JDBC connection: " + sqe + " after SQLException ", e);
}
}
throw new BrokerException(br.getKString(BrokerResources.E_CANNOT_GET_DB_CONNECTION, createDBUrl), e);
}
return conn;
}
/**
* Create a new database connection either from the DataSource or the DriverManager using the OPENDB_URL.
*/
public Connection getNewConnection(boolean autocommit) throws BrokerException {
Object c = newConnection(true);
if (c instanceof PooledConnection) {
final PooledConnection pc = (PooledConnection) c;
pc.addConnectionEventListener(new ConnectionEventListener() {
@Override
public void connectionClosed(ConnectionEvent event) {
pc.removeConnectionEventListener(this);
try {
pc.close();
} catch (Exception e) {
logger.log(logger.WARNING,
br.getKString(br.W_DB_CONN_CLOSE_EXCEPTION, pc.getClass().getName() + "[0x" + pc.hashCode() + "]", e.toString()));
}
}
@Override
public void connectionErrorOccurred(ConnectionEvent event) {
logger.log(logger.WARNING, br.getKString(br.W_DB_CONN_ERROR_EVENT, "0x" + pc.hashCode(), "" + event.getSQLException()));
pc.removeConnectionEventListener(this);
try {
pc.close();
} catch (Exception e) {
logger.log(logger.WARNING,
br.getKString(br.W_DB_CONN_CLOSE_EXCEPTION, pc.getClass().getName() + "[0x" + pc.hashCode() + "]", e.toString()));
}
}
});
}
try {
Util.RetryStrategy retry = null;
do {
try {
Connection conn = null;
if (c instanceof PooledConnection) {
conn = ((PooledConnection) c).getConnection();
} else {
conn = (Connection) c;
}
conn.setAutoCommit(autocommit);
return conn;
} catch (Exception e) {
BrokerException ex = new BrokerException(e.getMessage(), e);
if (retry == null) {
retry = new Util.RetryStrategy(this);
}
retry.assertShouldRetry(ex);
}
} while (true);
} catch (BrokerException e) {
try {
if (c instanceof PooledConnection) {
((PooledConnection) c).close();
} else {
((Connection) c).close();
}
} catch (Throwable t) {
logger.log(Logger.WARNING, br.getKString(br.W_DB_CONN_CLOSE_EXCEPTION, c.getClass().getName() + "[0x" + c.hashCode() + "]", t.toString()));
}
throw e;
}
}
protected Object getNewConnection() throws BrokerException {
return newConnection(false);
}
protected Object newConnection(boolean doRetry) throws BrokerException {
// make database connection; database should already exist
Util.RetryStrategy retry = null;
do {
try {
try {
Object conn = null;
if (dataSource != null) {
if (isPoolDataSource) {
if (user == null) {
conn = ((ConnectionPoolDataSource) dataSource).getPooledConnection();
} else {
conn = ((ConnectionPoolDataSource) dataSource).getPooledConnection(user, password);
}
} else {
if (user == null) {
conn = ((DataSource) dataSource).getConnection();
} else {
conn = ((DataSource) dataSource).getConnection(user, password);
}
}
} else {
if (user == null) {
conn = DriverManager.getConnection(openDBUrl);
} else {
conn = DriverManager.getConnection(openDBUrl, user, password);
}
}
return conn;
} catch (Exception e) {
throw new BrokerException(br.getKString(BrokerResources.E_CANNOT_GET_DB_CONNECTION, openDBUrl), e);
}
} catch (BrokerException e) {
if (!doRetry) {
throw e;
}
// Exception will be log & re-throw if operation cannot be retry
if (retry == null) {
retry = new Util.RetryStrategy(this, connRetryDelay, connRetryMax, true);
}
retry.assertShouldRetry(e);
}
} while (true);
}
public Connection getConnection(boolean autocommit) throws BrokerException {
Util.RetryStrategy retry = null;
do {
try {
Connection conn = getConnectionNoRetry(autocommit);
return conn;
} catch (BrokerException e) {
if (BrokerStateHandler.isStoreShutdownStage1()) {
throw e;
}
// Exception will be log & re-throw if operation cannot be retry
if (retry == null) {
retry = new Util.RetryStrategy(this, connRetryDelay, connRetryMax, true);
}
retry.assertShouldRetry(e);
}
} while (true);
}
/**
*/
public Connection getConnectionNoRetry(boolean autocommit) throws BrokerException {
Exception exception = null;
Connection conn = getConnection();
try {
// Set connection behavior
try {
conn.setAutoCommit(autocommit);
} catch (SQLException e) {
exception = e;
throw new BrokerException(br.getKString(BrokerResources.X_INTERNAL_EXCEPTION, "Unable to set connection's auto-commit mode"), e);
}
} finally {
if (exception != null) {
freeConnection(conn, exception);
}
}
return conn;
}
protected abstract Connection getConnection() throws BrokerException;
public abstract void freeConnection(Connection conn, Throwable thr) throws BrokerException;
protected abstract BaseDAO getFirstDAO() throws BrokerException;
public void setIsClosing() {
isClosing = true;
}
public boolean getIsClosing() {
return isClosing;
}
protected void close() {
// Use closeDBUrl to close embedded db
if (closeDBUrl != null) {
Connection conn = null;
try {
conn = DriverManager.getConnection(closeDBUrl);
} catch (SQLException e) {
if (Store.getDEBUG()) {
logger.log(Logger.DEBUG, getLogStringTag() + BrokerResources.I_DATABASE_SHUTDOWN, closeDBUrl, e);
}
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
/* ignore */
}
}
}
}
}
public boolean supportsBatchUpdates() {
return supportBatch;
}
public boolean supportsGetGeneratedKey() {
return supportGetGeneratedKey;
}
public boolean isMysql() {
return isMysql;
}
public boolean isDerby() {
return isDerby;
}
public boolean isDB2() {
return isDB2;
}
public boolean isPostgreSQL() {
return isPostgreSQL;
}
public boolean isOracle() {
return isOracle;
}
public boolean isOracleDriver() {
return isOraDriver;
}
public int getDBProductMajorVersion() {
return dbProductMajorVersion;
}
public int getSQLStateType() {
return sqlStateType;
}
public String getOpenDBURL() {
return openDBUrl;
}
public String getCreateDBURL() {
return createDBUrl;
}
public String getUser() {
return user;
}
public String getClusterID() {
return Globals.getClusterID();
}
public String getTableName(String tableNamePrefix) {
if (tableNamePrefix == null || tableNamePrefix.length() == 0) {
throw new NullPointerException();
}
return tableNamePrefix + tableSuffix;
}
public String getTableSuffix() {
return tableSuffix;
}
/**
* subclass must override this if this method is used
*/
public String[] getAllOldTableNames() {
return new String[0];
}
public abstract String[] getTableNames(int version);
public String getDriver() {
return driver;
}
public abstract Iterator allDAOIterator() throws BrokerException;
// get table schema for the current store version returns a Hashtable with
// table names map to the create table SQL
HashMap getTableSchemas() {
return tableSchemas;
}
public abstract int checkStoreExists(Connection conn) throws BrokerException;
// Return 0 if store has not been created, -1 if some tables are missing, or
// a value > 0 if all tables for the store have already been created
protected int checkStoreExists(Connection conn, String version) throws BrokerException {
Map tables = getTableNamesFromDB(conn, (version == null ? tableSuffix : (version + tableSuffix)), true);
int total = 0;
int found = 0;
Iterator itr = allDAOIterator();
StringBuilder sbuf = new StringBuilder();
while (itr.hasNext()) {
total++;
String tname = ((BaseDAO) itr.next()).getTableName();
if (tables.containsKey(tname.toLowerCase())) {
found++;
} else {
sbuf.append(tname + " ");
}
}
if ((found > 0) && (found != total)) {
logger.log(logger.WARNING, br.getKString(br.W_TABLE_NOT_FOUND_IN_DATABASE, sbuf.toString() + "[" + total + "," + found + ", " + tableSuffix + "]"));
return -1; // There is a problem! some tables are missing
} else {
return found;
}
}
// Get all table names from the db that matchs the specified name pattern .
// If name pattern is not specified then use tableSuffix for this broker.
// As a precaution, only get table that starts with "mq" or "MQ".
public Map getTableNamesFromDB(Connection conn, String namePattern, boolean isSuffix) throws BrokerException {
// If name pattern not specified then use the table suffix
if (namePattern == null || namePattern.trim().length() == 0) {
namePattern = tableSuffix;
isSuffix = true;