From c2ce6dfeb77c3fc6472644424ee863decba887df Mon Sep 17 00:00:00 2001 From: lilgreenbird Date: Mon, 16 Jan 2023 13:34:08 -0800 Subject: [PATCH 1/5] sonar --- .../com/microsoft/sqlserver/jdbc/DDC.java | 4 ++ .../microsoft/sqlserver/jdbc/DataTypes.java | 4 ++ .../microsoft/sqlserver/jdbc/IOBuffer.java | 8 ++-- .../jdbc/ISQLServerEnclaveProvider.java | 6 +-- .../jdbc/ISQLServerPreparedStatement.java | 2 +- .../jdbc/KeyStoreProviderCommon.java | 4 ++ .../jdbc/ParameterMetaDataCache.java | 8 +++- .../sqlserver/jdbc/ParameterUtils.java | 4 ++ .../sqlserver/jdbc/SQLCollation.java | 5 ++- .../sqlserver/jdbc/SQLJdbcVersion.java | 4 ++ .../jdbc/SQLServerAASEnclaveProvider.java | 10 ++--- .../jdbc/SQLServerBouncyCastleLoader.java | 5 +++ .../sqlserver/jdbc/SQLServerBulkCopy.java | 45 ++++++++----------- .../jdbc/SQLServerCertificateUtils.java | 10 +++-- .../sqlserver/jdbc/SQLServerClob.java | 9 +++- ...ColumnEncryptionAzureKeyVaultProvider.java | 36 +++++++-------- ...umnEncryptionCertificateStoreProvider.java | 6 +-- .../sqlserver/jdbc/SQLServerConnection.java | 10 +++-- .../jdbc/SQLServerNoneEnclaveProvider.java | 4 +- .../jdbc/SQLServerVSMEnclaveProvider.java | 4 +- 20 files changed, 112 insertions(+), 76 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java index 35ecb8aa8..01c031a33 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java @@ -36,6 +36,10 @@ final class DDC { + private DDC() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + /** * Convert an Integer object to desired target user type. * diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/DataTypes.java b/src/main/java/com/microsoft/sqlserver/jdbc/DataTypes.java index 7377dfb9d..7b710bc04 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/DataTypes.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/DataTypes.java @@ -1107,6 +1107,10 @@ boolean normalizationCheck(SSType ssType) { final class DataTypes { + private DataTypes() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + // ResultSet & CallableStatement getXXX conversions (SSType --> JDBCType) static final void throwConversionError(String fromType, String toType) throws SQLServerException { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unsupportedConversionFromTo")); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index 9c5a5596b..1bb851929 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -1289,7 +1289,7 @@ public void flush() throws IOException { filteredStream.flush(); } - private final byte singleByte[] = new byte[1]; + private final byte[] singleByte = new byte[1]; @Override public void write(int b) throws IOException { @@ -2748,7 +2748,7 @@ private SocketFactory getSocketFactory() throws IOException { * Port Number * @return First resolved address or unresolved address if none found */ - private InetSocketAddress getInetAddressByIPPreference(InetAddress addresses[], boolean ipv6first, String hostName, + private InetSocketAddress getInetAddressByIPPreference(InetAddress[] addresses, boolean ipv6first, String hostName, int portNumber) { InetSocketAddress addr = InetSocketAddress.createUnresolved(hostName, portNumber); for (InetAddress inetAddress : fillAddressList(addresses, ipv6first)) { @@ -6263,7 +6263,7 @@ byte[] writeEncryptedScaledTemporal(GregorianCalendar cal, int subSecondNanos, i DriverError.NOT_SET, null); } - byte encodedBytes[] = new byte[3]; + byte[] encodedBytes = new byte[3]; encodedBytes[0] = (byte) ((daysIntoCE >> 0) & 0xFF); encodedBytes[1] = (byte) ((daysIntoCE >> 8) & 0xFF); encodedBytes[2] = (byte) ((daysIntoCE >> 16) & 0xFF); @@ -6560,7 +6560,7 @@ void writeRPCReaderUnicode(String sName, Reader re, long reLength, boolean bOut, void sendEnclavePackage(String sql, ArrayList enclaveCEKs) throws SQLServerException { if (null != con && con.isAEv2()) { - if (null != sql && !sql.isEmpty() && null != enclaveCEKs && 0 < enclaveCEKs.size() + if (null != sql && !sql.isEmpty() && null != enclaveCEKs && !(enclaveCEKs.isEmpty()) && con.enclaveEstablished()) { byte[] b = con.generateEnclavePackage(sql, enclaveCEKs); if (null != b && 0 != b.length) { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerEnclaveProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerEnclaveProvider.java index 254b8c6ac..a09f58881 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerEnclaveProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerEnclaveProvider.java @@ -419,7 +419,7 @@ abstract class BaseAttestationResponse { protected byte[] sessionID = new byte[8]; protected int dhpkSize; protected int dhpkSsize; - protected byte[] DHpublicKey; + protected byte[] dhPublicKey; protected byte[] publicKeySig; @SuppressWarnings("unused") @@ -458,7 +458,7 @@ void validateDHPublicKey() throws SQLServerException, GeneralSecurityException { PublicKey pub = factory.generatePublic(spec); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(pub); - sig.update(DHpublicKey); + sig.update(dhPublicKey); if (!sig.verify(publicKeySig)) { SQLServerException.makeFromDriverError(null, this, SQLServerResource.getResource("R_InvalidDHKeySignature"), "0", false); @@ -466,7 +466,7 @@ void validateDHPublicKey() throws SQLServerException, GeneralSecurityException { } byte[] getDHpublicKey() { - return DHpublicKey; + return dhPublicKey; } byte[] getSessionID() { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerPreparedStatement.java index aa14bc46d..758992f87 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerPreparedStatement.java @@ -242,7 +242,7 @@ void setBigDecimal(int parameterIndex, BigDecimal x, int precision, int scale, * @throws SQLServerException * when an error occurs */ - void setBytes(int parameterIndex, byte x[], boolean forceEncrypt) throws SQLServerException; + void setBytes(int parameterIndex, byte[] x, boolean forceEncrypt) throws SQLServerException; /** * Sets the designated parameter to the given String. The driver converts this to an SQL GUID diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/KeyStoreProviderCommon.java b/src/main/java/com/microsoft/sqlserver/jdbc/KeyStoreProviderCommon.java index 91e229728..cdd44e00d 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/KeyStoreProviderCommon.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/KeyStoreProviderCommon.java @@ -39,6 +39,10 @@ class CertificateDetails { class KeyStoreProviderCommon { + private KeyStoreProviderCommon() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + static final String RSA_ENCRYPTION_ALGORITHM = "RSA_OAEP"; static byte[] version = new byte[] {0x01}; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/ParameterMetaDataCache.java b/src/main/java/com/microsoft/sqlserver/jdbc/ParameterMetaDataCache.java index 98a50d182..6aba09fdc 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/ParameterMetaDataCache.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/ParameterMetaDataCache.java @@ -20,6 +20,10 @@ */ class ParameterMetaDataCache { + private ParameterMetaDataCache() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + static final int CACHE_SIZE = 2000; // Size of the cache in number of entries static final int MAX_WEIGHTED_CAPACITY = 2300; // Size of cache + threshold, above which we trim. static CryptoCache cache = new CryptoCache(); @@ -97,7 +101,7 @@ static boolean getQueryMetadata(Parameter[] params, ArrayList parameterN SQLServerSecurityUtility.decryptSymmetricKey(cryptoCopy, connection, stmt); } catch (SQLServerException e) { - removeCacheEntry(stmt, connection, userSql); + removeCacheEntry(connection, userSql); for (Parameter paramToCleanup : params) { paramToCleanup.cryptoMeta = null; @@ -208,7 +212,7 @@ static boolean addQueryMetadata(Parameter[] params, ArrayList parameterN * @param userSql * The query executed by the user */ - static void removeCacheEntry(SQLServerStatement stmt, SQLServerConnection connection, String userSql) { + static void removeCacheEntry(SQLServerConnection connection, String userSql) { AbstractMap.SimpleEntry encryptionValues = getCacheLookupKeys(connection, userSql); if (encryptionValues.getKey() == null) { return; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/ParameterUtils.java b/src/main/java/com/microsoft/sqlserver/jdbc/ParameterUtils.java index 69dd717b4..126e4e162 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/ParameterUtils.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/ParameterUtils.java @@ -10,6 +10,10 @@ */ final class ParameterUtils { + private ParameterUtils() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + static byte[] hexToBin(String hexV) throws SQLServerException { int len = hexV.length(); char[] orig = hexV.toCharArray(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLCollation.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLCollation.java index 3e148a8bd..e7369bfe1 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLCollation.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLCollation.java @@ -40,6 +40,9 @@ private int langID() { private final Encoding encoding; private static final int UTF8_IN_TDSCOLLATION = 0x4000000; + // Length of collation in TDS (in bytes) + private static final int TDS_LENGTH = 5; + // Utility methods for getting details of this collation's encoding final Charset getCharset() throws SQLServerException { return encoding.charset(); @@ -54,7 +57,7 @@ final boolean hasAsciiCompatibleSBCS() { } static final int tdsLength() { - return 5; + return TDS_LENGTH; } // Length of collation in TDS (in bytes) /** diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java index 431cb5421..d4c2be5bb 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java @@ -16,4 +16,8 @@ final class SQLJdbcVersion { * 2. Set to "" (empty String) for official release. */ static final String RELEASE_EXT = "-preview"; + + private SQLJdbcVersion() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAASEnclaveProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAASEnclaveProvider.java index a6f49ebd7..c178ab5b4 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAASEnclaveProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAASEnclaveProvider.java @@ -182,7 +182,7 @@ class AASAttestationParameters extends BaseAttestationRequest { // Type 1 is AAS, sent as Little Endian 0x10000000 private static final byte[] ENCLAVE_TYPE = new byte[] {0x1, 0x0, 0x0, 0x0}; // Nonce length is always 256 - private static byte[] NONCE_LENGTH = new byte[] {0x0, 0x1, 0x0, 0x0}; + private static final byte[] NONCE_LENGTH = new byte[] {0x0, 0x1, 0x0, 0x0}; private byte[] nonce = new byte[256]; AASAttestationParameters(String attestationUrl) throws SQLServerException, IOException { @@ -278,10 +278,10 @@ class AASAttestationResponse extends BaseAttestationResponse { this.dhpkSize = response.getInt(); this.dhpkSsize = response.getInt(); - DHpublicKey = new byte[dhpkSize]; + dhPublicKey = new byte[dhpkSize]; publicKeySig = new byte[dhpkSsize]; - response.get(DHpublicKey, 0, dhpkSize); + response.get(dhPublicKey, 0, dhpkSize); response.get(publicKeySig, 0, dhpkSsize); if (0 != response.remaining()) { @@ -318,12 +318,12 @@ void validateToken(String attestationUrl, byte[] nonce) throws SQLServerExceptio String authorityUrl = new URL(attestationUrl).getAuthority(); URL wellKnownUrl = new URL("https://" + authorityUrl + "/.well-known/openid-configuration"); URLConnection con = wellKnownUrl.openConnection(); - String wellKnownUrlJson = new String(Util.convertInputStreamToString(con.getInputStream())); + String wellKnownUrlJson = Util.convertInputStreamToString(con.getInputStream()); JsonObject attestationJson = JsonParser.parseString(wellKnownUrlJson).getAsJsonObject(); // Get our Keys URL jwksUrl = new URL(attestationJson.get("jwks_uri").getAsString()); URLConnection jwksCon = jwksUrl.openConnection(); - String jwksUrlJson = new String(Util.convertInputStreamToString(jwksCon.getInputStream())); + String jwksUrlJson = Util.convertInputStreamToString(jwksCon.getInputStream()); JsonObject jwksJson = JsonParser.parseString(jwksUrlJson).getAsJsonObject(); keys = jwksJson.get("keys").getAsJsonArray(); certificateCache.put(attestationUrl, new JWTCertificateEntry(keys)); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBouncyCastleLoader.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBouncyCastleLoader.java index c94c40466..88e6544c3 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBouncyCastleLoader.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBouncyCastleLoader.java @@ -8,11 +8,16 @@ import java.security.Provider; import java.security.Security; + /* * Class that is meant to statically load the BouncyCastle Provider for JDK 8. Hides the call so JDK 11/13 don't have to include the dependency. * Also loads BouncyCastle provider for PKCS1 private key parsing. */ class SQLServerBouncyCastleLoader { + private SQLServerBouncyCastleLoader() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + static void loadBouncyCastle() { Provider p = new org.bouncycastle.jce.provider.BouncyCastleProvider(); if (null == Security.getProvider(p.getName())) { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java index ca9ceccf5..b4b663a6d 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java @@ -196,7 +196,7 @@ class BulkColumnMetaData { // used when allowEncryptedValueModifications is on and encryption is turned off in connection String encryptionType = null; - BulkColumnMetaData(Column column) throws SQLServerException { + BulkColumnMetaData(Column column) { this.cryptoMeta = column.getCryptoMetadata(); TypeInfo typeInfo = column.getTypeInfo(); this.columnName = column.getColumnName(); @@ -212,7 +212,7 @@ class BulkColumnMetaData { // This constructor is needed for the source meta data. BulkColumnMetaData(String colName, boolean isNullable, int precision, int scale, int jdbcType, - DateTimeFormatter dateTimeFormatter) throws SQLServerException { + DateTimeFormatter dateTimeFormatter) { this.columnName = colName; this.isNullable = isNullable; this.precision = precision; @@ -267,7 +267,7 @@ class BulkColumnMetaData { * The maximum temporal precision we can send when using varchar(precision) in bulkcommand, to send a * smalldatetime/datetime value. */ - private static final int sourceBulkRecordTemporalMaxPrecision = 50; + private static final int SOURCE_BULK_RECORD_TEMPORAL_MAX_PRECISION = 50; /** * Constructs a SQLServerBulkCopy using the specified open instance of SQLServerConnection. @@ -739,7 +739,7 @@ private void writeColumnMetaDataColumnData(TDSWriter tdsWriter, int idx) throws */ srcColumnIndex = columnMappings.get(idx).sourceColumnOrdinal; - byte flags[] = destColumnMetadata.get(destColumnIndex).flags; + byte[] flags = destColumnMetadata.get(destColumnIndex).flags; // If AllowEncryptedValueModification is set to true (and of course AE is off), // the driver will not sent AE information, so, we need to set Encryption bit flag to 0. if (null == srcColumnMetadata.get(srcColumnIndex).cryptoMeta @@ -848,7 +848,7 @@ else if (((java.sql.Types.CHAR == bulkJdbcType) || (java.sql.Types.VARCHAR == bu */ int destColNameLen = columnMappings.get(idx).destinationColumnName.length(); String destColName = columnMappings.get(idx).destinationColumnName; - byte colName[] = new byte[2 * destColNameLen]; + byte[] colName = new byte[2 * destColNameLen]; for (int i = 0; i < destColNameLen; ++i) { int c = destColName.charAt(i); @@ -1385,7 +1385,7 @@ private String getDestTypeFromSrcType(int srcColIndx, int destColIndx, case SMALLDATETIME: if (null != serverBulkData && connection.getSendTemporalDataTypesAsStringForBulkCopy()) { return SSType.VARCHAR.toString() + "(" - + ((0 == bulkPrecision) ? sourceBulkRecordTemporalMaxPrecision : bulkPrecision) + + ((0 == bulkPrecision) ? SOURCE_BULK_RECORD_TEMPORAL_MAX_PRECISION : bulkPrecision) + ")"; } else { return SSType.SMALLDATETIME.toString(); @@ -1393,7 +1393,7 @@ private String getDestTypeFromSrcType(int srcColIndx, int destColIndx, case DATETIME: if (null != serverBulkData && connection.getSendTemporalDataTypesAsStringForBulkCopy()) { return SSType.VARCHAR.toString() + "(" - + ((0 == bulkPrecision) ? sourceBulkRecordTemporalMaxPrecision : bulkPrecision) + + ((0 == bulkPrecision) ? SOURCE_BULK_RECORD_TEMPORAL_MAX_PRECISION : bulkPrecision) + ")"; } else { return SSType.DATETIME.toString(); @@ -1552,10 +1552,10 @@ private boolean doInsertBulk(TDSCommand command) throws SQLServerException { boolean insertRowByRow = false; if (null != sourceResultSet && sourceResultSet instanceof SQLServerResultSet) { - SQLServerStatement src_stmt = (SQLServerStatement) ((SQLServerResultSet) sourceResultSet).getStatement(); + SQLServerStatement srcStmt = (SQLServerStatement) ((SQLServerResultSet) sourceResultSet).getStatement(); int resultSetServerCursorId = ((SQLServerResultSet) sourceResultSet).getServerCursorId(); - if (connection.equals(src_stmt.getConnection()) && 0 != resultSetServerCursorId) { + if (connection.equals(srcStmt.getConnection()) && 0 != resultSetServerCursorId) { insertRowByRow = true; } @@ -1797,7 +1797,7 @@ private void getSourceMetadata() throws SQLServerException { } } else if (null != serverBulkData) { Set columnOrdinals = serverBulkData.getColumnOrdinals(); - if (null == columnOrdinals || 0 == columnOrdinals.size()) { + if (null == columnOrdinals || columnOrdinals.isEmpty()) { throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveColMeta"), null); } else { srcColumnCount = columnOrdinals.size(); @@ -2278,12 +2278,10 @@ else if (null != sourceCryptoMeta) { // writeReader is unicode. tdsWriter.writeReader(reader, DataTypes.UNKNOWN_STREAM_LENGTH, true); } else { - if ((SSType.BINARY == destSSType) || (SSType.VARBINARY == destSSType) - || (SSType.VARBINARYMAX == destSSType) || (SSType.IMAGE == destSSType)) { - tdsWriter.writeNonUnicodeReader(reader, DataTypes.UNKNOWN_STREAM_LENGTH, true); - } else { - tdsWriter.writeNonUnicodeReader(reader, DataTypes.UNKNOWN_STREAM_LENGTH, false); - } + tdsWriter.writeNonUnicodeReader(reader, DataTypes.UNKNOWN_STREAM_LENGTH, + (SSType.BINARY == destSSType) || (SSType.VARBINARY == destSSType) + || (SSType.VARBINARYMAX == destSSType) + || (SSType.IMAGE == destSSType)); } reader.close(); } catch (IOException e) { @@ -3227,8 +3225,7 @@ private Object getTemporalObjectFromCSV(Object value, int srcJdbcType, case java.sql.Types.TIME: { String time = connection.baseYear() + "-01-01 " + valueStr; - Timestamp ts = java.sql.Timestamp.valueOf(time); - return ts; + return java.sql.Timestamp.valueOf(time); } case java.sql.Types.DATE: return java.sql.Date.valueOf(valueStr); @@ -3319,19 +3316,13 @@ else if ('-' == valueStr.charAt(startIndx)) { default: break; } - } catch (IndexOutOfBoundsException e) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ParsingError")); - Object[] msgArgs = {JDBCType.of(srcJdbcType)}; - throw new SQLServerException(this, form.format(msgArgs), null, 0, false); - } catch (NumberFormatException e) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ParsingError")); - Object[] msgArgs = {JDBCType.of(srcJdbcType)}; - throw new SQLServerException(this, form.format(msgArgs), null, 0, false); - } catch (IllegalArgumentException e) { + } catch (IndexOutOfBoundsException | IllegalArgumentException e) { + // IllegalArgumentsException includes NumberFormatException MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ParsingError")); Object[] msgArgs = {JDBCType.of(srcJdbcType)}; throw new SQLServerException(this, form.format(msgArgs), null, 0, false); } + // unreachable code. Need to do to compile from Eclipse. return value; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCertificateUtils.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCertificateUtils.java index 162d592fd..60104a83f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCertificateUtils.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCertificateUtils.java @@ -64,6 +64,10 @@ final class SQLServerCertificateUtils { private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.SQLServerCertificateUtils"); private static final String logContext = Thread.currentThread().getStackTrace()[1].getClassName() + ": "; + private SQLServerCertificateUtils() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + static KeyManager[] getKeyManagerFromFile(String certPath, String keyPath, String keyPassword) throws IOException, GeneralSecurityException, SQLServerException { if (keyPath != null && keyPath.length() > 0) { @@ -322,7 +326,7 @@ private static void logSuccessMessage(String nameInCert, String hostName) { private static final String RSA_ALG = "RSA"; private static KeyManager[] readPKCS12Certificate(String certPath, - String keyPassword) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyStoreException, SQLServerException { + String keyPassword) throws NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyStoreException, SQLServerException { KeyStore keystore = KeyStore.getInstance(PKCS12_ALG); try (FileInputStream certStream = new FileInputStream(certPath)) { keystore.load(certStream, keyPassword.toCharArray()); @@ -351,7 +355,7 @@ private static KeyManager[] readPKCS8Certificate(String certPath, String keyPath } private static PrivateKey loadPrivateKeyFromPKCS8( - String key) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { + String key) throws NoSuchAlgorithmException, InvalidKeySpecException { StringBuilder sb = new StringBuilder(key); deleteFirst(sb, PEM_PRIVATE_START); deleteFirst(sb, PEM_PRIVATE_END); @@ -369,7 +373,7 @@ private static void deleteFirst(StringBuilder sb, String str) { } private static PrivateKey loadPrivateKeyFromPKCS1(String key, - String keyPass) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { + String keyPass) throws IOException { SQLServerBouncyCastleLoader.loadBouncyCastle(); try (PEMParser pemParser = new PEMParser(new StringReader(key))) { Object object = pemParser.readObject(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java index 7e6b746f9..781163066 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java @@ -60,7 +60,7 @@ public SQLServerClob(SQLServerConnection connection, String data) { super(connection, "", connection.getDatabaseCollation(), logger, null); } - SQLServerClob(BaseInputStream stream, TypeInfo typeInfo) throws SQLServerException, UnsupportedEncodingException { + SQLServerClob(BaseInputStream stream, TypeInfo typeInfo) { super(null, stream, typeInfo.getSQLCollation(), logger, typeInfo); } @@ -595,7 +595,12 @@ public int setString(long pos, String str, int offset, int len) throws SQLExcept // Make sure the new value length wouldn't exceed the maximum // allowed DataTypes.getCheckedLength(con, getJdbcType(), pos + len, false); - assert pos + len <= Integer.MAX_VALUE; + + if (!(pos + len <= Integer.MAX_VALUE)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidLength")); + Object[] msgArgs = {pos}; + SQLServerException.makeFromDriverError(con, null, form.format(msgArgs), null, true); + } // Start with the original value, up to the starting position StringBuilder sb = new StringBuilder((int) pos + len); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionAzureKeyVaultProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionAzureKeyVaultProvider.java index 5f0b53959..33fb520bc 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionAzureKeyVaultProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionAzureKeyVaultProvider.java @@ -136,7 +136,7 @@ public class SQLServerColumnEncryptionAzureKeyVaultProvider extends SQLServerCol /** * Algorithm version */ - private final byte[] firstVersion = new byte[] {0x01}; + private static final byte[] firstVersion = new byte[] {0x01}; private Map cachedKeyClients = new ConcurrentHashMap<>(); private Map cachedCryptographyClients = new ConcurrentHashMap<>(); @@ -274,7 +274,7 @@ public SQLServerColumnEncryptionAzureKeyVaultProvider(TokenCredential tokenCrede * - Callback function used for authenticating to AAD. * @throws SQLServerException * when an error occurs - * + * * @deprecated */ @Deprecated(since = "12.1.0", forRemoval = true) @@ -324,7 +324,7 @@ public byte[] decryptColumnEncryptionKey(String masterKeyPath, String encryption byte[] encryptedColumnEncryptionKey) throws SQLServerException { // Validate the input parameters - this.ValidateNonEmptyAKVPath(masterKeyPath); + this.validateNonEmptyAKVPath(masterKeyPath); if (null == encryptedColumnEncryptionKey) { throw new SQLServerException(SQLServerException.getErrString("R_NullEncryptedColumnEncryptionKey"), null); @@ -420,21 +420,21 @@ public byte[] decryptColumnEncryptionKey(String masterKeyPath, String encryption throw new SQLServerException(SQLServerException.getErrString("R_NoSHA256Algorithm"), e); } md.update(hash); - byte dataToVerify[] = md.digest(); + byte[] dataToVerify = md.digest(); if (null == dataToVerify) { throw new SQLServerException(SQLServerException.getErrString("R_HashNull"), null); } // Validate the signature - if (!AzureKeyVaultVerifySignature(dataToVerify, signature, masterKeyPath)) { + if (!azureKeyVaultVerifySignature(dataToVerify, signature, masterKeyPath)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_CEKSignatureNotMatchCMK")); Object[] msgArgs = {masterKeyPath}; throw new SQLServerException(this, form.format(msgArgs), null, 0, false); } // Decrypt the CEK - byte[] decryptedCEK = this.AzureKeyVaultUnWrap(masterKeyPath, keyWrapAlgorithm, cipherText); + byte[] decryptedCEK = this.azureKeyVaultUnWrap(masterKeyPath, keyWrapAlgorithm, cipherText); if (allowCache) { columnEncryptionKeyCache.put(encryptedColumnEncryptionKeyHexString, decryptedCEK); @@ -475,7 +475,7 @@ public byte[] encryptColumnEncryptionKey(String masterKeyPath, String encryption byte[] columnEncryptionKey) throws SQLServerException { // Validate the input parameters - this.ValidateNonEmptyAKVPath(masterKeyPath); + this.validateNonEmptyAKVPath(masterKeyPath); if (null == columnEncryptionKey) { throw new SQLServerException(SQLServerException.getErrString("R_NullColumnEncryptionKey"), null); @@ -506,7 +506,7 @@ public byte[] encryptColumnEncryptionKey(String masterKeyPath, String encryption keyPathLength[1] = (byte) (((short) masterKeyPathBytes.length) >> 8 & 0xff); // Encrypt the plain text - byte[] cipherText = this.AzureKeyVaultWrap(masterKeyPath, keyWrapAlgorithm, columnEncryptionKey); + byte[] cipherText = this.azureKeyVaultWrap(masterKeyPath, keyWrapAlgorithm, columnEncryptionKey); byte[] cipherTextLength = new byte[2]; cipherTextLength[0] = (byte) (((short) cipherText.length) & 0xff); @@ -541,16 +541,16 @@ public byte[] encryptColumnEncryptionKey(String masterKeyPath, String encryption throw new SQLServerException(SQLServerException.getErrString("R_NoSHA256Algorithm"), e); } md.update(dataToHash); - byte dataToSign[] = md.digest(); + byte[] dataToSign = md.digest(); // Sign the hash - byte[] signedHash = AzureKeyVaultSignHashedData(dataToSign, masterKeyPath); + byte[] signedHash = azureKeyVaultSignHashedData(dataToSign, masterKeyPath); if (signedHash.length != keySizeInBytes) { throw new SQLServerException(SQLServerException.getErrString("R_SignedHashLengthError"), null); } - if (!this.AzureKeyVaultVerifySignature(dataToSign, signedHash, masterKeyPath)) { + if (!this.azureKeyVaultVerifySignature(dataToSign, signedHash, masterKeyPath)) { throw new SQLServerException(SQLServerException.getErrString("R_InvalidSignatureComputed"), null); } @@ -622,7 +622,7 @@ private KeyWrapAlgorithm validateEncryptionAlgorithm(String encryptionAlgorithm) * @param masterKeyPath * @throws SQLServerException */ - private void ValidateNonEmptyAKVPath(String masterKeyPath) throws SQLServerException { + private void validateNonEmptyAKVPath(String masterKeyPath) throws SQLServerException { // throw appropriate error if masterKeyPath is null or empty if (null == masterKeyPath || masterKeyPath.trim().isEmpty()) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_AKVPathNull")); @@ -668,7 +668,7 @@ private void ValidateNonEmptyAKVPath(String masterKeyPath) throws SQLServerExcep * @return Returns an encrypted blob or throws an exception if there are any errors. * @throws SQLServerException */ - private byte[] AzureKeyVaultWrap(String masterKeyPath, KeyWrapAlgorithm encryptionAlgorithm, + private byte[] azureKeyVaultWrap(String masterKeyPath, KeyWrapAlgorithm encryptionAlgorithm, byte[] columnEncryptionKey) throws SQLServerException { if (null == columnEncryptionKey) { throw new SQLServerException(SQLServerException.getErrString("R_CEKNull"), null); @@ -691,7 +691,7 @@ private byte[] AzureKeyVaultWrap(String masterKeyPath, KeyWrapAlgorithm encrypti * @return Returns the decrypted plaintext Column Encryption Key or throws an exception if there are any errors. * @throws SQLServerException */ - private byte[] AzureKeyVaultUnWrap(String masterKeyPath, KeyWrapAlgorithm encryptionAlgorithm, + private byte[] azureKeyVaultUnWrap(String masterKeyPath, KeyWrapAlgorithm encryptionAlgorithm, byte[] encryptedColumnEncryptionKey) throws SQLServerException { if (null == encryptedColumnEncryptionKey) { throw new SQLServerException(SQLServerException.getErrString("R_EncryptedCEKNull"), null); @@ -737,7 +737,7 @@ private CryptographyClient getCryptographyClient(String masterKeyPath) throws SQ * @return Signature * @throws SQLServerException */ - private byte[] AzureKeyVaultSignHashedData(byte[] dataToSign, String masterKeyPath) throws SQLServerException { + private byte[] azureKeyVaultSignHashedData(byte[] dataToSign, String masterKeyPath) throws SQLServerException { assert ((null != dataToSign) && (0 != dataToSign.length)); CryptographyClient cryptoClient = getCryptographyClient(masterKeyPath); @@ -755,7 +755,7 @@ private byte[] AzureKeyVaultSignHashedData(byte[] dataToSign, String masterKeyPa * @return true if signature is valid, false if it is not valid * @throws SQLServerException */ - private boolean AzureKeyVaultVerifySignature(byte[] dataToVerify, byte[] signature, + private boolean azureKeyVaultVerifySignature(byte[] dataToVerify, byte[] signature, String masterKeyPath) throws SQLServerException { assert ((null != dataToVerify) && (0 != dataToVerify.length)); assert ((null != signature) && (0 != signature.length)); @@ -889,13 +889,13 @@ public boolean verifyColumnMasterKeyMetadata(String masterKeyPath, boolean allow } // Sign the hash - byte[] signedHash = AzureKeyVaultSignHashedData(dataToVerify, masterKeyPath); + byte[] signedHash = azureKeyVaultSignHashedData(dataToVerify, masterKeyPath); if (null == signedHash) { throw new SQLServerException(SQLServerException.getErrString("R_SignedHashLengthError"), null); } // Validate the signature - boolean isValid = AzureKeyVaultVerifySignature(dataToVerify, signature, masterKeyPath); + boolean isValid = azureKeyVaultVerifySignature(dataToVerify, signature, masterKeyPath); cmkMetadataSignatureVerificationCache.put(key, isValid); return isValid; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java index 1e8d0d040..2b822fbf4 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java @@ -21,9 +21,9 @@ public final class SQLServerColumnEncryptionCertificateStoreProvider extends SQL String name = "MSSQL_CERTIFICATE_STORE"; - static final String localMachineDirectory = "LocalMachine"; - static final String currentUserDirectory = "CurrentUser"; - static final String myCertificateStore = "My"; + static final String LOCAL_MACHINE_DIRECTORY = "LocalMachine"; + static final String CURRENT_USER_DIRECTORY = "CurrentUser"; + static final String MY_CERTIFICATE_STORE = "My"; static { if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows")) { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 1133c67ff..12c02f959 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -583,6 +583,10 @@ class ActiveDirectoryAuthentication { static final int GET_ACCESS_TOKEN_INVALID_GRANT = 1; static final int GET_ACCESS_TOKEN_TANSISENT_ERROR = 2; static final int GET_ACCESS_TOKEN_OTHER_ERROR = 3; + + private ActiveDirectoryAuthentication() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } } final static int TNIR_FIRST_ATTEMPT_TIMEOUT_MS = 500; // fraction of timeout to use for fast failover connections @@ -5140,12 +5144,12 @@ final void processEnvChange(TDSReader tdsReader) throws SQLServerException { case ENVCHANGE_DTC_ENLIST: case ENVCHANGE_XACT_BEGIN: rolledBackTransaction = false; - byte[] transactionDescriptor = getTransactionDescriptor(); + byte[] descriptor = getTransactionDescriptor(); - if (transactionDescriptor.length != tdsReader.readUnsignedByte()) + if (descriptor.length != tdsReader.readUnsignedByte()) tdsReader.throwInvalidTDS(); - tdsReader.readBytes(transactionDescriptor, 0, transactionDescriptor.length); + tdsReader.readBytes(descriptor, 0, descriptor.length); if (connectionlogger.isLoggable(Level.FINER)) { String op; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerNoneEnclaveProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerNoneEnclaveProvider.java index 95def0d43..c0db8ed38 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerNoneEnclaveProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerNoneEnclaveProvider.java @@ -203,10 +203,10 @@ class NoneAttestationResponse extends BaseAttestationResponse { this.dhpkSize = response.getInt(); this.dhpkSsize = response.getInt(); - DHpublicKey = new byte[dhpkSize]; + dhPublicKey = new byte[dhpkSize]; publicKeySig = new byte[dhpkSsize]; - response.get(DHpublicKey, 0, dhpkSize); + response.get(dhPublicKey, 0, dhpkSize); response.get(publicKeySig, 0, dhpkSsize); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerVSMEnclaveProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerVSMEnclaveProvider.java index 8a329dcf7..ab8ae3c9d 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerVSMEnclaveProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerVSMEnclaveProvider.java @@ -268,10 +268,10 @@ class VSMAttestationResponse extends BaseAttestationResponse { this.dhpkSize = response.getInt(); this.dhpkSsize = response.getInt(); - DHpublicKey = new byte[dhpkSize]; + dhPublicKey = new byte[dhpkSize]; publicKeySig = new byte[dhpkSsize]; - response.get(DHpublicKey, 0, dhpkSize); + response.get(dhPublicKey, 0, dhpkSize); response.get(publicKeySig, 0, dhpkSsize); } From da5cf55c00d85743e7ee3ef23e5bdf43af59200c Mon Sep 17 00:00:00 2001 From: lilgreenbird Date: Mon, 16 Jan 2023 13:51:05 -0800 Subject: [PATCH 2/5] fixed --- .../microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 8aa67b726..7f3df88c3 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -624,7 +624,7 @@ final void doExecutePreparedStatement(PrepStmtExecCmd command) throws SQLServerE } else if (!inRetry && connection.doesServerSupportEnclaveRetry()) { // We only want to retry once, so no retrying if we're already in the second pass. // If we are AE_v3, remove the failed entry and try again. - ParameterMetaDataCache.removeCacheEntry(this, connection, preparedSQL); + ParameterMetaDataCache.removeCacheEntry(connection, preparedSQL); inRetry = true; doExecutePreparedStatement(command); } else { From 628e8f1ca01081646b187ae7d1e48768b708fd37 Mon Sep 17 00:00:00 2001 From: lilgreenbird Date: Mon, 16 Jan 2023 17:28:11 -0800 Subject: [PATCH 3/5] fix --- .../jdbc/ISQLServerEnclaveProvider.java | 5 ++- .../jdbc/SQLServerAASEnclaveProvider.java | 4 +- .../sqlserver/jdbc/SQLServerBulkCopy.java | 2 +- .../sqlserver/jdbc/SQLServerClob.java | 3 +- .../sqlserver/jdbc/SQLServerConnection.java | 18 ++++---- .../jdbc/SQLServerConnectionPoolProxy.java | 8 ++-- .../sqlserver/jdbc/SQLServerDataSource.java | 41 +++++++++++++----- .../sqlserver/jdbc/SQLServerDataTable.java | 7 ++-- .../jdbc/SQLServerDatabaseMetaData.java | 12 ------ .../sqlserver/jdbc/SQLServerDriver.java | 7 ++-- .../sqlserver/jdbc/SQLServerException.java | 27 ++++++------ .../sqlserver/jdbc/SQLServerJdbc42.java | 5 +++ .../sqlserver/jdbc/SQLServerJdbc43.java | 4 ++ .../sqlserver/jdbc/SQLServerMSAL4JUtils.java | 4 ++ .../jdbc/SQLServerParameterMetaData.java | 10 ++--- .../sqlserver/jdbc/SQLServerParser.java | 4 ++ .../jdbc/SQLServerPreparedStatement.java | 16 +++---- .../sqlserver/jdbc/SQLServerResultSet.java | 3 ++ .../sqlserver/jdbc/SimpleInputStream.java | 4 ++ .../com/microsoft/sqlserver/jdbc/Util.java | 4 ++ .../java/com/microsoft/sqlserver/jdbc/cache | 42 +++++++++++++++++++ .../com/microsoft/sqlserver/jdbc/dtv.java | 22 +++++----- .../microsoft/sqlserver/jdbc/tdsparser.java | 5 +++ 23 files changed, 169 insertions(+), 88 deletions(-) create mode 100644 src/main/java/com/microsoft/sqlserver/jdbc/cache diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerEnclaveProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerEnclaveProvider.java index a09f58881..55a551ea5 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerEnclaveProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/ISQLServerEnclaveProvider.java @@ -38,6 +38,7 @@ import java.util.Hashtable; import java.util.Map; import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import javax.crypto.KeyAgreement; @@ -501,10 +502,10 @@ long getCounter() { final class EnclaveSessionCache { - private Hashtable sessionCache; + private ConcurrentHashMap sessionCache; EnclaveSessionCache() { - sessionCache = new Hashtable<>(0); + sessionCache = new ConcurrentHashMap<>(0); } void addEntry(String servername, String catalog, String attestationUrl, BaseAttestationRequest b, diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAASEnclaveProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAASEnclaveProvider.java index c178ab5b4..73471767c 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAASEnclaveProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAASEnclaveProvider.java @@ -26,7 +26,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; -import java.util.Hashtable; +import java.util.concurrent.ConcurrentHashMap; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -243,7 +243,7 @@ JsonArray getCertificates() { class AASAttestationResponse extends BaseAttestationResponse { private byte[] attestationToken; - private static Hashtable certificateCache = new Hashtable<>(); + private static ConcurrentHashMap certificateCache = new ConcurrentHashMap<>(); AASAttestationResponse(byte[] b) throws SQLServerException { /*- diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java index b4b663a6d..e828705f4 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java @@ -221,7 +221,7 @@ class BulkColumnMetaData { this.dateTimeFormatter = dateTimeFormatter; } - BulkColumnMetaData(Column column, String collationName, String encryptionType) throws SQLServerException { + BulkColumnMetaData(Column column, String collationName, String encryptionType) { this(column); this.collationName = collationName; this.encryptionType = encryptionType; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java index 781163066..c504df190 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java @@ -14,7 +14,6 @@ import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; -import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.Clob; @@ -596,7 +595,7 @@ public int setString(long pos, String str, int offset, int len) throws SQLExcept // allowed DataTypes.getCheckedLength(con, getJdbcType(), pos + len, false); - if (!(pos + len <= Integer.MAX_VALUE)) { + if (pos + len > Integer.MAX_VALUE) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidLength")); Object[] msgArgs = {pos}; SQLServerException.makeFromDriverError(con, null, form.format(msgArgs), null, true); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 12c02f959..fa9359903 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -6138,6 +6138,7 @@ final class LogonProcessor extends TDSTokenHandler { this.loginAckToken = null; } + @Override boolean onSSPI(TDSReader tdsReader) throws SQLServerException { StreamSSPI ack = new StreamSSPI(); ack.setFromTDS(tdsReader); @@ -6150,6 +6151,7 @@ boolean onSSPI(TDSReader tdsReader) throws SQLServerException { return true; } + @Override boolean onLoginAck(TDSReader tdsReader) throws SQLServerException { loginAckToken = new StreamLoginAck(); loginAckToken.setFromTDS(tdsReader); @@ -7285,11 +7287,9 @@ String replaceParameterMarkers(String sqlSrc, int[] paramPositions, Parameter[] dstBegin += makeParamName(nParam++, sqlDst, dstBegin); srcBegin = srcEnd + 1; - if (params[paramIndex++].isOutput()) { - if (!isReturnValueSyntax || paramIndex > 1) { - System.arraycopy(OUT, 0, sqlDst, dstBegin, OUT.length); - dstBegin += OUT.length; - } + if (params[paramIndex++].isOutput() && (!isReturnValueSyntax || paramIndex > 1)) { + System.arraycopy(OUT, 0, sqlDst, dstBegin, OUT.length); + dstBegin += OUT.length; } } @@ -7719,8 +7719,8 @@ public void setStatementPoolingCacheSize(int value) { } /** - * Deprecated. Time-to-live is no longer supported for the cached Managed Identity tokens. - * This method will always return 0 and is for backwards compatibility only. + * @deprecated Time-to-live is no longer supported for the cached Managed Identity tokens. + * This method will always return 0 and is for backwards compatibility only. */ @Deprecated @Override @@ -7729,8 +7729,8 @@ public int getMsiTokenCacheTtl() { } /** - * Deprecated. Time-to-live is no longer supported for the cached Managed Identity tokens. - * This method is a no-op for backwards compatibility only. + * @deprecated Time-to-live is no longer supported for the cached Managed Identity tokens. + * This method is a no-op for backwards compatibility only. */ @Deprecated @Override diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnectionPoolProxy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnectionPoolProxy.java index a2b386c8c..0cbb4a9c6 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnectionPoolProxy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnectionPoolProxy.java @@ -644,8 +644,8 @@ public String getIPAddressPreference() { } /** - * Deprecated. Time-to-live is no longer supported for the cached Managed Identity tokens. - * This method will always return 0 and is for backwards compatibility only. + * @deprecated Time-to-live is no longer supported for the cached Managed Identity tokens. + * This method will always return 0 and is for backwards compatibility only. */ @Deprecated @Override @@ -654,8 +654,8 @@ public int getMsiTokenCacheTtl() { } /** - * Deprecated. Time-to-live is no longer supported for the cached Managed Identity tokens. - * This method is a no-op for backwards compatibility only. + * @deprecated Time-to-live is no longer supported for the cached Managed Identity tokens. + * This method is a no-op for backwards compatibility only. */ @Deprecated @Override diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSource.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSource.java index 4e38b6fca..3b37a0991 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSource.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSource.java @@ -312,6 +312,9 @@ public void setEncrypt(String encryptOption) { setStringProperty(connectionProps, SQLServerDriverStringProperty.ENCRYPT.toString(), encryptOption); } + /** + * @deprecated + */ @Override @Deprecated public void setEncrypt(boolean encryptOption) { @@ -524,14 +527,17 @@ public boolean getSendTimeAsDatetime() { return getBooleanProperty(connectionProps, SQLServerDriverBooleanProperty.SEND_TIME_AS_DATETIME.toString(), SQLServerDriverBooleanProperty.SEND_TIME_AS_DATETIME.getDefaultValue()); } + @Override public void setDatetimeParameterType(String datetimeParameterType) { - setStringProperty(connectionProps, SQLServerDriverStringProperty.DATETIME_DATATYPE.toString(), datetimeParameterType); + setStringProperty(connectionProps, SQLServerDriverStringProperty.DATETIME_DATATYPE.toString(), + datetimeParameterType); } @Override public String getDatetimeParameterType() { - return getStringProperty(connectionProps, SQLServerDriverStringProperty.DATETIME_DATATYPE.toString(), SQLServerDriverStringProperty.DATETIME_DATATYPE.getDefaultValue()); + return getStringProperty(connectionProps, SQLServerDriverStringProperty.DATETIME_DATATYPE.toString(), + SQLServerDriverStringProperty.DATETIME_DATATYPE.getDefaultValue()); } @Override @@ -992,6 +998,9 @@ public boolean getUseBulkCopyForBatchInsert() { SQLServerDriverBooleanProperty.USE_BULK_COPY_FOR_BATCH_INSERT.getDefaultValue()); } + /** + * @deprecated + */ @Override @Deprecated public void setJASSConfigurationName(String configurationName) { @@ -999,6 +1008,9 @@ public void setJASSConfigurationName(String configurationName) { configurationName); } + /** + * @deprecated + */ @Override @Deprecated public String getJASSConfigurationName() { @@ -1019,9 +1031,9 @@ public String getJAASConfigurationName() { } /** - * This method is deprecated. Use {@link SQLServerDataSource#setUser(String user)} instead. + * @deprecated This method is deprecated. Use {@link SQLServerDataSource#setUser(String user)} instead. * - * Sets the client id to be used to retrieve the access token for a user-assigned Managed Identity. + * Sets the client id to be used to retrieve the access token for a user-assigned Managed Identity. * * @param managedIdentityClientId * Client ID of the user-assigned Managed Identity. @@ -1034,9 +1046,9 @@ public void setMSIClientId(String managedIdentityClientId) { } /** - * This method is deprecated. Use {@link SQLServerDataSource#getUser()} instead. + * @deprecated This method is deprecated. Use {@link SQLServerDataSource#getUser()} instead. * - * Returns the value for the connection property 'msiClientId'. + * Returns the value for the connection property 'msiClientId'. * * @return msiClientId property value */ @@ -1138,6 +1150,9 @@ public void setClientKeyPassword(String password) { setStringProperty(connectionProps, SQLServerDriverStringProperty.CLIENT_KEY_PASSWORD.toString(), password); } + /** + * @deprecated + */ @Override @Deprecated public String getAADSecurePrincipalId() { @@ -1145,6 +1160,9 @@ public String getAADSecurePrincipalId() { SQLServerDriverStringProperty.AAD_SECURE_PRINCIPAL_ID.getDefaultValue()); } + /** + * @deprecated + */ @Override @Deprecated public void setAADSecurePrincipalId(String AADSecurePrincipalId) { @@ -1152,6 +1170,9 @@ public void setAADSecurePrincipalId(String AADSecurePrincipalId) { AADSecurePrincipalId); } + /** + * @deprecated + */ @Override @Deprecated public void setAADSecurePrincipalSecret(String AADSecurePrincipalSecret) { @@ -1218,7 +1239,7 @@ public String getPrepareMethod() { } /** - * Deprecated. Time-to-live is no longer supported for the cached Managed Identity tokens. + * @deprecated Time-to-live is no longer supported for the cached Managed Identity tokens. * This method will always return 0 and is for backwards compatibility only. */ @Deprecated @@ -1226,8 +1247,8 @@ public String getPrepareMethod() { public void setMsiTokenCacheTtl(int timeToLive) {} /** - * Deprecated. Time-to-live is no longer supported for the cached Managed Identity tokens. - * This method is a no-op for backwards compatibility only. + * @deprecated Time-to-live is no longer supported for the cached Managed Identity tokens. + * This method is a no-op for backwards compatibility only. */ @Deprecated @Override @@ -1311,7 +1332,7 @@ private String getStringProperty(Properties props, String propKey, String defaul private void setIntProperty(Properties props, String propKey, int propValue) { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) loggerExternal.entering(getClassNameLogging(), "set" + propKey, propValue); - props.setProperty(propKey, Integer.valueOf(propValue).toString()); + props.setProperty(propKey, Integer.toString(propValue)); loggerExternal.exiting(getClassNameLogging(), "set" + propKey); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java index 87564204a..6abdaa174 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java @@ -21,6 +21,7 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; + /** * Represents the data table for SQL Server. */ @@ -132,9 +133,9 @@ public void addColumnMetadata(SQLServerDataColumn column) throws SQLServerExcept public void addRow(Object... values) throws SQLServerException { lock.lock(); try { - int columnCount = columnMetadata.size(); + int count = columnMetadata.size(); - if ((null != values) && values.length > columnCount) { + if ((null != values) && values.length > count) { MessageFormat form = new MessageFormat( SQLServerException.getErrString("R_moreDataInRowThanColumnInTVP")); Object[] msgArgs = {}; @@ -142,7 +143,7 @@ public void addRow(Object... values) throws SQLServerException { } Iterator> columnsIterator = columnMetadata.entrySet().iterator(); - Object[] rowValues = new Object[columnCount]; + Object[] rowValues = new Object[count]; int currentColumn = 0; while (columnsIterator.hasNext()) { Object val = null; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java index 069e4f131..4d92b9bac 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java @@ -180,11 +180,6 @@ private void checkClosed() throws SQLServerException { } private static final String ASC_OR_DESC = "ASC_OR_DESC"; - private static final String ATTR_NAME = "ATTR_NAME"; - private static final String ATTR_TYPE_NAME = "ATTR_TYPE_NAME"; - private static final String ATTR_SIZE = "ATTR_SIZE"; - private static final String ATTR_DEF = "ATTR_DEF"; - private static final String BASE_TYPE = "BASE_TYPE"; private static final String BUFFER_LENGTH = "BUFFER_LENGTH"; private static final String CARDINALITY = "CARDINALITY"; private static final String CHAR_OCTET_LENGTH = "CHAR_OCTET_LENGTH"; @@ -241,19 +236,12 @@ private void checkClosed() throws SQLServerException { private static final String SOURCE_DATA_TYPE = "SOURCE_DATA_TYPE"; private static final String SQL_DATA_TYPE = "SQL_DATA_TYPE"; private static final String SQL_DATETIME_SUB = "SQL_DATETIME_SUB"; - private static final String SS_DATA_TYPE = "SS_DATA_TYPE"; - private static final String SUPERTABLE_NAME = "SUPERTABLE_NAME"; - private static final String SUPERTYPE_CAT = "SUPERTYPE_CAT"; - private static final String SUPERTYPE_NAME = "SUPERTYPE_NAME"; - private static final String SUPERTYPE_SCHEM = "SUPERTYPE_SCHEM"; private static final String TABLE_CAT = "TABLE_CAT"; private static final String TABLE_NAME = "TABLE_NAME"; private static final String TABLE_SCHEM = "TABLE_SCHEM"; private static final String TABLE_TYPE = "TABLE_TYPE"; private static final String TYPE = "TYPE"; - private static final String TYPE_CAT = "TYPE_CAT"; private static final String TYPE_NAME = "TYPE_NAME"; - private static final String TYPE_SCHEM = "TYPE_SCHEM"; private static final String UPDATE_RULE = "UPDATE_RULE"; private static final String FUNCTION_CAT = "FUNCTION_CAT"; private static final String FUNCTION_NAME = "FUNCTION_NAME"; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java index 48ded26bb..b52c3abae 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java @@ -430,7 +430,7 @@ public String toString() { } static ApplicationIntent valueOfString(String value) throws SQLServerException { - ApplicationIntent applicationIntent = ApplicationIntent.READ_WRITE; + ApplicationIntent applicationIntent; assert value != null; // handling turkish i issues value = value.toUpperCase(Locale.US).toLowerCase(Locale.US); @@ -473,7 +473,7 @@ public String toString() { } static DatetimeType valueOfString(String value) throws SQLServerException { - DatetimeType datetimeType = DatetimeType.DATETIME2; + DatetimeType datetimeType; assert value != null; @@ -836,8 +836,7 @@ public final class SQLServerDriver implements java.sql.Driver { TRUE_FALSE), new SQLServerDriverPropertyInfo(SQLServerDriverStringProperty.DATETIME_DATATYPE.toString(), SQLServerDriverStringProperty.DATETIME_DATATYPE.getDefaultValue(), false, - new String[] {DatetimeType.DATETIME.toString(), - DatetimeType.DATETIME2.toString(), + new String[] {DatetimeType.DATETIME.toString(), DatetimeType.DATETIME2.toString(), DatetimeType.DATETIMEOFFSET.toString()}), new SQLServerDriverPropertyInfo(SQLServerDriverStringProperty.USER.toString(), SQLServerDriverStringProperty.USER.getDefaultValue(), true, null), diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java index 0e316134e..92c51a1fc 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java @@ -115,22 +115,21 @@ private void logException(Object o, String errText, boolean bStack) { if (exLogger.isLoggable(Level.FINE)) exLogger.fine("*** SQLException:" + id + " " + this.toString() + " " + errText); - if (bStack) { - if (exLogger.isLoggable(Level.FINE)) { - StringBuilder sb = new StringBuilder(100); - StackTraceElement st[] = this.getStackTrace(); - for (StackTraceElement aSt : st) - sb.append(aSt.toString()); - Throwable t = this.getCause(); - if (t != null) { - sb.append("\n caused by ").append(t).append("\n"); - StackTraceElement tst[] = t.getStackTrace(); - for (StackTraceElement aTst : tst) - sb.append(aTst.toString()); - } - exLogger.fine(sb.toString()); + if (bStack && exLogger.isLoggable(Level.FINE)) { + StringBuilder sb = new StringBuilder(100); + StackTraceElement st[] = this.getStackTrace(); + for (StackTraceElement aSt : st) + sb.append(aSt.toString()); + Throwable t = this.getCause(); + if (t != null) { + sb.append("\n caused by ").append(t).append("\n"); + StackTraceElement tst[] = t.getStackTrace(); + for (StackTraceElement aTst : tst) + sb.append(aTst.toString()); } + exLogger.fine(sb.toString()); } + if (SQLServerException.getErrString("R_queryTimedOut").equals(errText)) { this.setDriverErrorCode(SQLServerException.ERROR_QUERY_TIMEOUT); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerJdbc42.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerJdbc42.java index 118234199..a4cdd78e8 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerJdbc42.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerJdbc42.java @@ -23,6 +23,11 @@ final class DriverJDBCVersion { static final int MAJOR = 4; static final int MINOR = 2; + private DriverJDBCVersion() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + + private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.DriverJDBCVersion"); static final boolean checkSupportsJDBC43() { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerJdbc43.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerJdbc43.java index 73f5f8adb..978c0c834 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerJdbc43.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerJdbc43.java @@ -28,6 +28,10 @@ final class DriverJDBCVersion { static final int MAJOR = 4; static final int MINOR = 3; + private DriverJDBCVersion() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.DriverJDBCVersion"); static final boolean checkSupportsJDBC43() { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerMSAL4JUtils.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerMSAL4JUtils.java index cf2b8d6b6..fc58debf7 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerMSAL4JUtils.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerMSAL4JUtils.java @@ -43,6 +43,10 @@ class SQLServerMSAL4JUtils { static final String SLASH_DEFAULT = "/.default"; static final String ACCESS_TOKEN_EXPIRE = " Access token expires on the following date: "; + private SQLServerMSAL4JUtils() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + private static final java.util.logging.Logger logger = java.util.logging.Logger .getLogger("com.microsoft.sqlserver.jdbc.SQLServerMSAL4JUtils"); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java index ab997181c..139c9a10d 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java @@ -209,12 +209,10 @@ private void parseFMTQueryMeta(ResultSetMetaData md, SQLServerFMTQuery f) throws */ if ("*".equals(columns.get(i))) { for (int j = 0; j < params.get(valueListOffset).size(); j++) { - if ("?".equals(params.get(valueListOffset).get(j))) { - if (!md.isAutoIncrement(mdIndex + j)) { - QueryMeta qm = getQueryMetaFromResultSetMetaData(md, mdIndex + j); - queryMetaMap.put(mapIndex++, qm); - i++; - } + if ("?".equals(params.get(valueListOffset).get(j)) && (!md.isAutoIncrement(mdIndex + j))) { + QueryMeta qm = getQueryMetaFromResultSetMetaData(md, mdIndex + j); + queryMetaMap.put(mapIndex++, qm); + i++; } } mdIndex += params.get(valueListOffset).size(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParser.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParser.java index e3dac71d3..bdd308d4f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParser.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParser.java @@ -19,6 +19,10 @@ final class SQLServerParser { + private SQLServerParser() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + private static final List SELECT_DELIMITING_WORDS = Arrays.asList(SQLServerLexer.WHERE, SQLServerLexer.GROUP, SQLServerLexer.HAVING, SQLServerLexer.ORDER, SQLServerLexer.OPTION); private static final List INSERT_DELIMITING_WORDS = Arrays.asList(SQLServerLexer.VALUES, diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 7f3df88c3..38a92a04c 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -2470,7 +2470,7 @@ private String parseUserSQLForTableNameDW(boolean hasInsertBeenFound, boolean ha // If it's encapsulated in [] or "", we need be more careful with parsing as anything could go into []/"". // For ] or ", they can be escaped by ]] or "", watch out for this too. if (checkSQLLength(1) && "[".equalsIgnoreCase(localUserSQL.substring(0, 1))) { - int tempint = localUserSQL.indexOf("]", 1); + int tempint = localUserSQL.indexOf(']', 1); // ] has not been found, this is wrong. if (tempint < 0) { @@ -2481,7 +2481,7 @@ private String parseUserSQLForTableNameDW(boolean hasInsertBeenFound, boolean ha // keep checking if it's escaped while (tempint >= 0 && checkSQLLength(tempint + 2) && localUserSQL.charAt(tempint + 1) == ']') { - tempint = localUserSQL.indexOf("]", tempint + 2); + tempint = localUserSQL.indexOf(']', tempint + 2); } // we've found a ] that is actually trying to close the square bracket. @@ -2493,7 +2493,7 @@ private String parseUserSQLForTableNameDW(boolean hasInsertBeenFound, boolean ha // do the same for "" if (checkSQLLength(1) && "\"".equalsIgnoreCase(localUserSQL.substring(0, 1))) { - int tempint = localUserSQL.indexOf("\"", 1); + int tempint = localUserSQL.indexOf('"', 1); // \" has not been found, this is wrong. if (tempint < 0) { @@ -2504,7 +2504,7 @@ private String parseUserSQLForTableNameDW(boolean hasInsertBeenFound, boolean ha // keep checking if it's escaped while (tempint >= 0 && checkSQLLength(tempint + 2) && localUserSQL.charAt(tempint + 1) == '\"') { - tempint = localUserSQL.indexOf("\"", tempint + 2); + tempint = localUserSQL.indexOf('"', tempint + 2); } // we've found a " that is actually trying to close the quote. @@ -2571,7 +2571,7 @@ private ArrayList parseUserSQLForColumnListDWHelper(ArrayList li // handle [] case if (localUserSQL.charAt(0) == '[') { - int tempint = localUserSQL.indexOf("]", 1); + int tempint = localUserSQL.indexOf(']', 1); // ] has not been found, this is wrong. if (tempint < 0) { @@ -2583,7 +2583,7 @@ private ArrayList parseUserSQLForColumnListDWHelper(ArrayList li // keep checking if it's escaped while (tempint >= 0 && checkSQLLength(tempint + 2) && localUserSQL.charAt(tempint + 1) == ']') { localUserSQL = localUserSQL.substring(0, tempint) + localUserSQL.substring(tempint + 1); - tempint = localUserSQL.indexOf("]", tempint + 1); + tempint = localUserSQL.indexOf(']', tempint + 1); } // we've found a ] that is actually trying to close the square bracket. @@ -2595,7 +2595,7 @@ private ArrayList parseUserSQLForColumnListDWHelper(ArrayList li // handle "" case if (localUserSQL.charAt(0) == '\"') { - int tempint = localUserSQL.indexOf("\"", 1); + int tempint = localUserSQL.indexOf('"', 1); // \" has not been found, this is wrong. if (tempint < 0) { @@ -2607,7 +2607,7 @@ private ArrayList parseUserSQLForColumnListDWHelper(ArrayList li // keep checking if it's escaped while (tempint >= 0 && checkSQLLength(tempint + 2) && localUserSQL.charAt(tempint + 1) == '\"') { localUserSQL = localUserSQL.substring(0, tempint) + localUserSQL.substring(tempint + 1); - tempint = localUserSQL.indexOf("\"", tempint + 1); + tempint = localUserSQL.indexOf('"', tempint + 1); } // we've found a " that is actually trying to close the quote. diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java index 0d1a154f9..7c8b5c933 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java @@ -289,18 +289,21 @@ final Column[] buildColumns() throws SQLServerException { super(name); } + @Override boolean onColInfo(TDSReader tdsReader) throws SQLServerException { colInfo = new StreamColInfo(); colInfo.setFromTDS(tdsReader); return true; } + @Override boolean onTabName(TDSReader tdsReader) throws SQLServerException { tabName = new StreamTabName(); tabName.setFromTDS(tdsReader); return true; } + @Override boolean onColMetaData(TDSReader tdsReader) throws SQLServerException { columnMetaData = new StreamColumns( Util.shouldHonorAEForRead(stmt.stmtColumnEncriptionSetting, stmt.connection)); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SimpleInputStream.java b/src/main/java/com/microsoft/sqlserver/jdbc/SimpleInputStream.java index 2742079bf..fb602266f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SimpleInputStream.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SimpleInputStream.java @@ -220,6 +220,7 @@ public long skip(long n) throws IOException { * @exception IOException * if an I/O error occurs. */ + @Override public int available() throws IOException { checkClosed(); assert streamPos <= payloadLength; @@ -258,6 +259,7 @@ public int read() throws IOException { * @exception IOException * if an I/O error occurs. */ + @Override public int read(byte[] b) throws IOException { checkClosed(); return read(b, 0, b.length); @@ -317,6 +319,7 @@ public int read(byte[] b, int offset, int maxBytes) throws IOException { * @param readLimit * the number of bytes to hold */ + @Override public void mark(int readLimit) { if (null != tdsReader && readLimit > 0) { currentMark = tdsReader.mark(); @@ -331,6 +334,7 @@ public void mark(int readLimit) { * @exception IOException * if an I/O error occurs. */ + @Override public void reset() throws IOException { resetHelper(); streamPos = markedStreamPos; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java index 1cf9eedc7..89dd37bb9 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java @@ -36,6 +36,10 @@ final class Util { final static String ACTIVITY_ID_TRACE_PROPERTY = "com.microsoft.sqlserver.jdbc.traceactivity"; + private Util() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + // The JRE is identified by the string below so that the driver can make // any vendor or version specific decisions static final String SYSTEM_JRE = System.getProperty("java.vendor") + " " + System.getProperty("java.version"); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/cache b/src/main/java/com/microsoft/sqlserver/jdbc/cache new file mode 100644 index 000000000..987a39def --- /dev/null +++ b/src/main/java/com/microsoft/sqlserver/jdbc/cache @@ -0,0 +1,42 @@ +# This viminfo file was generated by Vim 8.1. +# You may edit it if you're careful! + +# Viminfo version +|1,4 + +# Value of 'encoding' when this file was written +*encoding=utf-8 + + +# hlsearch on (H) or off (h): +~h +# Command Line History (newest to oldest): + +# Search String History (newest to oldest): + +# Expression History (newest to oldest): + +# Input Line History (newest to oldest): + +# Debug Line History (newest to oldest): + +# Registers: + +# File marks: +'0 3 0 /mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep +|4,48,3,0,1673914526,"/mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep" + +# Jumplist (newest first): +-' 3 0 /mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep +|4,39,3,0,1673914526,"/mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep" +-' 1 0 /mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep +|4,39,1,0,1673914511,"/mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep" + +# History of marks within files (newest to oldest): + +> /mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep + * 1673914524 0 + " 3 0 + ^ 3 1 + . 3 0 + + 3 0 diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java b/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java index 12e8f5d90..c5716f9b4 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java @@ -1985,7 +1985,7 @@ final class SetValueOp extends DTVExecuteOp { } void execute(DTV dtv, String strValue) throws SQLServerException { - JDBCType jdbcType = dtv.getJdbcType(); + JDBCType type = dtv.getJdbcType(); // Normally we let the server convert the string to whatever backend // type it is going into. However, if the app says that the string @@ -1993,14 +1993,14 @@ void execute(DTV dtv, String strValue) throws SQLServerException { // now so that GetTypeDefinitionOp can generate a type definition // with the correct scale. - if ((JDBCType.DECIMAL == jdbcType) || (JDBCType.NUMERIC == jdbcType) || (JDBCType.MONEY == jdbcType) - || (JDBCType.SMALLMONEY == jdbcType)) { + if ((JDBCType.DECIMAL == type) || (JDBCType.NUMERIC == type) || (JDBCType.MONEY == type) + || (JDBCType.SMALLMONEY == type)) { assert null != strValue; try { dtv.setValue(new BigDecimal(strValue), JavaType.BIGDECIMAL); } catch (NumberFormatException e) { - DataTypes.throwConversionError("String", jdbcType.toString()); + DataTypes.throwConversionError("String", type.toString()); } } @@ -2008,7 +2008,7 @@ void execute(DTV dtv, String strValue) throws SQLServerException { // type, but we are being told that it is binary, then we need to convert // the hexized text value to binary here because the server doesn't do // this conversion for us. - else if (jdbcType.isBinary()) { + else if (type.isBinary()) { assert null != strValue; dtv.setValue(ParameterUtils.hexToBin(strValue), JavaType.BYTEARRAY); } @@ -2017,8 +2017,8 @@ else if (jdbcType.isBinary()) { // then do the conversion now so that the decision to use a "short" or "long" // SSType (i.e. VARCHAR vs. TEXT/VARCHAR(max)) is based on the exact length of // the MBCS value (in bytes). - else if (null != collation && (JDBCType.CHAR == jdbcType || JDBCType.VARCHAR == jdbcType - || JDBCType.LONGVARCHAR == jdbcType || JDBCType.CLOB == jdbcType)) { + else if (null != collation && (JDBCType.CHAR == type || JDBCType.VARCHAR == type + || JDBCType.LONGVARCHAR == type || JDBCType.CLOB == type)) { byte[] nativeEncoding = null; if (null != strValue) { @@ -2204,7 +2204,7 @@ void execute(DTV dtv, Reader readerValue) throws SQLServerException { // executeOp should have handled null Reader as a null String. assert null != readerValue; - JDBCType jdbcType = dtv.getJdbcType(); + JDBCType type = dtv.getJdbcType(); long readerLength = DataTypes.getCheckedLength(con, dtv.getJdbcType(), dtv.getStreamSetterArgs().getLength(), true); @@ -2213,7 +2213,7 @@ void execute(DTV dtv, Reader readerValue) throws SQLServerException { // type, but we are being told that it is binary, then we need to convert // the hexized text value to binary here because the server doesn't do // this conversion for us. - jdbcType.isBinary()) { + type.isBinary()) { String stringValue = DDC.convertReaderToString(readerValue, (int) readerLength); // If we were given an input stream length that we had to match and @@ -2229,8 +2229,8 @@ void execute(DTV dtv, Reader readerValue) throws SQLServerException { } // If the reader value is to be sent as MBCS, then convert the value to an MBCS InputStream - else if (null != collation && (JDBCType.CHAR == jdbcType || JDBCType.VARCHAR == jdbcType - || JDBCType.LONGVARCHAR == jdbcType || JDBCType.CLOB == jdbcType)) { + else if (null != collation && (JDBCType.CHAR == type || JDBCType.VARCHAR == type + || JDBCType.LONGVARCHAR == type || JDBCType.CLOB == type)) { ReaderInputStream streamValue = new ReaderInputStream(readerValue, collation.getCharset(), readerLength); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/tdsparser.java b/src/main/java/com/microsoft/sqlserver/jdbc/tdsparser.java index 8e8b5d860..3da844f68 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/tdsparser.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/tdsparser.java @@ -13,6 +13,11 @@ * The top level TDS parser class. */ final class TDSParser { + + private TDSParser() { + throw new UnsupportedOperationException(SQLServerException.getErrString("R_notSupported")); + } + /** TDS protocol diagnostics logger */ private static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.TOKEN"); From ba68f3457522a88e8efaa340b81d79ddf9f62d5b Mon Sep 17 00:00:00 2001 From: lilgreenbird Date: Tue, 17 Jan 2023 16:46:43 -0800 Subject: [PATCH 4/5] update method method --- .../sqlserver/jdbc/AlwaysEncrypted/MultiUserAKVTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/MultiUserAKVTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/MultiUserAKVTest.java index b597c2052..61931c777 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/MultiUserAKVTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/MultiUserAKVTest.java @@ -587,7 +587,7 @@ private byte[] signColumnMasterKeyMetadata(SQLServerColumnEncryptionAzureKeyVaul assertTrue(dataToSign.length > 0); - Method method = provider.getClass().getDeclaredMethod("AzureKeyVaultSignHashedData", byte[].class, + Method method = provider.getClass().getDeclaredMethod("azureKeyVaultSignHashedData", byte[].class, String.class); method.setAccessible(true); From 6bf40f567064cc2b03d13716d0348922cdb8abdf Mon Sep 17 00:00:00 2001 From: lilgreenbird Date: Wed, 18 Jan 2023 14:55:14 -0800 Subject: [PATCH 5/5] removed junk file --- .../java/com/microsoft/sqlserver/jdbc/cache | 42 ------------------- 1 file changed, 42 deletions(-) delete mode 100644 src/main/java/com/microsoft/sqlserver/jdbc/cache diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/cache b/src/main/java/com/microsoft/sqlserver/jdbc/cache deleted file mode 100644 index 987a39def..000000000 --- a/src/main/java/com/microsoft/sqlserver/jdbc/cache +++ /dev/null @@ -1,42 +0,0 @@ -# This viminfo file was generated by Vim 8.1. -# You may edit it if you're careful! - -# Viminfo version -|1,4 - -# Value of 'encoding' when this file was written -*encoding=utf-8 - - -# hlsearch on (H) or off (h): -~h -# Command Line History (newest to oldest): - -# Search String History (newest to oldest): - -# Expression History (newest to oldest): - -# Input Line History (newest to oldest): - -# Debug Line History (newest to oldest): - -# Registers: - -# File marks: -'0 3 0 /mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep -|4,48,3,0,1673914526,"/mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep" - -# Jumplist (newest first): --' 3 0 /mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep -|4,39,3,0,1673914526,"/mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep" --' 1 0 /mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep -|4,39,1,0,1673914511,"/mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep" - -# History of marks within files (newest to oldest): - -> /mnt/c/mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServergrep - * 1673914524 0 - " 3 0 - ^ 3 1 - . 3 0 - + 3 0