Skip to content

Commit

Permalink
misc - code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
rusher committed Apr 16, 2021
1 parent 57dd43b commit db9de26
Show file tree
Hide file tree
Showing 99 changed files with 376 additions and 696 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@
<plugin>
<groupId>com.coveo</groupId>
<artifactId>fmt-maven-plugin</artifactId>
<version>2.10</version>
<version>2.9.1</version>
<executions>
<execution>
<goals>
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/org/mariadb/jdbc/BaseCallableStatement.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,10 @@

public abstract class BaseCallableStatement extends ServerPreparedStatement
implements CallableStatement {
protected final String sql;
protected final String databaseName;
protected final String procedureName;
protected CallableParameterMetaData parameterMetaData = null;
protected Set<Integer> outputParameters = new HashSet<>();
protected final Set<Integer> outputParameters = new HashSet<>();
protected Result outputResult = null;

public BaseCallableStatement(
Expand All @@ -48,7 +47,6 @@ public BaseCallableStatement(
resultSetType,
resultSetConcurrency,
defaultFetchSize);
this.sql = sql;
this.databaseName = databaseName;
this.procedureName = procedureName;
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/mariadb/jdbc/BasePreparedStatement.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public abstract class BasePreparedStatement extends Statement implements Prepare
private static final CodecList codecList = CodecLoader.get();
protected ParameterList parameters;
protected List<ParameterList> batchParameters;
protected String sql;
protected final String sql;
protected PrepareResultPacket prepareResult = null;

public BasePreparedStatement(
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/mariadb/jdbc/ClientPreparedStatement.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import org.mariadb.jdbc.util.constants.ServerStatus;

public class ClientPreparedStatement extends BasePreparedStatement {
private ClientParser parser;
private final ClientParser parser;

public ClientPreparedStatement(
String sql,
Expand Down Expand Up @@ -318,7 +318,7 @@ public void addBatch() throws SQLException {

protected void validParameters() throws SQLException {
for (int i = 0; i < parser.getParamCount(); i++) {
if (!parameters.containsKey(i)) {
if (parameters.containsKey(i)) {
throw exceptionFactory()
.create("Parameter at position " + (i + 1) + " is not set", "07004");
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/mariadb/jdbc/Configuration.java
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ private static Configuration parseInternal(String url, Properties properties)
if ((dbIndex < paramIndex && dbIndex < 0) || (dbIndex > paramIndex && paramIndex > -1)) {
hostAddressesString = urlSecondPart.substring(0, paramIndex);
additionalParameters = urlSecondPart.substring(paramIndex);
} else if (dbIndex < paramIndex || dbIndex > paramIndex && paramIndex < 0) {
} else if (dbIndex < paramIndex || dbIndex > paramIndex) {
hostAddressesString = urlSecondPart.substring(0, dbIndex);
additionalParameters = urlSecondPart.substring(dbIndex);
} else {
Expand Down Expand Up @@ -1030,7 +1030,7 @@ protected static String buildUrl(Configuration conf) {
sb.append(first ? '?' : '&');
first = false;
sb.append(field.getName()).append('=');
sb.append(((Boolean) obj).toString());
sb.append(obj);
}
} else if (field.getType().equals(int.class)) {
try {
Expand Down
11 changes: 3 additions & 8 deletions src/main/java/org/mariadb/jdbc/Connection.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,9 @@
import org.mariadb.jdbc.util.constants.ConnectionState;
import org.mariadb.jdbc.util.constants.ServerStatus;
import org.mariadb.jdbc.util.exceptions.ExceptionFactory;
import org.mariadb.jdbc.util.log.Logger;
import org.mariadb.jdbc.util.log.Loggers;

public class Connection implements java.sql.Connection {

private static final Logger logger = Loggers.getLogger(Connection.class);
private static final Pattern CALLABLE_STATEMENT_PATTERN =
Pattern.compile(
"^(\\s*\\{)?\\s*((\\?\\s*=)?(\\s*\\/\\*([^\\*]|\\*[^\\/])*\\*\\/)*\\s*"
Expand All @@ -38,8 +35,6 @@ public class Connection implements java.sql.Connection {
+ "\\s*(#.*)?)\\s*(\\}\\s*)?$",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private final ReentrantLock lock;
private final List<ConnectionEventListener> connectionEventListeners = new ArrayList<>();
private final List<StatementEventListener> statementEventListeners = new ArrayList<>();
private final Configuration conf;
private ExceptionFactory exceptionFactory;
private final Client client;
Expand All @@ -52,7 +47,7 @@ public class Connection implements java.sql.Connection {
private final int defaultFetchSize;
private MariaDbPoolConnection poolConnection;

public Connection(Configuration conf, ReentrantLock lock, Client client) throws SQLException {
public Connection(Configuration conf, ReentrantLock lock, Client client) {
this.conf = conf;
this.lock = lock;
this.exceptionFactory = client.getExceptionFactory().setConnection(this);
Expand Down Expand Up @@ -274,7 +269,7 @@ public String getCatalog() throws SQLException {
@Override
public void setCatalog(String catalog) throws SQLException {
if ((client.getContext().getServerCapabilities() & Capabilities.CLIENT_SESSION_TRACK) != 0
&& catalog == client.getContext().getDatabase()) {
&& catalog.equals(client.getContext().getDatabase())) {
return;
}
lock.lock();
Expand Down Expand Up @@ -719,7 +714,7 @@ public <T> T unwrap(Class<T> iface) throws SQLException {
}

@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
public boolean isWrapperFor(Class<?> iface) {
return iface.isInstance(this);
}

Expand Down
6 changes: 3 additions & 3 deletions src/main/java/org/mariadb/jdbc/DatabaseMetaData.java
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ public ResultSet getTables(
boolean mustAddType = false;
StringBuilder sqlType = new StringBuilder(" AND TABLE_TYPE IN (");
for (int i = 0; i < types.length; i++) {
if (mustAddType == true) sqlType.append(",");
if (mustAddType) sqlType.append(",");
mustAddType = true;
if (types[i] == null) {
mustAddType = false;
Expand Down Expand Up @@ -1160,7 +1160,7 @@ public String getDatabaseProductName() {
}

public String getDatabaseProductVersion() {
return connection.getContext().getVersion().getServerVersion();
return connection.getContext().getVersion().getVersion();
}

public String getDriverName() {
Expand Down Expand Up @@ -3746,7 +3746,7 @@ public <T> T unwrap(Class<T> iface) throws SQLException {
}

@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
public boolean isWrapperFor(Class<?> iface) {
return iface.isInstance(this);
}

Expand Down
9 changes: 6 additions & 3 deletions src/main/java/org/mariadb/jdbc/Driver.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,13 @@ public static Connection connect(Configuration configuration) throws SQLExceptio
*/
public Connection connect(final String url, final Properties props) throws SQLException {
Configuration configuration = Configuration.parse(url, props);
if (configuration.pool()) {
return Pools.retrievePool(configuration).getPoolConnection().getConnection();
if (configuration != null) {
if (configuration.pool()) {
return Pools.retrievePool(configuration).getPoolConnection().getConnection();
}
return connect(configuration);
}
return connect(configuration);
return null;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/mariadb/jdbc/HostAddress.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

public class HostAddress {

public String host;
public final String host;
public int port;
public Boolean primary;

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/mariadb/jdbc/MariaDbBlob.java
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ public BlobOutputStream(MariaDbBlob blob, int pos) {
}

@Override
public void write(int bit) throws IOException {
public void write(int bit) {

if (this.pos >= blob.length) {
byte[] tmp = new byte[2 * blob.length + 1];
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/org/mariadb/jdbc/MariaDbDataSource.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,9 @@ public <T> T unwrap(Class<T> iface) throws SQLException {
* @param iface a Class defining an interface.
* @return true if this implements the interface or directly or indirectly wraps an object that
* does.
* @throws SQLException if an error occurs while determining whether this is a wrapper for an
* object with the given interface.
*/
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
public boolean isWrapperFor(Class<?> iface) {
return iface.isInstance(this);
}

Expand Down
4 changes: 1 addition & 3 deletions src/main/java/org/mariadb/jdbc/MariaDbPoolDataSource.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,9 @@ public <T> T unwrap(Class<T> iface) throws SQLException {
* @param iface a Class defining an interface.
* @return true if this implements the interface or directly or indirectly wraps an object that
* does.
* @throws SQLException if an error occurs while determining whether this is a wrapper for an
* object with the given interface.
*/
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
public boolean isWrapperFor(Class<?> iface) {
return iface.isInstance(this);
}

Expand Down
7 changes: 3 additions & 4 deletions src/main/java/org/mariadb/jdbc/ServerPreparedStatement.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ public ServerPreparedStatement(
int autoGeneratedKeys,
int resultSetType,
int resultSetConcurrency,
int defaultFetchSize)
throws SQLException {
int defaultFetchSize) {
super(
sql,
con,
Expand Down Expand Up @@ -450,7 +449,7 @@ public void addBatch() throws SQLException {
protected void validParameters() throws SQLException {
if (prepareResult != null) {
for (int i = 0; i < prepareResult.getParameters().length; i++) {
if (!parameters.containsKey(i)) {
if (parameters.containsKey(i)) {
throw exceptionFactory()
.create("Parameter at position " + (i + 1) + " is not set", "07004");
}
Expand All @@ -469,7 +468,7 @@ protected void validParameters() throws SQLException {

// ensure all parameters are set
for (int i = 0; i < parameters.size(); i++) {
if (!parameters.containsKey(i)) {
if (parameters.containsKey(i)) {
throw exceptionFactory()
.create("Parameter at position " + (i + 1) + " is not set", "07004");
}
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/org/mariadb/jdbc/Statement.java
Original file line number Diff line number Diff line change
Expand Up @@ -565,12 +565,10 @@ public int getResultSetConcurrency() throws SQLException {
*
* @return one of <code>ResultSet.TYPE_FORWARD_ONLY</code>, <code>
* ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @throws SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @since 1.2
*/
@Override
public int getResultSetType() throws SQLException {
public int getResultSetType() {
return this.resultSetType;
}

Expand Down
17 changes: 6 additions & 11 deletions src/main/java/org/mariadb/jdbc/client/ClientImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,24 +48,21 @@

public class ClientImpl implements Client, AutoCloseable {
private static final Logger logger = Loggers.getLogger(ClientImpl.class);

private static Integer MAX_ALLOWED_PACKET = 0;

private final Socket socket;
private final MutableInt sequence = new MutableInt();
private final MutableInt compressionSequence = new MutableInt();
private final ReentrantLock lock;
private final Configuration conf;
private final HostAddress hostAddress;
private boolean closed = false;
protected ExceptionFactory exceptionFactory;
protected final ExceptionFactory exceptionFactory;
protected PacketWriter writer;
private PacketReader reader;
private org.mariadb.jdbc.Statement streamStmt = null;
private ClientMessage streamMsg = null;
private int socketTimeout;
private int waitTimeout;
private boolean disablePipeline;
private final boolean disablePipeline;
protected Context context;

public ClientImpl(
Expand Down Expand Up @@ -108,8 +105,7 @@ public ClientImpl(

this.exceptionFactory.setThreadId(handshake.getThreadId());
long clientCapabilities =
ConnectionHelper.initializeClientCapabilities(
conf, handshake.getCapabilities(), skipPostCommands);
ConnectionHelper.initializeClientCapabilities(conf, handshake.getCapabilities());
this.context =
conf.transactionReplay()
? new RedoContext(
Expand Down Expand Up @@ -390,7 +386,7 @@ public String createSessionVariableQuery(String serverTz) {
}
sb.append("='").append(conf.transactionIsolation().getValue()).append("'");

return "set " + sb.toString();
return "set " + sb;
}

public void setReadOnly(boolean readOnly) throws SQLException {
Expand Down Expand Up @@ -467,7 +463,7 @@ public List<Completion> executePipeline(
for (int i = 0; i < messages.length; i++) {
responseMsg[i] = sendQuery(messages[i]);
}
for (; readCounter < messages.length; ) {
while (readCounter < messages.length) {
readCounter++;
for (int j = 0; j < responseMsg[readCounter - 1]; j++) {
results.addAll(
Expand Down Expand Up @@ -565,7 +561,7 @@ public List<Completion> readResponse(
return completions;
}

public List<Completion> readResponse(ClientMessage message) throws SQLException {
public void readResponse(ClientMessage message) throws SQLException {
checkNotClosed();
if (streamStmt != null) {
streamStmt.fetchRemaining();
Expand All @@ -581,7 +577,6 @@ public List<Completion> readResponse(ClientMessage message) throws SQLException
ResultSet.CONCUR_READ_ONLY,
ResultSet.TYPE_FORWARD_ONLY,
false);
return completions;
}

public void closePrepare(PrepareResultPacket prepare) throws SQLException {
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/org/mariadb/jdbc/client/ConnectionHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public static Socket connectSocket(final Configuration conf, final HostAddress h
}

public static long initializeClientCapabilities(
final Configuration configuration, final long serverCapabilities, boolean skipPostCommands) {
final Configuration configuration, final long serverCapabilities) {
long capabilities =
Capabilities.IGNORE_SPACE
| Capabilities.CLIENT_PROTOCOL_41
Expand Down Expand Up @@ -210,7 +210,7 @@ public static byte decideLanguage(InitialHandshakePacket handshake) {
|| (serverLanguage >= 224 && serverLanguage <= 247)) {
return (byte) serverLanguage;
}
if (handshake.getMajorServerVersion() == 5 && handshake.getMinorServerVersion() <= 1) {
if (!handshake.getVersion().versionGreaterOrEqual(5, 5, 0)) {
// 5.1 version doesn't know 4 bytes utf8
return (byte) 33; // utf8_general_ci
}
Expand All @@ -233,7 +233,7 @@ public static void authenticationHandler(
// Authentication Switch Request see
// https://mariadb.com/kb/en/library/connection/#authentication-switch-request
// *************************************************************************************
AuthSwitchPacket authSwitchPacket = AuthSwitchPacket.decode(buf, context);
AuthSwitchPacket authSwitchPacket = AuthSwitchPacket.decode(buf);
AuthenticationPlugin authenticationPlugin =
AuthenticationPluginLoader.get(authSwitchPacket.getPlugin(), conf);

Expand Down Expand Up @@ -324,7 +324,7 @@ public static SSLSocket sslWrapper(

SSLSession session = sslSocket.getSession();
try {
socketPlugin.verify(hostAddress.host, session, conf, context.getThreadId());
socketPlugin.verify(hostAddress.host, session, context.getThreadId());
} catch (SSLException ex) {
throw context
.getExceptionFactory()
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/org/mariadb/jdbc/client/MultiPrimaryClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class MultiPrimaryClient implements Client {
private static final Logger logger = Loggers.getLogger(MultiPrimaryClient.class);

protected static final ConcurrentMap<HostAddress, Long> denyList = new ConcurrentHashMap<>();
protected long deniedListTimeout;
protected final long deniedListTimeout;
protected final Configuration conf;
protected boolean closed = false;
protected final ReentrantLock lock;
Expand Down Expand Up @@ -92,9 +92,7 @@ protected Client connectHost(boolean readOnly, boolean failFast) throws SQLExcep
// return the one with lower denylist timeout
// (check that server is in conf, because denyList is shared for all instances)
if (denyList.entrySet().stream()
.filter(e -> conf.addresses().contains(e.getKey()) && e.getKey().primary != readOnly)
.count()
== 0)
.noneMatch(e -> conf.addresses().contains(e.getKey()) && e.getKey().primary != readOnly))
throw new SQLNonTransientConnectionException(
String.format("No %s host defined", readOnly ? "replica" : "primary"));
while (maxRetries > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ public void abort(Executor executor) throws SQLException {
}

@Override
public void close() throws SQLException {
public void close() {
if (!closed) {
closed = true;
try {
Expand Down
1 change: 1 addition & 0 deletions src/main/java/org/mariadb/jdbc/client/PrepareCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ public CachedPrepareResultPacket get(Object key) {
throw new IllegalStateException("not available method");
}

@SuppressWarnings("unused")
public CachedPrepareResultPacket put(String key, PrepareResultPacket result) {
throw new IllegalStateException("not available method");
}
Expand Down
Loading

0 comments on commit db9de26

Please sign in to comment.