Skip to content

Commit

Permalink
Updates for java 8 compliance (#1328)
Browse files Browse the repository at this point in the history
  • Loading branch information
lilgreenbird authored May 22, 2020
1 parent f857e25 commit 1b52685
Show file tree
Hide file tree
Showing 10 changed files with 50 additions and 51 deletions.
5 changes: 2 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -125,16 +125,13 @@
<version>${bouncycastle.bcprov.version}</version>
<optional>true</optional>
</dependency>

<!-- dependencies for Client Certificate Authentication -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>${bouncycastle.bcpkix.version}</version>
<optional>true</optional>
</dependency>


<!-- dependencies provided by an OSGi-Framework -->
<dependency>
<groupId>org.osgi</groupId>
Expand Down Expand Up @@ -278,6 +275,8 @@
<configuration>
<!-- Exclude [xJDBC42] For tests not compatible with JDBC 4.2 Specifications -->
<excludedGroups>${excludedGroups}, xJDBC42</excludedGroups>
<!-- needs to be overridden as illegal-access and MaxPermSize=256m not valid in java 8 -->
<argLine>-Xmx1024m</argLine>
</configuration>
</plugin>
</plugins>
Expand Down
24 changes: 12 additions & 12 deletions src/main/java/com/microsoft/sqlserver/jdbc/DDC.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@


/**
* Utility class for all Data Dependant Conversions (DDC).
* Utility class for all Data Dependent Conversions (DDC).
*/

final class DDC {
Expand Down Expand Up @@ -348,9 +348,9 @@ static final byte[] convertMoneyToBytes(BigDecimal bigDecimalVal, int bLength) {
byte[] longbArray = new byte[bLength];
Util.writeLong(bi.longValue(), longbArray, 0);
/*
* TDS 2.2.5.5.1.4 Fixed-Point Numbers
* Money is represented as a 8 byte signed integer, with one 4-byte integer that represents
* the more significant half, and one 4-byte integer that represents the less significant half.
* TDS 2.2.5.5.1.4 Fixed-Point Numbers Money is represented as a 8 byte signed integer, with one 4-byte
* integer that represents the more significant half, and one 4-byte integer that represents the less
* significant half.
*/
System.arraycopy(longbArray, 0, valueBytes, 4, 4);
System.arraycopy(longbArray, 4, valueBytes, 0, 4);
Expand Down Expand Up @@ -653,9 +653,9 @@ private static LocalDateTime parseStringIntoLDT(String s) {
if (firstDash > 0 && secondDash > 0 && secondDash < dividingSpace - 1) {
if (firstDash == YEAR_LENGTH && (secondDash - firstDash > 1 && secondDash - firstDash <= MONTH_LENGTH + 1)
&& (dividingSpace - secondDash > 1 && dividingSpace - secondDash <= DAY_LENGTH + 1)) {
year = Integer.parseInt(s, 0, firstDash, 10);
month = Integer.parseInt(s, firstDash + 1, secondDash, 10);
day = Integer.parseInt(s, secondDash + 1, dividingSpace, 10);
year = Integer.parseInt(s.substring(0, firstDash));
month = Integer.parseInt(s.substring(firstDash + 1, secondDash));
day = Integer.parseInt(s.substring(secondDash + 1, dividingSpace));

if ((month >= 1 && month <= MAX_MONTH) && (day >= 1 && day <= MAX_DAY)) {
parsedDate = true;
Expand All @@ -669,16 +669,16 @@ private static LocalDateTime parseStringIntoLDT(String s) {
// Convert the time; default missing nanos
int len = s.length();
if (firstColon > 0 && secondColon > 0 && secondColon < len - 1) {
hour = Integer.parseInt(s, dividingSpace + 1, firstColon, 10);
minute = Integer.parseInt(s, firstColon + 1, secondColon, 10);
hour = Integer.parseInt(s.substring(dividingSpace + 1, firstColon));
minute = Integer.parseInt(s.substring(firstColon + 1, secondColon));
if (period > 0 && period < len - 1) {
second = Integer.parseInt(s, secondColon + 1, period, 10);
second = Integer.parseInt(s.substring(secondColon + 1, period));
int nanoPrecision = len - (period + 1);
if (nanoPrecision > 9)
throw new java.lang.IllegalArgumentException(formatError);
if (!Character.isDigit(s.charAt(period + 1)))
throw new java.lang.IllegalArgumentException(formatError);
int tmpNanos = Integer.parseInt(s, period + 1, len, 10);
int tmpNanos = Integer.parseInt(s.substring(period + 1, len));
while (nanoPrecision < 9) {
tmpNanos *= 10;
nanoPrecision++;
Expand All @@ -687,7 +687,7 @@ private static LocalDateTime parseStringIntoLDT(String s) {
} else if (period > 0) {
throw new java.lang.IllegalArgumentException(formatError);
} else {
second = Integer.parseInt(s, secondColon + 1, len, 10);
second = Integer.parseInt(s.substring(secondColon + 1, len));
}
} else {
throw new java.lang.IllegalArgumentException(formatError);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigInteger;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
Expand Down Expand Up @@ -153,22 +154,23 @@ private static PrivateKey loadPrivateKeyFromPVK(String keyPath,
ByteBuffer buffer = ByteBuffer.allocate((int) f.length());
try (FileInputStream in = new FileInputStream(f)) {
in.getChannel().read(buffer);
buffer.order(ByteOrder.LITTLE_ENDIAN).rewind();
((Buffer) buffer.order(ByteOrder.LITTLE_ENDIAN)).rewind();

long magic = buffer.getInt() & 0xFFFFFFFFL;
if (PVK_MAGIC != magic) {
SQLServerException.makeFromDriverError(null, magic, SQLServerResource.getResource("R_pvkHeaderError"),
"", false);
}

buffer.position(buffer.position() + 8); // skip reserved and keytype
((Buffer) buffer).position(((Buffer) buffer).position() + 8); // skip reserved and keytype
boolean encrypted = buffer.getInt() != 0;
int saltLength = buffer.getInt();
int keyLength = buffer.getInt();
byte[] salt = new byte[saltLength];
buffer.get(salt);

buffer.position(buffer.position() + 8); // skip btype(1b), version(1b), reserved(2b), and keyalg(4b)
((Buffer) buffer).position(((Buffer) buffer).position() + 8); // skip btype(1b), version(1b), reserved(2b),
// and keyalg(4b)

byte[] key = new byte[keyLength - 8];
buffer.get(key);
Expand All @@ -184,7 +186,7 @@ private static PrivateKey loadPrivateKeyFromPVK(String keyPath,
}

ByteBuffer buff = ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN);
buff.position(RSA2_MAGIC.length); // skip the header
((Buffer) buff).position(RSA2_MAGIC.length); // skip the header

int byteLength = buff.getInt() / 8;
BigInteger publicExponent = BigInteger.valueOf(buff.getInt());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -667,7 +667,7 @@ private static List<String> getTrustedEndpoints() {
boolean append = true;
if (null != mssqlJdbcProperties) {
String endpoints = mssqlJdbcProperties.getProperty(AKV_TRUSTED_ENDPOINTS_KEYWORD);
if (null != endpoints && !endpoints.isBlank()) {
if (null != endpoints && !endpoints.trim().isEmpty()) {
endpoints = endpoints.trim();
// Append if the list starts with a semicolon.
if (';' != endpoints.charAt(0)) {
Expand All @@ -677,7 +677,7 @@ private static List<String> getTrustedEndpoints() {
}
String[] entries = endpoints.split(";");
for (String entry : entries) {
if (null != entry && !entry.isBlank()) {
if (null != entry && !entry.trim().isEmpty()) {
trustedEndpoints.add(entry.trim());
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
*
*/
@RunWith(JUnitPlatform.class)
@Tag(Constants.xJDBC42)
public class JDBC43Test extends AbstractTest {
ShardingKey superShardingKey = null;
ShardingKey shardingKey = null;
Expand Down Expand Up @@ -128,7 +129,6 @@ public void connectionPoolDataSourceTest() throws TestAbortedException, SQLExcep
* @since 1.9
*/
@Test
@Tag(Constants.xJDBC42)
public void setShardingKeyIfValidTest() throws TestAbortedException, SQLException {
try (SQLServerConnection connection43 = (SQLServerConnection43) getConnection()) {
try {
Expand All @@ -152,7 +152,6 @@ public void setShardingKeyIfValidTest() throws TestAbortedException, SQLExceptio
* @since 1.9
*/
@Test
@Tag(Constants.xJDBC42)
public void setShardingKeyTest() throws TestAbortedException, SQLException {
try (SQLServerConnection connection43 = (SQLServerConnection43) getConnection()) {
try {
Expand Down
18 changes: 10 additions & 8 deletions src/test/java/com/microsoft/sqlserver/jdbc/NTLMConnectionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ public static void setUp() throws Exception {
*/
@Test
public void testNTLMBasicConnection() throws SQLException {
try (Connection con1 = dsNTLMLocal.getConnection();
Connection con2 = dsNTLMXA.getConnection();
try (Connection con1 = dsNTLMLocal.getConnection(); Connection con2 = dsNTLMXA.getConnection();
Connection con3 = dsNTLMPool.getConnection();
Connection con4 = PrepUtil.getConnection(connectionStringNTLM)) {
verifyNTLM(con1);
Expand Down Expand Up @@ -372,17 +371,20 @@ private byte[] getChallengeToken(int offset, byte[] badBytes) {

token.put(challengeTargetInfo2);

// update targetinfo len
token.position(ntlmChallengeTargetInfoLenOffset);
token.putShort((short) targetInfoLen); // len
token.putShort((short) targetInfoLen); // maxlen
/*
* update target info - the cast is necessary as JDK 8 calls method Buffer.position(I)LBuffer while in JDK 9+
* calls method ByteBuffer.position(I)LByteBuffer
*/
((java.nio.Buffer) token).position(ntlmChallengeTargetInfoLenOffset);
token.putShort((short) targetInfoLen); // update target info len
token.putShort((short) targetInfoLen); // update target info maxlen

// write bad bytes
if (0 <= offset) {
token.position(offset);
((java.nio.Buffer) token).position(offset);
token.put(badBytes);
} else {
token.position(tokenLen + offset);
((java.nio.Buffer) token).position(tokenLen + offset);
token.put(badBytes);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.util.logging.Logger;
import java.util.stream.Stream;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
Expand Down Expand Up @@ -59,9 +60,8 @@ public void testDriverRegistrationDM() throws SQLException, ClassNotFoundExcepti
current = drivers.nextElement();
DriverManager.deregisterDriver(current);
}
Stream<Driver> currentDrivers = DriverManager.drivers();
Object[] driversArray = currentDrivers.toArray();
assertEquals(0, driversArray.length);
Enumeration<Driver> currentDrivers = DriverManager.getDrivers();
assertEquals(false, currentDrivers.hasMoreElements());
DriverManager.registerDriver(current);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public void testWithSupportedProtocols(String sslProtocol) throws Exception {
// Example, if the highest TLS version enabled in the server is TLSv1.1,
// the connection will fail if we enable only TLSv1.2
assertTrue(e.getMessage().contains(TestResource.getResource("R_noProtocolVersion"))
|| e.getCause().getMessage().contains(TestResource.getResource("R_connectionClosed"))
|| e.getCause().getCause().getMessage().contains(TestResource.getResource("R_connectionClosed")));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1824,7 +1824,7 @@ public void testGetLocalDateTimePriorGregorian() throws Exception {
}
}
}

@Test
public void testNullValuesWithGetObject() throws Exception {
String ldtTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("ldtTable"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,13 @@ public void testLengthAfterStream() throws SQLException, IOException {

@Test
@DisplayName("testClobsVarcharASCII")
@SuppressWarnings("resource")
public void testClobsVarcharASCII() throws SQLException, IOException {
try (Connection conn = getConnection()) {
try (Statement stmt = conn.createStatement()) {
TestUtils.dropTableIfExists(tableName, stmt);

ArrayList<String> lob_data = createRandomStringArray(Constants.LOB.CLOB);
ArrayList<String> recievedDataFromServer = new ArrayList<>();
ArrayList<String> receivedDataFromServer = new ArrayList<>();

createLobTable(stmt, tableName, Constants.LOB.CLOB);
insertData(conn, tableName, lob_data);
Expand All @@ -144,19 +143,18 @@ public void testClobsVarcharASCII() throws SQLException, IOException {
int index = rs.getInt(1);
Clob c = rs.getClob(2);
assertEquals(c.length(), lob_data.get(index).length());
try (InputStream is = c.getAsciiStream();
Scanner s = new Scanner(is, java.nio.charset.StandardCharsets.US_ASCII)
.useDelimiter("\\A")) {
String received = getStringFromInputStream(is, s);// streaming string
assertEquals(lob_data.get(index), received);// compare streamed string to initial string
try (InputStream is = c.getAsciiStream(); Scanner s = new Scanner(is, "US-ASCII")) {
// streaming string
String received = getStringFromInputStream(is, s.useDelimiter("\\A"));
// compare streamed string to initial string
assertEquals(lob_data.get(index), received);
c.free();
recievedDataFromServer.add(received);
receivedDataFromServer.add(received);
}
}
for (int i = 0; i < lob_data.size(); i++) {
assertEquals(recievedDataFromServer.get(i), lob_data.get(i));// compare static string to
// streamed
// string
// compare satic string to streamed string
assertEquals(receivedDataFromServer.get(i), lob_data.get(i));
}
}
} finally {
Expand All @@ -168,7 +166,6 @@ public void testClobsVarcharASCII() throws SQLException, IOException {

}

@SuppressWarnings("resource")
@Test
@DisplayName("testNClobsNVarcharASCII")
public void testNClobsVarcharASCII() throws SQLException, IOException {
Expand All @@ -186,10 +183,9 @@ public void testNClobsVarcharASCII() throws SQLException, IOException {
int index = rs.getInt(1);
NClob c = rs.getNClob(2);
assertEquals(c.length(), lob_data.get(index).length());
try (InputStream is = c.getAsciiStream();
Scanner s = new Scanner(is, java.nio.charset.StandardCharsets.US_ASCII)
.useDelimiter("\\A")) {
String received = getStringFromInputStream(is, s);// NClob AsciiStream is never streamed
try (InputStream is = c.getAsciiStream(); Scanner s = new Scanner(is, "US-ASCII")) {
// nClob AsciiStream is never streamed
String received = getStringFromInputStream(is, s.useDelimiter("\\A"));
c.free();
assertEquals(lob_data.get(index), received);// compare string to initial string
}
Expand Down

0 comments on commit 1b52685

Please sign in to comment.