Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
hostDescription:
* - simple :
* {@code :}
* (for example localhost:3306)
*
* - complex :
* {@code address=[(type=(master|slave))][(port=)](host=)}
*
*
* type is by default master
* port is by default 3306
*
*
host can be dns name, ipv4 or ipv6.
* in case of ipv6 and simple host description, the ip must be written inside bracket.
* exemple : {@code jdbc:mariadb://[2001:0660:7401:0200:0000:0000:0edf:bdd7]:3306}
*
*
Some examples :
* {@code jdbc:mariadb://localhost:3306/database?user=greg&password=pass}
* {@code
* jdbc:mariadb://address=(type=master)(host=master1),address=(port=3307)(type=slave)(host=slave1)/database?user=greg&password=pass}
*
*/
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 addresses = null;
private HaMode haMode = HaMode.NONE;
private String initialUrl = null;
private Properties nonMappedOptions = null;
// various
private String timezone = null;
private String connectionCollation = null;
private String connectionTimeZone = null;
private Boolean forceConnectionTimeZoneToSession = null;
private boolean preserveInstants;
private Boolean autocommit = null;
private boolean useMysqlMetadata = false;
private boolean nullDatabaseMeansCurrent = false;
private CatalogTerm useCatalogTerm = CatalogTerm.UseCatalog;
private boolean createDatabaseIfNotExist = false;
private boolean useLocalSessionState = false;
private boolean returnMultiValuesGeneratedIds = false;
private boolean jdbcCompliantTruncation = true;
private boolean permitRedirect = true;
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;
private boolean pinGlobalTxToPhysicalConnection = false;
// 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 trustStore = null;
private String keyStorePassword = null;
private String trustStorePassword = null;
private String keyPassword = null;
private String keyStoreType = null;
private String trustStoreType = null;
private String enabledSslCipherSuites = null;
private String enabledSslProtocolSuites = null;
private boolean fallbackToSystemKeyStore = true;
private boolean fallbackToSystemTrustStore = true;
// protocol
private boolean allowMultiQueries = false;
private boolean allowLocalInfile = true;
private boolean useCompression = false;
private boolean useAffectedRows = false;
private boolean useBulkStmts = false;
private boolean useBulkStmtsForInserts = 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 addresses,
HaMode haMode,
Properties nonMappedOptions,
String timezone,
String connectionTimeZone,
String connectionCollation,
boolean forceConnectionTimeZoneToSession,
boolean preserveInstants,
Boolean autocommit,
boolean useMysqlMetadata,
boolean nullDatabaseMeansCurrent,
CatalogTerm useCatalogTerm,
boolean createDatabaseIfNotExist,
boolean useLocalSessionState,
boolean returnMultiValuesGeneratedIds,
boolean jdbcCompliantTruncation,
boolean permitRedirect,
boolean pinGlobalTxToPhysicalConnection,
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 trustStore,
String keyStorePassword,
String trustStorePassword,
String keyPassword,
String keyStoreType,
String trustStoreType,
String enabledSslCipherSuites,
String enabledSslProtocolSuites,
boolean fallbackToSystemKeyStore,
boolean fallbackToSystemTrustStore,
boolean allowMultiQueries,
boolean allowLocalInfile,
boolean useCompression,
boolean useAffectedRows,
boolean useBulkStmts,
boolean useBulkStmtsForInserts,
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.connectionTimeZone = connectionTimeZone;
this.connectionCollation = connectionCollation;
this.forceConnectionTimeZoneToSession = forceConnectionTimeZoneToSession;
this.preserveInstants = preserveInstants;
this.autocommit = autocommit;
this.useMysqlMetadata = useMysqlMetadata;
this.nullDatabaseMeansCurrent = nullDatabaseMeansCurrent;
this.useCatalogTerm = useCatalogTerm;
this.createDatabaseIfNotExist = createDatabaseIfNotExist;
this.returnMultiValuesGeneratedIds = returnMultiValuesGeneratedIds;
this.jdbcCompliantTruncation = jdbcCompliantTruncation;
this.permitRedirect = permitRedirect;
this.pinGlobalTxToPhysicalConnection = pinGlobalTxToPhysicalConnection;
this.useLocalSessionState = useLocalSessionState;
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.trustStore = trustStore;
this.keyStorePassword = keyStorePassword;
this.trustStorePassword = trustStorePassword;
this.keyPassword = keyPassword;
this.keyStoreType = keyStoreType;
this.trustStoreType = trustStoreType;
this.enabledSslCipherSuites = enabledSslCipherSuites;
this.enabledSslProtocolSuites = enabledSslProtocolSuites;
this.fallbackToSystemKeyStore = fallbackToSystemKeyStore;
this.fallbackToSystemTrustStore = fallbackToSystemTrustStore;
this.allowMultiQueries = allowMultiQueries;
this.allowLocalInfile = allowLocalInfile;
this.useCompression = useCompression;
this.useAffectedRows = useAffectedRows;
this.useBulkStmts = useBulkStmts;
this.useBulkStmtsForInserts = useBulkStmtsForInserts;
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 addresses,
HaMode haMode,
String user,
String password,
String enabledSslProtocolSuites,
Boolean fallbackToSystemKeyStore,
Boolean fallbackToSystemTrustStore,
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,
String connectionTimeZone,
String connectionCollation,
Boolean forceConnectionTimeZoneToSession,
Boolean preserveInstants,
Boolean dumpQueriesOnException,
Integer prepStmtCacheSize,
Boolean useAffectedRows,
Boolean useServerPrepStmts,
String connectionAttributes,
Boolean useBulkStmts,
Boolean useBulkStmtsForInserts,
Boolean disablePipeline,
Boolean autocommit,
Boolean useMysqlMetadata,
Boolean nullDatabaseMeansCurrent,
String useCatalogTerm,
Boolean createDatabaseIfNotExist,
Boolean useLocalSessionState,
Boolean returnMultiValuesGeneratedIds,
Boolean jdbcCompliantTruncation,
Boolean permitRedirect,
Boolean pinGlobalTxToPhysicalConnection,
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 trustStore,
String keyStorePassword,
String trustStorePassword,
String keyPassword,
String keyStoreType,
String trustStoreType,
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;
if (fallbackToSystemKeyStore != null) this.fallbackToSystemKeyStore = fallbackToSystemKeyStore;
if (fallbackToSystemTrustStore != null)
this.fallbackToSystemTrustStore = fallbackToSystemTrustStore;
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 (connectionTimeZone != null) this.connectionTimeZone = connectionTimeZone;
if (connectionCollation != null) this.connectionCollation = connectionCollation;
if (forceConnectionTimeZoneToSession != null)
this.forceConnectionTimeZoneToSession = forceConnectionTimeZoneToSession;
if (preserveInstants != null) this.preserveInstants = preserveInstants;
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 (useBulkStmtsForInserts != null) {
this.useBulkStmtsForInserts = useBulkStmtsForInserts;
} else if (useBulkStmts != null) {
this.useBulkStmtsForInserts = useBulkStmts;
}
if (disablePipeline != null) this.disablePipeline = disablePipeline;
if (autocommit != null) this.autocommit = autocommit;
if (useMysqlMetadata != null) this.useMysqlMetadata = useMysqlMetadata;
if (nullDatabaseMeansCurrent != null) this.nullDatabaseMeansCurrent = nullDatabaseMeansCurrent;
if (useCatalogTerm != null) {
if (!"CATALOG".equalsIgnoreCase(useCatalogTerm)
&& !"SCHEMA".equalsIgnoreCase(useCatalogTerm)) {
throw new IllegalArgumentException(
"useCatalogTerm can only have CATALOG/SCHEMA value, current set value is "
+ useCatalogTerm);
}
this.useCatalogTerm =
"CATALOG".equalsIgnoreCase(useCatalogTerm)
? CatalogTerm.UseCatalog
: CatalogTerm.UseSchema;
}
if (createDatabaseIfNotExist != null) this.createDatabaseIfNotExist = createDatabaseIfNotExist;
if (useLocalSessionState != null) this.useLocalSessionState = useLocalSessionState;
if (returnMultiValuesGeneratedIds != null)
this.returnMultiValuesGeneratedIds = returnMultiValuesGeneratedIds;
if (jdbcCompliantTruncation != null) this.jdbcCompliantTruncation = jdbcCompliantTruncation;
if (permitRedirect != null) this.permitRedirect = permitRedirect;
if (pinGlobalTxToPhysicalConnection != null)
this.pinGlobalTxToPhysicalConnection = pinGlobalTxToPhysicalConnection;
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.isEmpty() ? null : 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 (trustStore != null) this.trustStore = trustStore;
if (keyStorePassword != null) this.keyStorePassword = keyStorePassword;
if (trustStorePassword != null) this.trustStorePassword = trustStorePassword;
if (keyPassword != null) this.keyPassword = keyPassword;
if (keyStoreType != null) this.keyStoreType = keyStoreType;
if (trustStoreType != null) this.trustStoreType = trustStoreType;
// *************************************************************
// hosts
// *************************************************************
if (addresses.isEmpty()) {
if (this.localSocket != null) {
addresses.add(HostAddress.localSocket(this.localSocket));
} else if (this.pipe != null) {
addresses.add(HostAddress.pipe(this.pipe));
}
} else {
if (this.localSocket != null) {
List newAddresses = new ArrayList<>();
for (HostAddress host : addresses) {
newAddresses.add(host.withLocalSocket(this.localSocket));
}
this.addresses = newAddresses;
}
if (this.pipe != null) {
List newAddresses = new ArrayList<>();
for (HostAddress host : addresses) {
newAddresses.add(host.withPipe(this.pipe));
}
this.addresses = newAddresses;
}
}
// *************************************************************
// 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;
}
// *************************************************************
// timezone verification
// *************************************************************
if (this.timezone != null) {
if (this.connectionTimeZone == null) {
if ("disable".equalsIgnoreCase(this.timezone)) {
this.forceConnectionTimeZoneToSession = false;
} else {
this.forceConnectionTimeZoneToSession = true;
if (!"auto".equalsIgnoreCase(this.timezone)) {
this.connectionTimeZone = this.timezone;
}
}
}
}
// *************************************************************
// option value verification
// *************************************************************
// ensure connection collation format
if (connectionCollation != null) {
if ("".equals(connectionCollation.trim())) {
this.connectionCollation = null;
} else {
// ensure this is an utf8mb4 collation
if (!connectionCollation.toLowerCase(Locale.ROOT).startsWith("utf8mb4_")) {
throw new SQLException(
String.format(
"wrong connection collation '%s' only utf8mb4 collation are accepted",
connectionCollation));
} else if (!connectionCollation.matches("^[a-zA-Z0-9_]+$")) {
throw new SQLException(
String.format("wrong connection collation '%s' name", connectionCollation));
}
}
}
// 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
}
}
/**
* Create a Builder from current configuration. Since configuration data are final, this permit to
* change configuration, creating another object.
*
* @return builder
*/
public Builder toBuilder() {
Builder builder =
new Builder()
.user(this.user)
.password(this.password)
.database(this.database)
.addresses(this.addresses == null ? null : this.addresses.toArray(new HostAddress[0]))
.haMode(this.haMode)
.timezone(this.timezone)
.connectionTimeZone(this.connectionTimeZone)
.connectionCollation(this.connectionCollation)
.forceConnectionTimeZoneToSession(this.forceConnectionTimeZoneToSession)
.preserveInstants(this.preserveInstants)
.autocommit(this.autocommit)
.useMysqlMetadata(this.useMysqlMetadata)
.nullDatabaseMeansCurrent(this.nullDatabaseMeansCurrent)
.useCatalogTerm(this.useCatalogTerm == CatalogTerm.UseCatalog ? "CATALOG" : "SCHEMA")
.createDatabaseIfNotExist(this.createDatabaseIfNotExist)
.useLocalSessionState(this.useLocalSessionState)
.returnMultiValuesGeneratedIds(this.returnMultiValuesGeneratedIds)
.jdbcCompliantTruncation(this.jdbcCompliantTruncation)
.permitRedirect(this.permitRedirect)
.pinGlobalTxToPhysicalConnection(this.pinGlobalTxToPhysicalConnection)
.transactionIsolation(
transactionIsolation == null ? null : this.transactionIsolation.getValue())
.defaultFetchSize(this.defaultFetchSize)
.maxQuerySizeToLog(this.maxQuerySizeToLog)
.maxAllowedPacket(this.maxAllowedPacket)
.geometryDefaultType(this.geometryDefaultType)
.geometryDefaultType(this.geometryDefaultType)
.restrictedAuth(this.restrictedAuth)
.initSql(this.initSql)
.socketFactory(this.socketFactory)
.connectTimeout(this.connectTimeout)
.pipe(this.pipe)
.localSocket(this.localSocket)
.uuidAsString(this.uuidAsString)
.tcpKeepAlive(this.tcpKeepAlive)
.tcpKeepIdle(this.tcpKeepIdle)
.tcpKeepCount(this.tcpKeepCount)
.tcpKeepInterval(this.tcpKeepInterval)
.tcpAbortiveClose(this.tcpAbortiveClose)
.localSocketAddress(this.localSocketAddress)
.socketTimeout(this.socketTimeout)
.useReadAheadInput(this.useReadAheadInput)
.tlsSocketType(this.tlsSocketType)
.sslMode(this.sslMode.name())
.serverSslCert(this.serverSslCert)
.keyStore(this.keyStore)
.trustStore(this.trustStore)
.keyStoreType(this.keyStoreType)
.keyStorePassword(this.keyStorePassword)
.trustStorePassword(this.trustStorePassword)
.keyPassword(this.keyPassword)
.trustStoreType(this.trustStoreType)
.enabledSslCipherSuites(this.enabledSslCipherSuites)
.enabledSslProtocolSuites(this.enabledSslProtocolSuites)
.fallbackToSystemKeyStore(this.fallbackToSystemKeyStore)
.fallbackToSystemTrustStore(this.fallbackToSystemTrustStore)
.allowMultiQueries(this.allowMultiQueries)
.allowLocalInfile(this.allowLocalInfile)
.useCompression(this.useCompression)
.useAffectedRows(this.useAffectedRows)
.useBulkStmts(this.useBulkStmts)
.useBulkStmtsForInserts(this.useBulkStmtsForInserts)
.disablePipeline(this.disablePipeline)
.cachePrepStmts(this.cachePrepStmts)
.prepStmtCacheSize(this.prepStmtCacheSize)
.useServerPrepStmts(this.useServerPrepStmts)
.credentialType(this.credentialType == null ? null : this.credentialType.type())
.sessionVariables(this.sessionVariables)
.connectionAttributes(this.connectionAttributes)
.servicePrincipalName(this.servicePrincipalName)
.blankTableNameMeta(this.blankTableNameMeta)
.tinyInt1isBit(this.tinyInt1isBit)
.transformedBitIsBoolean(this.transformedBitIsBoolean)
.yearIsDateType(this.yearIsDateType)
.dumpQueriesOnException(this.dumpQueriesOnException)
.includeInnodbStatusInDeadlockExceptions(this.includeInnodbStatusInDeadlockExceptions)
.includeThreadDumpInDeadlockExceptions(this.includeThreadDumpInDeadlockExceptions)
.retriesAllDown(this.retriesAllDown)
.galeraAllowedState(this.galeraAllowedState)
.transactionReplay(this.transactionReplay)
.transactionReplaySize(this.transactionReplaySize)
.pool(this.pool)
.poolName(this.poolName)
.maxPoolSize(this.maxPoolSize)
.minPoolSize(this.minPoolSize)
.maxIdleTime(this.maxIdleTime)
.registerJmxPool(this.registerJmxPool)
.poolValidMinDelay(this.poolValidMinDelay)
.useResetConnection(this.useResetConnection)
.serverRsaPublicKeyFile(this.serverRsaPublicKeyFile)
.allowPublicKeyRetrieval(this.allowPublicKeyRetrieval);
builder._nonMappedOptions = this.nonMappedOptions;
return builder;
}
/**
* 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 skipPos;
int posToSkip = 0;
while ((skipPos = urlSecondPart.indexOf("address=(", posToSkip)) > -1) {
posToSkip = urlSecondPart.indexOf(")", skipPos) + 1;
while (urlSecondPart.startsWith("(", posToSkip)) {
int endingBraceIndex = urlSecondPart.indexOf(")", posToSkip);
if (endingBraceIndex == -1) break;
posToSkip = endingBraceIndex + 1;
}
}
int dbIndex = urlSecondPart.indexOf("/", posToSkip);
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.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);
}
}
/**
* Permit to have string information on how string is parsed. example :
* Configuration.toConf("jdbc:mariadb://localhost/test") will return a String containing:
* Configuration:
* * resulting Url : jdbc:mariadb://localhost/test
* Unknown options : None
*
* Non default options :
* * database : test
*
* default options :
* * user : null
* ...
*
*
* @param url url string
* @return string describing the configuration parsed from url
* @throws SQLException if parsing fails
*/
public static String toConf(String url) throws SQLException {
Configuration conf = Configuration.parseInternal(url, new Properties());
StringBuilder sb = new StringBuilder();
StringBuilder sbUnknownOpts = new StringBuilder();
if (conf.nonMappedOptions.isEmpty()) {
sbUnknownOpts.append("None");
} else {
for (Map.Entry