-
Notifications
You must be signed in to change notification settings - Fork 219
/
Configuration.java
2690 lines (2471 loc) · 77.9 KB
/
Configuration.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
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2012-2014 Monty Program Ab
// Copyright (c) 2015-2021 MariaDB Corporation Ab
package org.mariadb.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;
import org.mariadb.jdbc.export.HaMode;
import org.mariadb.jdbc.export.SslMode;
import org.mariadb.jdbc.plugin.Codec;
import org.mariadb.jdbc.plugin.CredentialPlugin;
import org.mariadb.jdbc.plugin.credential.CredentialPluginLoader;
import org.mariadb.jdbc.util.log.Logger;
import org.mariadb.jdbc.util.log.Loggers;
import org.mariadb.jdbc.util.options.OptionAliases;
/**
* parse and verification of URL.
*
* <p>basic syntax :<br>
* {@code
* jdbc:mariadb:[replication:|failover|loadbalance:|aurora:]//<hostDescription>[,<hostDescription>]/[database>]
* [?<key1>=<value1>[&<key2>=<value2>]] }
*
* <p>hostDescription:<br>
* - simple :<br>
* {@code <host>:<portnumber>}<br>
* (for example localhost:3306)<br>
* <br>
* - complex :<br>
* {@code address=[(type=(master|slave))][(port=<portnumber>)](host=<host>)}<br>
* <br>
* <br>
* type is by default master<br>
* port is by default 3306<br>
*
* <p>host can be dns name, ipv4 or ipv6.<br>
* in case of ipv6 and simple host description, the ip must be written inside bracket.<br>
* exemple : {@code jdbc:mariadb://[2001:0660:7401:0200:0000:0000:0edf:bdd7]:3306}<br>
*
* <p>Some examples :<br>
* {@code jdbc:mariadb://localhost:3306/database?user=greg&password=pass}<br>
* {@code
* jdbc:mariadb://address=(type=master)(host=master1),address=(port=3307)(type=slave)(host=slave1)/database?user=greg&password=pass}
* <br>
*/
public class Configuration {
private static final Logger logger = Loggers.getLogger(Configuration.class);
// standard options
private String user = null;
private String password = null;
private String database = null;
private List<HostAddress> addresses = null;
private HaMode haMode = HaMode.NONE;
private String initialUrl = null;
private Properties nonMappedOptions = null;
// various
private String timezone = null;
private Boolean autocommit = null;
private boolean useMysqlMetadata = false;
private boolean createDatabaseIfNotExist = false;
private TransactionIsolation transactionIsolation = null;
private int defaultFetchSize = 0;
private int maxQuerySizeToLog = 1024;
private Integer maxAllowedPacket = null;
private String geometryDefaultType = null;
private String restrictedAuth = null;
private String initSql = null;
// socket
private String socketFactory = null;
private int connectTimeout =
DriverManager.getLoginTimeout() > 0 ? DriverManager.getLoginTimeout() * 1000 : 30_000;
private String pipe = null;
private String localSocket = null;
private boolean uuidAsString = false;
private boolean tcpKeepAlive = true;
private int tcpKeepIdle = 0;
private int tcpKeepCount = 0;
private int tcpKeepInterval = 0;
private boolean tcpAbortiveClose = false;
private String localSocketAddress = null;
private int socketTimeout = 0;
private boolean useReadAheadInput = false;
private String tlsSocketType = null;
// SSL
private SslMode sslMode = SslMode.DISABLE;
private String serverSslCert = null;
private String keyStore = null;
private String keyStorePassword = null;
private String keyStoreType = null;
private String enabledSslCipherSuites = null;
private String enabledSslProtocolSuites = null;
// protocol
private boolean allowMultiQueries = false;
private boolean allowLocalInfile = true;
private boolean useCompression = false;
private boolean useAffectedRows = false;
private boolean useBulkStmts = true;
private boolean disablePipeline = false;
// prepare
private boolean cachePrepStmts = true;
private int prepStmtCacheSize = 250;
private boolean useServerPrepStmts = false;
// authentication
private CredentialPlugin credentialType = null;
private String sessionVariables = null;
private String connectionAttributes = null;
private String servicePrincipalName = null;
// meta
private boolean blankTableNameMeta = false;
private boolean tinyInt1isBit = true;
private boolean transformedBitIsBoolean = true;
private boolean yearIsDateType = true;
private boolean dumpQueriesOnException = false;
private boolean includeInnodbStatusInDeadlockExceptions = false;
private boolean includeThreadDumpInDeadlockExceptions = false;
// HA options
private int retriesAllDown = 120;
private String galeraAllowedState = null;
private boolean transactionReplay = false;
private int transactionReplaySize = 64;
// Pool options
private boolean pool = false;
private String poolName = null;
private int maxPoolSize = 8;
private int minPoolSize = 8;
private int maxIdleTime = 600_000;
private boolean registerJmxPool = true;
private int poolValidMinDelay = 1000;
private boolean useResetConnection = false;
// MySQL sha authentication
private String serverRsaPublicKeyFile = null;
private boolean allowPublicKeyRetrieval = false;
private Codec<?>[] codecs = null;
private Configuration() {}
private Configuration(
String user,
String password,
String database,
List<HostAddress> addresses,
HaMode haMode,
Properties nonMappedOptions,
String timezone,
Boolean autocommit,
boolean useMysqlMetadata,
boolean createDatabaseIfNotExist,
TransactionIsolation transactionIsolation,
int defaultFetchSize,
int maxQuerySizeToLog,
Integer maxAllowedPacket,
String geometryDefaultType,
String restrictedAuth,
String initSql,
String socketFactory,
int connectTimeout,
String pipe,
String localSocket,
boolean tcpKeepAlive,
boolean uuidAsString,
int tcpKeepIdle,
int tcpKeepCount,
int tcpKeepInterval,
boolean tcpAbortiveClose,
String localSocketAddress,
int socketTimeout,
boolean useReadAheadInput,
String tlsSocketType,
SslMode sslMode,
String serverSslCert,
String keyStore,
String keyStorePassword,
String keyStoreType,
String enabledSslCipherSuites,
String enabledSslProtocolSuites,
boolean allowMultiQueries,
boolean allowLocalInfile,
boolean useCompression,
boolean useAffectedRows,
boolean useBulkStmts,
boolean disablePipeline,
boolean cachePrepStmts,
int prepStmtCacheSize,
boolean useServerPrepStmts,
CredentialPlugin credentialType,
String sessionVariables,
String connectionAttributes,
String servicePrincipalName,
boolean blankTableNameMeta,
boolean tinyInt1isBit,
boolean transformedBitIsBoolean,
boolean yearIsDateType,
boolean dumpQueriesOnException,
boolean includeInnodbStatusInDeadlockExceptions,
boolean includeThreadDumpInDeadlockExceptions,
int retriesAllDown,
String galeraAllowedState,
boolean transactionReplay,
int transactionReplaySize,
boolean pool,
String poolName,
int maxPoolSize,
int minPoolSize,
int maxIdleTime,
boolean registerJmxPool,
int poolValidMinDelay,
boolean useResetConnection,
String serverRsaPublicKeyFile,
boolean allowPublicKeyRetrieval) {
this.user = user;
this.password = password;
this.database = database;
this.addresses = addresses;
this.haMode = haMode;
this.nonMappedOptions = nonMappedOptions;
this.timezone = timezone;
this.autocommit = autocommit;
this.useMysqlMetadata = useMysqlMetadata;
this.createDatabaseIfNotExist = createDatabaseIfNotExist;
this.transactionIsolation = transactionIsolation;
this.defaultFetchSize = defaultFetchSize;
this.maxQuerySizeToLog = maxQuerySizeToLog;
this.maxAllowedPacket = maxAllowedPacket;
this.geometryDefaultType = geometryDefaultType;
this.restrictedAuth = restrictedAuth;
this.initSql = initSql;
this.socketFactory = socketFactory;
this.connectTimeout = connectTimeout;
this.pipe = pipe;
this.localSocket = localSocket;
this.tcpKeepAlive = tcpKeepAlive;
this.uuidAsString = uuidAsString;
this.tcpKeepIdle = tcpKeepIdle;
this.tcpKeepCount = tcpKeepCount;
this.tcpKeepInterval = tcpKeepInterval;
this.tcpAbortiveClose = tcpAbortiveClose;
this.localSocketAddress = localSocketAddress;
this.socketTimeout = socketTimeout;
this.useReadAheadInput = useReadAheadInput;
this.tlsSocketType = tlsSocketType;
this.sslMode = sslMode;
this.serverSslCert = serverSslCert;
this.keyStore = keyStore;
this.keyStorePassword = keyStorePassword;
this.keyStoreType = keyStoreType;
this.enabledSslCipherSuites = enabledSslCipherSuites;
this.enabledSslProtocolSuites = enabledSslProtocolSuites;
this.allowMultiQueries = allowMultiQueries;
this.allowLocalInfile = allowLocalInfile;
this.useCompression = useCompression;
this.useAffectedRows = useAffectedRows;
this.useBulkStmts = useBulkStmts;
this.disablePipeline = disablePipeline;
this.cachePrepStmts = cachePrepStmts;
this.prepStmtCacheSize = prepStmtCacheSize;
this.useServerPrepStmts = useServerPrepStmts;
this.credentialType = credentialType;
this.sessionVariables = sessionVariables;
this.connectionAttributes = connectionAttributes;
this.servicePrincipalName = servicePrincipalName;
this.blankTableNameMeta = blankTableNameMeta;
this.tinyInt1isBit = tinyInt1isBit;
this.transformedBitIsBoolean = transformedBitIsBoolean;
this.yearIsDateType = yearIsDateType;
this.dumpQueriesOnException = dumpQueriesOnException;
this.includeInnodbStatusInDeadlockExceptions = includeInnodbStatusInDeadlockExceptions;
this.includeThreadDumpInDeadlockExceptions = includeThreadDumpInDeadlockExceptions;
this.retriesAllDown = retriesAllDown;
this.galeraAllowedState = galeraAllowedState;
this.transactionReplay = transactionReplay;
this.transactionReplaySize = transactionReplaySize;
this.pool = pool;
this.poolName = poolName;
this.maxPoolSize = maxPoolSize;
this.minPoolSize = minPoolSize;
this.maxIdleTime = maxIdleTime;
this.registerJmxPool = registerJmxPool;
this.poolValidMinDelay = poolValidMinDelay;
this.useResetConnection = useResetConnection;
this.serverRsaPublicKeyFile = serverRsaPublicKeyFile;
this.allowPublicKeyRetrieval = allowPublicKeyRetrieval;
this.initialUrl = buildUrl(this);
}
private Configuration(
String database,
List<HostAddress> addresses,
HaMode haMode,
String user,
String password,
String enabledSslProtocolSuites,
String socketFactory,
Integer connectTimeout,
String pipe,
String localSocket,
Boolean tcpKeepAlive,
Boolean uuidAsString,
Integer tcpKeepIdle,
Integer tcpKeepCount,
Integer tcpKeepInterval,
Boolean tcpAbortiveClose,
String localSocketAddress,
Integer socketTimeout,
Boolean allowMultiQueries,
Boolean allowLocalInfile,
Boolean useCompression,
Boolean blankTableNameMeta,
String credentialType,
String sslMode,
String transactionIsolation,
String enabledSslCipherSuites,
String sessionVariables,
Boolean tinyInt1isBit,
Boolean transformedBitIsBoolean,
Boolean yearIsDateType,
String timezone,
Boolean dumpQueriesOnException,
Integer prepStmtCacheSize,
Boolean useAffectedRows,
Boolean useServerPrepStmts,
String connectionAttributes,
Boolean useBulkStmts,
Boolean disablePipeline,
Boolean autocommit,
Boolean useMysqlMetadata,
Boolean createDatabaseIfNotExist,
Boolean includeInnodbStatusInDeadlockExceptions,
Boolean includeThreadDumpInDeadlockExceptions,
String servicePrincipalName,
Integer defaultFetchSize,
String tlsSocketType,
Integer maxQuerySizeToLog,
Integer maxAllowedPacket,
Integer retriesAllDown,
String galeraAllowedState,
Boolean pool,
String poolName,
Integer maxPoolSize,
Integer minPoolSize,
Integer maxIdleTime,
Boolean registerJmxPool,
Integer poolValidMinDelay,
Boolean useResetConnection,
String serverRsaPublicKeyFile,
Boolean allowPublicKeyRetrieval,
String serverSslCert,
String keyStore,
String keyStorePassword,
String keyStoreType,
Boolean useReadAheadInput,
Boolean cachePrepStmts,
Boolean transactionReplay,
Integer transactionReplaySize,
String geometryDefaultType,
String restrictedAuth,
String initSql,
Properties nonMappedOptions)
throws SQLException {
this.database = database;
this.addresses = addresses;
this.nonMappedOptions = nonMappedOptions;
if (haMode != null) this.haMode = haMode;
this.credentialType = CredentialPluginLoader.get(credentialType);
this.user = user;
this.password = password;
this.enabledSslProtocolSuites = enabledSslProtocolSuites;
this.socketFactory = socketFactory;
if (connectTimeout != null) this.connectTimeout = connectTimeout;
this.pipe = pipe;
this.localSocket = localSocket;
if (tcpKeepAlive != null) this.tcpKeepAlive = tcpKeepAlive;
if (uuidAsString != null) this.uuidAsString = uuidAsString;
if (tcpKeepIdle != null) this.tcpKeepIdle = tcpKeepIdle;
if (tcpKeepCount != null) this.tcpKeepCount = tcpKeepCount;
if (tcpKeepInterval != null) this.tcpKeepInterval = tcpKeepInterval;
if (tcpAbortiveClose != null) this.tcpAbortiveClose = tcpAbortiveClose;
this.localSocketAddress = localSocketAddress;
if (socketTimeout != null) this.socketTimeout = socketTimeout;
if (allowMultiQueries != null) this.allowMultiQueries = allowMultiQueries;
if (allowLocalInfile != null) this.allowLocalInfile = allowLocalInfile;
if (useCompression != null) this.useCompression = useCompression;
if (blankTableNameMeta != null) this.blankTableNameMeta = blankTableNameMeta;
if (this.credentialType != null
&& this.credentialType.mustUseSsl()
&& (sslMode == null || SslMode.from(sslMode) == SslMode.DISABLE)) {
this.sslMode = SslMode.VERIFY_FULL;
} else {
this.sslMode = sslMode != null ? SslMode.from(sslMode) : SslMode.DISABLE;
}
if (transactionIsolation != null)
this.transactionIsolation = TransactionIsolation.from(transactionIsolation);
this.enabledSslCipherSuites = enabledSslCipherSuites;
this.sessionVariables = sessionVariables;
if (tinyInt1isBit != null) this.tinyInt1isBit = tinyInt1isBit;
if (transformedBitIsBoolean != null) this.transformedBitIsBoolean = transformedBitIsBoolean;
if (yearIsDateType != null) this.yearIsDateType = yearIsDateType;
this.timezone = timezone;
if (dumpQueriesOnException != null) this.dumpQueriesOnException = dumpQueriesOnException;
if (prepStmtCacheSize != null) this.prepStmtCacheSize = prepStmtCacheSize;
if (useAffectedRows != null) this.useAffectedRows = useAffectedRows;
if (useServerPrepStmts != null) this.useServerPrepStmts = useServerPrepStmts;
this.connectionAttributes = connectionAttributes;
if (useBulkStmts != null) this.useBulkStmts = useBulkStmts;
if (disablePipeline != null) this.disablePipeline = disablePipeline;
if (autocommit != null) this.autocommit = autocommit;
if (useMysqlMetadata != null) this.useMysqlMetadata = useMysqlMetadata;
if (createDatabaseIfNotExist != null) this.createDatabaseIfNotExist = createDatabaseIfNotExist;
if (includeInnodbStatusInDeadlockExceptions != null)
this.includeInnodbStatusInDeadlockExceptions = includeInnodbStatusInDeadlockExceptions;
if (includeThreadDumpInDeadlockExceptions != null)
this.includeThreadDumpInDeadlockExceptions = includeThreadDumpInDeadlockExceptions;
if (servicePrincipalName != null) this.servicePrincipalName = servicePrincipalName;
if (defaultFetchSize != null) this.defaultFetchSize = defaultFetchSize;
if (tlsSocketType != null) this.tlsSocketType = tlsSocketType;
if (maxQuerySizeToLog != null) this.maxQuerySizeToLog = maxQuerySizeToLog;
if (maxAllowedPacket != null) this.maxAllowedPacket = maxAllowedPacket;
if (retriesAllDown != null) this.retriesAllDown = retriesAllDown;
if (galeraAllowedState != null) this.galeraAllowedState = galeraAllowedState;
if (pool != null) this.pool = pool;
if (poolName != null) this.poolName = poolName;
if (maxPoolSize != null) this.maxPoolSize = maxPoolSize;
// if min pool size default to maximum pool size if not set
if (minPoolSize != null) {
this.minPoolSize = minPoolSize;
} else {
this.minPoolSize = this.maxPoolSize;
}
if (maxIdleTime != null) this.maxIdleTime = maxIdleTime;
if (registerJmxPool != null) this.registerJmxPool = registerJmxPool;
if (poolValidMinDelay != null) this.poolValidMinDelay = poolValidMinDelay;
if (useResetConnection != null) this.useResetConnection = useResetConnection;
if (serverRsaPublicKeyFile != null) this.serverRsaPublicKeyFile = serverRsaPublicKeyFile;
if (allowPublicKeyRetrieval != null) this.allowPublicKeyRetrieval = allowPublicKeyRetrieval;
if (useReadAheadInput != null) this.useReadAheadInput = useReadAheadInput;
if (cachePrepStmts != null) this.cachePrepStmts = cachePrepStmts;
if (transactionReplay != null) this.transactionReplay = transactionReplay;
if (transactionReplaySize != null) this.transactionReplaySize = transactionReplaySize;
if (geometryDefaultType != null) this.geometryDefaultType = geometryDefaultType;
if (restrictedAuth != null) this.restrictedAuth = restrictedAuth;
if (initSql != null) this.initSql = initSql;
if (serverSslCert != null) this.serverSslCert = serverSslCert;
if (keyStore != null) this.keyStore = keyStore;
if (keyStorePassword != null) this.keyStorePassword = keyStorePassword;
if (keyStoreType != null) this.keyStoreType = keyStoreType;
// *************************************************************
// host primary check
// *************************************************************
boolean first = true;
for (HostAddress host : addresses) {
boolean primary = haMode != HaMode.REPLICATION || first;
if (host.primary == null) {
host.primary = primary;
}
first = false;
}
// *************************************************************
// option value verification
// *************************************************************
// int fields must all be positive
Field[] fields = Configuration.class.getDeclaredFields();
try {
for (Field field : fields) {
if (field.getType().equals(int.class)) {
int val = field.getInt(this);
if (val < 0) {
throw new SQLException(
String.format("Value for %s must be >= 1 (value is %s)", field.getName(), val));
}
}
}
} catch (IllegalArgumentException | IllegalAccessException ie) {
// eat
}
}
/**
* Tell if mariadb driver accept url string. (Correspond to interface
* java.jdbc.Driver.acceptsURL() method)
*
* @param url url String
* @return true if url string correspond.
*/
public static boolean acceptsUrl(String url) {
return url != null
&& (url.startsWith("jdbc:mariadb:")
|| (url.startsWith("jdbc:mysql:") && url.contains("permitMysqlScheme")));
}
/**
* parse connection string
*
* @param url connection string
* @return configuration resulting object
* @throws SQLException if not supported driver or wrong connection string format.
*/
public static Configuration parse(final String url) throws SQLException {
return parse(url, new Properties());
}
/**
* Parse url connection string with additional properties.
*
* @param url connection string
* @param prop properties
* @return UrlParser instance
* @throws SQLException if parsing exception occur
*/
public static Configuration parse(final String url, Properties prop) throws SQLException {
if (acceptsUrl(url)) {
return parseInternal(url, (prop == null) ? new Properties() : prop);
}
return null;
}
/**
* Parses the connection URL in order to set the UrlParser instance with all the information
* provided through the URL.
*
* @param url connection URL
* @param properties properties
* @throws SQLException if format is incorrect
*/
private static Configuration parseInternal(String url, Properties properties)
throws SQLException {
try {
Builder builder = new Builder();
int separator = url.indexOf("//");
if (separator == -1) {
throw new IllegalArgumentException(
"url parsing error : '//' is not present in the url " + url);
}
builder.haMode(parseHaMode(url, separator));
String urlSecondPart = url.substring(separator + 2);
int dbIndex = urlSecondPart.indexOf("/");
int paramIndex = urlSecondPart.indexOf("?");
String hostAddressesString;
String additionalParameters;
if ((dbIndex < paramIndex && dbIndex < 0) || (dbIndex > paramIndex && paramIndex > -1)) {
hostAddressesString = urlSecondPart.substring(0, paramIndex);
additionalParameters = urlSecondPart.substring(paramIndex);
} else if (dbIndex < paramIndex || dbIndex > paramIndex) {
hostAddressesString = urlSecondPart.substring(0, dbIndex);
additionalParameters = urlSecondPart.substring(dbIndex);
} else {
hostAddressesString = urlSecondPart;
additionalParameters = null;
}
if (additionalParameters != null) {
int optIndex = additionalParameters.indexOf("?");
String database;
if (optIndex < 0) {
database = (additionalParameters.length() > 1) ? additionalParameters.substring(1) : null;
} else {
if (optIndex == 0) {
database = null;
} else {
database = additionalParameters.substring(1, optIndex);
if (database.isEmpty()) database = null;
}
String urlParameters = additionalParameters.substring(optIndex + 1);
if (urlParameters != null && !urlParameters.isEmpty()) {
String[] parameters = urlParameters.split("&");
for (String parameter : parameters) {
int pos = parameter.indexOf('=');
if (pos == -1) {
properties.setProperty(parameter, "");
} else {
properties.setProperty(parameter.substring(0, pos), parameter.substring(pos + 1));
}
}
}
}
builder.database(database);
} else {
builder.database(null);
}
mapPropertiesToOption(builder, properties);
builder._addresses = HostAddress.parse(hostAddressesString, builder._haMode);
return builder.build();
} catch (IllegalArgumentException i) {
throw new SQLException("error parsing url : " + i.getMessage(), i);
}
}
private static void mapPropertiesToOption(Builder builder, Properties properties) {
Properties nonMappedOptions = new Properties();
try {
// Option object is already initialized to default values.
// loop on properties,
// - check DefaultOption to check that property value correspond to type (and range)
// - set values
for (final Object keyObj : properties.keySet()) {
String realKey =
OptionAliases.OPTIONS_ALIASES.get(keyObj.toString().toLowerCase(Locale.ROOT));
if (realKey == null) realKey = keyObj.toString();
final Object propertyValue = properties.get(keyObj);
if (propertyValue != null && realKey != null) {
boolean used = false;
for (Field field : Builder.class.getDeclaredFields()) {
if (realKey.toLowerCase(Locale.ROOT).equals(field.getName().toLowerCase(Locale.ROOT))) {
field.setAccessible(true);
used = true;
if (field.getGenericType().equals(String.class)
&& !propertyValue.toString().isEmpty()) {
field.set(builder, propertyValue);
} else if (field.getGenericType().equals(Boolean.class)) {
switch (propertyValue.toString().toLowerCase()) {
case "":
case "1":
case "true":
field.set(builder, Boolean.TRUE);
break;
case "0":
case "false":
field.set(builder, Boolean.FALSE);
break;
default:
throw new IllegalArgumentException(
String.format(
"Optional parameter %s must be boolean (true/false or 0/1) was '%s'",
keyObj, propertyValue));
}
} else if (field.getGenericType().equals(Integer.class)) {
try {
final Integer value = Integer.parseInt(propertyValue.toString());
field.set(builder, value);
} catch (NumberFormatException n) {
throw new IllegalArgumentException(
String.format(
"Optional parameter %s must be Integer, was '%s'",
keyObj, propertyValue));
}
}
}
}
if (!used) nonMappedOptions.put(realKey, propertyValue);
}
}
// for compatibility with 2.x
if (isSet("useSsl", nonMappedOptions) || isSet("useSSL", nonMappedOptions)) {
Properties deprecatedDesc = new Properties();
try (InputStream inputStream =
Driver.class.getClassLoader().getResourceAsStream("deprecated.properties")) {
deprecatedDesc.load(inputStream);
} catch (IOException io) {
// eat
}
logger.warn(deprecatedDesc.getProperty("useSsl"));
if (isSet("trustServerCertificate", nonMappedOptions)) {
builder.sslMode("trust");
logger.warn(deprecatedDesc.getProperty("trustServerCertificate"));
} else if (isSet("disableSslHostnameVerification", nonMappedOptions)) {
logger.warn(deprecatedDesc.getProperty("disableSslHostnameVerification"));
builder.sslMode("verify-ca");
} else {
builder.sslMode("verify-full");
}
}
} catch (IllegalAccessException | SecurityException s) {
throw new IllegalArgumentException("Unexpected error", s);
}
builder._nonMappedOptions = nonMappedOptions;
}
private static boolean isSet(String key, Properties nonMappedOptions) {
String value = nonMappedOptions.getProperty(key);
return value != null && (value.equals("1") || value.equals("true") || value.isEmpty());
}
private static HaMode parseHaMode(String url, int separator) {
// parser is sure to have at least 2 colon, since jdbc:[mysql|mariadb]: is tested.
int firstColonPos = url.indexOf(':');
int secondColonPos = url.indexOf(':', firstColonPos + 1);
int thirdColonPos = url.indexOf(':', secondColonPos + 1);
if (thirdColonPos > separator || thirdColonPos == -1) {
if (secondColonPos == separator - 1) {
return HaMode.NONE;
}
thirdColonPos = separator;
}
try {
String haModeString = url.substring(secondColonPos + 1, thirdColonPos);
if ("FAILOVER".equalsIgnoreCase(haModeString)) {
haModeString = "LOADBALANCE";
}
return HaMode.from(haModeString);
} catch (IllegalArgumentException i) {
throw new IllegalArgumentException(
"wrong failover parameter format in connection String " + url);
}
}
/**
* Clone configuration with another user/password
*
* @param username new username
* @param password new password
* @return new cloned configuration object
*/
public Configuration clone(String username, String password) {
return new Configuration(
username != null && username.isEmpty() ? null : username,
password != null && password.isEmpty() ? null : password,
this.database,
this.addresses,
this.haMode,
this.nonMappedOptions,
this.timezone,
this.autocommit,
this.useMysqlMetadata,
this.createDatabaseIfNotExist,
this.transactionIsolation,
this.defaultFetchSize,
this.maxQuerySizeToLog,
this.maxAllowedPacket,
this.geometryDefaultType,
this.restrictedAuth,
this.initSql,
this.socketFactory,
this.connectTimeout,
this.pipe,
this.localSocket,
this.tcpKeepAlive,
this.uuidAsString,
this.tcpKeepIdle,
this.tcpKeepCount,
this.tcpKeepInterval,
this.tcpAbortiveClose,
this.localSocketAddress,
this.socketTimeout,
this.useReadAheadInput,
this.tlsSocketType,
this.sslMode,
this.serverSslCert,
this.keyStore,
this.keyStorePassword,
this.keyStoreType,
this.enabledSslCipherSuites,
this.enabledSslProtocolSuites,
this.allowMultiQueries,
this.allowLocalInfile,
this.useCompression,
this.useAffectedRows,
this.useBulkStmts,
this.disablePipeline,
this.cachePrepStmts,
this.prepStmtCacheSize,
this.useServerPrepStmts,
this.credentialType,
this.sessionVariables,
this.connectionAttributes,
this.servicePrincipalName,
this.blankTableNameMeta,
this.tinyInt1isBit,
this.transformedBitIsBoolean,
this.yearIsDateType,
this.dumpQueriesOnException,
this.includeInnodbStatusInDeadlockExceptions,
this.includeThreadDumpInDeadlockExceptions,
this.retriesAllDown,
this.galeraAllowedState,
this.transactionReplay,
this.transactionReplaySize,
this.pool,
this.poolName,
this.maxPoolSize,
this.minPoolSize,
this.maxIdleTime,
this.registerJmxPool,
this.poolValidMinDelay,
this.useResetConnection,
this.serverRsaPublicKeyFile,
this.allowPublicKeyRetrieval);
}
/**
* Connection default database
*
* @return database
*/
public String database() {
return database;
}
/**
* addresses
*
* @return addresses
*/
public List<HostAddress> addresses() {
return addresses;
}
/**
* High availability mode
*
* @return configuration HA mode
*/
public HaMode haMode() {
return haMode;
}
/**
* credential plugin to use
*
* @return credential plugin to use, null of none
*/
public CredentialPlugin credentialPlugin() {
return credentialType;
}
/**
* configuration user
*
* @return user
*/
public String user() {
return user;
}
/**
* configuration password
*
* @return password
*/
public String password() {
return password;
}
/**
* Configuration generated URL depending on current configuration option. Password will be hidden
* by "***"
*
* @return generated url
*/
public String initialUrl() {
return initialUrl;
}
/**
* server ssl certificate (file path / certificat content)
*
* @return server ssl certificate
*/
public String serverSslCert() {
return serverSslCert;
}
/**
* key store
*
* @return key store
*/
public String keyStore() {
return keyStore;
}
/**
* key store password
*
* @return key store password
*/
public String keyStorePassword() {
return keyStorePassword;
}
/**
* key store type (to replace default javax.net.ssl.keyStoreType system property)
*
* @return key store type
*/
public String keyStoreType() {
return keyStoreType;
}
/**
* permitted ssl protocol list (comma separated)
*
* @return enabled ssl protocol list
*/
public String enabledSslProtocolSuites() {
return enabledSslProtocolSuites;
}
/**
* Socket factory class name
*
* @return socket factory
*/
public String socketFactory() {
return socketFactory;
}
/**
* socket connect timeout
*
* @return connect timeout
*/
public int connectTimeout() {
return connectTimeout;
}
/**
* Set connect timeout
*
* @param connectTimeout timeout value
* @return current configuration
*/
public Configuration connectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* Pipe path
*
* @return pipe value
*/
public String pipe() {
return pipe;
}
/**
* local socket configuration
*
* @return local socket path
*/
public String localSocket() {
return localSocket;
}
/**
* socket tcp keep alive
*
* @return socket tcp keep alive value
*/
public boolean tcpKeepAlive() {
return tcpKeepAlive;
}
/**
* must uuid fields return as String and not java.util.UUID
*
* @return must UUID return as String and not uuid
*/
public boolean uuidAsString() {
return uuidAsString;
}
/**
* socket tcp keep idle (java 11+ only)
*
* @return socket tcp keep idle
*/
public int tcpKeepIdle() {
return tcpKeepIdle;
}
/**
* socket tcp keep count (java 11+ only)
*
* @return socket tcp keep count
*/
public int tcpKeepCount() {
return tcpKeepCount;
}