diff --git a/sharding-core/src/main/java/io/shardingsphere/spi/NewInstanceServiceLoader.java b/sharding-core/src/main/java/io/shardingsphere/spi/NewInstanceServiceLoader.java index abee185144ca6..588e316357341 100644 --- a/sharding-core/src/main/java/io/shardingsphere/spi/NewInstanceServiceLoader.java +++ b/sharding-core/src/main/java/io/shardingsphere/spi/NewInstanceServiceLoader.java @@ -17,9 +17,9 @@ package io.shardingsphere.spi; -import io.shardingsphere.core.exception.ShardingException; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import lombok.SneakyThrows; import java.util.Collection; import java.util.LinkedList; @@ -57,14 +57,11 @@ public static NewInstanceServiceLoader load(final Class service) { * * @return service instances */ + @SneakyThrows public Collection newServiceInstances() { Collection result = new LinkedList<>(); for (Class each : serviceClasses) { - try { - result.add(each.newInstance()); - } catch (final ReflectiveOperationException ex) { - throw new ShardingException(ex); - } + result.add(each.newInstance()); } return result; } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/executor/fixture/ExecutorTestUtil.java b/sharding-core/src/test/java/io/shardingsphere/core/executor/fixture/ExecutorTestUtil.java index 7c17577a0bb1c..1c4f44a6adb66 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/executor/fixture/ExecutorTestUtil.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/executor/fixture/ExecutorTestUtil.java @@ -22,6 +22,7 @@ import io.shardingsphere.core.executor.sql.execute.threadlocal.ExecutorExceptionHandler; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import lombok.SneakyThrows; import java.lang.reflect.Field; @@ -32,7 +33,7 @@ public final class ExecutorTestUtil { * Listen event. * * @param eventCaller event caller - * @param event SQL execution event + * @param event SQL execution event */ public static void listen(final EventCaller eventCaller, final SQLExecutionEvent event) { eventCaller.verifyDataSource(event.getRouteUnit().getDataSourceName()); @@ -46,10 +47,9 @@ public static void listen(final EventCaller eventCaller, final SQLExecutionEvent /** * Clear thread local. - * - * @throws ReflectiveOperationException reflective operation exception */ - public static void clear() throws ReflectiveOperationException { + @SneakyThrows + public static void clear() { Field field = ExecutorExceptionHandler.class.getDeclaredField("IS_EXCEPTION_THROWN"); field.setAccessible(true); ((ThreadLocal) field.get(ExecutorExceptionHandler.class)).remove(); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/executor/threadlocal/ExecutorExceptionHandlerTest.java b/sharding-core/src/test/java/io/shardingsphere/core/executor/threadlocal/ExecutorExceptionHandlerTest.java index 526266e95a21c..bd6b723217dde 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/executor/threadlocal/ExecutorExceptionHandlerTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/executor/threadlocal/ExecutorExceptionHandlerTest.java @@ -30,7 +30,7 @@ public class ExecutorExceptionHandlerTest { @After - public void tearDown() throws ReflectiveOperationException { + public void tearDown() { ExecutorTestUtil.clear(); } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/keygen/DefaultKeyGeneratorTest.java b/sharding-core/src/test/java/io/shardingsphere/core/keygen/DefaultKeyGeneratorTest.java index 6da506b191b1b..b52e679db9119 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/keygen/DefaultKeyGeneratorTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/keygen/DefaultKeyGeneratorTest.java @@ -18,6 +18,7 @@ package io.shardingsphere.core.keygen; import io.shardingsphere.core.keygen.fixture.FixedTimeService; +import lombok.SneakyThrows; import org.junit.Test; import java.lang.reflect.Field; @@ -80,7 +81,8 @@ public void assertSetWorkerIdFailureWhenTooMuch() { } @Test - public void assertSetWorkerIdSuccess() throws NoSuchFieldException, IllegalAccessException { + @SneakyThrows + public void assertSetWorkerIdSuccess() { DefaultKeyGenerator.setWorkerId(1L); Field workerIdField = DefaultKeyGenerator.class.getDeclaredField("workerId"); workerIdField.setAccessible(true); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/ParserResultSetLoader.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/ParserResultSetLoader.java index 42462ad90a5ac..fb7461b9f0ed9 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/ParserResultSetLoader.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/ParserResultSetLoader.java @@ -20,9 +20,9 @@ import com.google.common.base.Preconditions; import io.shardingsphere.core.parsing.integrate.jaxb.root.ParserResult; import io.shardingsphere.core.parsing.integrate.jaxb.root.ParserResultSet; +import lombok.SneakyThrows; import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; import java.io.File; import java.net.URL; import java.util.HashMap; @@ -64,14 +64,11 @@ private Map loadParserResultSet() { return result; } + @SneakyThrows private Map loadParserResultSet(final File file) { Map result = new HashMap<>(Short.MAX_VALUE, 1); - try { - for (ParserResult each : ((ParserResultSet) JAXBContext.newInstance(ParserResultSet.class).createUnmarshaller().unmarshal(file)).getParserResults()) { - result.put(each.getSqlCaseId(), each); - } - } catch (JAXBException ex) { - throw new RuntimeException(ex); + for (ParserResult each : ((ParserResultSet) JAXBContext.newInstance(ParserResultSet.class).createUnmarshaller().unmarshal(file)).getParserResults()) { + result.put(each.getSqlCaseId(), each); } return result; } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/condition/ConditionAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/condition/ConditionAssert.java index 9bbce4aeca7e6..51a2a09b75b85 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/condition/ConditionAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/condition/ConditionAssert.java @@ -26,6 +26,7 @@ import io.shardingsphere.core.parsing.parser.context.condition.Condition; import io.shardingsphere.core.parsing.parser.context.condition.OrCondition; import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; import java.lang.reflect.Field; import java.util.Map; @@ -85,13 +86,10 @@ private void assertCondition(final Condition actual, final ExpectedCondition exp } } + @SneakyThrows private Object getField(final Object actual, final String fieldName) { - try { - Field field = actual.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - return field.get(actual); - } catch (final ReflectiveOperationException ex) { - throw new RuntimeException(ex); - } + Field field = actual.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(actual); } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractShardingPreparedStatementAdapter.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractShardingPreparedStatementAdapter.java index 0be22f0bfd22a..e1452c5923bae 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractShardingPreparedStatementAdapter.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractShardingPreparedStatementAdapter.java @@ -17,10 +17,10 @@ package io.shardingsphere.shardingjdbc.jdbc.adapter; -import io.shardingsphere.core.exception.ShardingException; import io.shardingsphere.shardingjdbc.jdbc.adapter.invocation.SetParameterMethodInvocation; import io.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationPreparedStatement; import lombok.Getter; +import lombok.SneakyThrows; import java.io.InputStream; import java.io.Reader; @@ -257,14 +257,6 @@ private void setParameter(final int parameterIndex, final Object value) { parameters.set(parameterIndex - 1, value); } - private void recordSetParameter(final String methodName, final Class[] argumentTypes, final Object... arguments) { - try { - setParameterMethodInvocations.add(new SetParameterMethodInvocation(PreparedStatement.class.getMethod(methodName, argumentTypes), arguments, arguments[1])); - } catch (final NoSuchMethodException ex) { - throw new ShardingException(ex); - } - } - protected final void replaySetParameter(final PreparedStatement preparedStatement, final List parameters) { setParameterMethodInvocations.clear(); addParameters(parameters); @@ -275,10 +267,15 @@ protected final void replaySetParameter(final PreparedStatement preparedStatemen private void addParameters(final List parameters) { for (int i = 0; i < parameters.size(); i++) { - recordSetParameter("setObject", new Class[]{int.class, Object.class}, i + 1, parameters.get(i)); + setParameter(new Class[]{int.class, Object.class}, i + 1, parameters.get(i)); } } + @SneakyThrows + private void setParameter(final Class[] argumentTypes, final Object... arguments) { + setParameterMethodInvocations.add(new SetParameterMethodInvocation(PreparedStatement.class.getMethod("setObject", argumentTypes), arguments, arguments[1])); + } + @Override public final void clearParameters() { parameters.clear(); diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/WrapperAdapter.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/WrapperAdapter.java index 6346d18c42276..9cb7b0efd9735 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/WrapperAdapter.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/WrapperAdapter.java @@ -17,8 +17,8 @@ package io.shardingsphere.shardingjdbc.jdbc.adapter; -import io.shardingsphere.core.exception.ShardingException; import io.shardingsphere.shardingjdbc.jdbc.adapter.invocation.JdbcMethodInvocation; +import lombok.SneakyThrows; import java.sql.SQLException; import java.sql.Wrapper; @@ -56,12 +56,9 @@ public final boolean isWrapperFor(final Class iface) { * @param argumentTypes argument types * @param arguments arguments */ + @SneakyThrows public final void recordMethodInvocation(final Class targetClass, final String methodName, final Class[] argumentTypes, final Object[] arguments) { - try { - jdbcMethodInvocations.add(new JdbcMethodInvocation(targetClass.getMethod(methodName, argumentTypes), arguments)); - } catch (final NoSuchMethodException ex) { - throw new ShardingException(ex); - } + jdbcMethodInvocations.add(new JdbcMethodInvocation(targetClass.getMethod(methodName, argumentTypes), arguments)); } /** diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocation.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocation.java index 9ba0d242c0ed2..3fe68fea0f7ce 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocation.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocation.java @@ -17,11 +17,10 @@ package io.shardingsphere.shardingjdbc.jdbc.adapter.invocation; -import io.shardingsphere.core.exception.ShardingException; import lombok.Getter; import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** @@ -43,11 +42,8 @@ public class JdbcMethodInvocation { * * @param target target object */ + @SneakyThrows public void invoke(final Object target) { - try { - method.invoke(target, arguments); - } catch (final IllegalAccessException | InvocationTargetException ex) { - throw new ShardingException("Invoke jdbc method exception", ex); - } + method.invoke(target, arguments); } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/core/datasource/MasterSlaveDataSource.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/core/datasource/MasterSlaveDataSource.java index 2419e50092b5d..bfa1f1104ab69 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/core/datasource/MasterSlaveDataSource.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/core/datasource/MasterSlaveDataSource.java @@ -27,7 +27,6 @@ import lombok.Getter; import javax.sql.DataSource; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.Collection; @@ -101,7 +100,7 @@ private void closeOriginalDataSources() { try { Method closeMethod = each.getClass().getDeclaredMethod("close"); closeMethod.invoke(each); - } catch (final NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { + } catch (final ReflectiveOperationException ignored) { } } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/dbtest/cases/assertion/IntegrateTestCasesLoader.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/dbtest/cases/assertion/IntegrateTestCasesLoader.java index ac7c956383ea5..e3d474b7c9c00 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/dbtest/cases/assertion/IntegrateTestCasesLoader.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/dbtest/cases/assertion/IntegrateTestCasesLoader.java @@ -28,6 +28,7 @@ import io.shardingsphere.dbtest.cases.assertion.dql.DQLIntegrateTestCases; import io.shardingsphere.dbtest.cases.assertion.root.IntegrateTestCase; import io.shardingsphere.dbtest.cases.assertion.root.IntegrateTestCases; +import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import javax.xml.bind.JAXBContext; @@ -74,15 +75,12 @@ public final class IntegrateTestCasesLoader { private final Map dclIntegrateTestCaseMap; + @SneakyThrows private IntegrateTestCasesLoader() { - try { - dqlIntegrateTestCaseMap = loadIntegrateTestCases(DQL_INTEGRATE_TEST_CASES_FILE_PREFIX); - dmlIntegrateTestCaseMap = loadIntegrateTestCases(DML_INTEGRATE_TEST_CASES_FILE_PREFIX); - ddlIntegrateTestCaseMap = loadIntegrateTestCases(DDL_INTEGRATE_TEST_CASES_FILE_PREFIX); - dclIntegrateTestCaseMap = loadIntegrateTestCases(DCL_INTEGRATE_TEST_CASES_FILE_PREFIX); - } catch (final IOException | URISyntaxException | JAXBException ex) { - throw new RuntimeException(ex); - } + dqlIntegrateTestCaseMap = loadIntegrateTestCases(DQL_INTEGRATE_TEST_CASES_FILE_PREFIX); + dmlIntegrateTestCaseMap = loadIntegrateTestCases(DML_INTEGRATE_TEST_CASES_FILE_PREFIX); + ddlIntegrateTestCaseMap = loadIntegrateTestCases(DDL_INTEGRATE_TEST_CASES_FILE_PREFIX); + dclIntegrateTestCaseMap = loadIntegrateTestCases(DCL_INTEGRATE_TEST_CASES_FILE_PREFIX); } /** diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/api/ShardingDataSourceFactoryTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/api/ShardingDataSourceFactoryTest.java index 11877fbc7be6a..065451d9433d3 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/api/ShardingDataSourceFactoryTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/api/ShardingDataSourceFactoryTest.java @@ -22,6 +22,7 @@ import io.shardingsphere.api.config.TableRuleConfiguration; import io.shardingsphere.core.rule.ShardingRule; import io.shardingsphere.shardingjdbc.jdbc.core.ShardingContext; +import lombok.SneakyThrows; import org.junit.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; @@ -47,7 +48,7 @@ public final class ShardingDataSourceFactoryTest { @Test - public void assertCreateDataSourceWithShardingRuleAndConfigMapAndProperties() throws SQLException, NoSuchFieldException, IllegalAccessException { + public void assertCreateDataSourceWithShardingRuleAndConfigMapAndProperties() throws SQLException { ShardingRuleConfiguration shardingRuleConfig = createShardingRuleConfig(); Properties props = new Properties(); Map configMap = new ConcurrentHashMap<>(); @@ -72,8 +73,8 @@ private Map getDataSourceMap() throws SQLException { when(connection.createStatement()).thenReturn(statement); when(statement.executeQuery(Mockito.anyString())).thenReturn(resultSet); when(statement.getConnection()).thenReturn(connection); - when(statement.getConnection().getMetaData().getTables(ArgumentMatchers.any(), ArgumentMatchers.any(), - ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(resultSet); + when(statement.getConnection().getMetaData().getTables( + ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(resultSet); when(resultSet.next()).thenReturn(false); Map result = new HashMap<>(1); when(statement.getConnection().getMetaData().getURL()).thenReturn("jdbc:h2:mem:demo_ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL"); @@ -90,13 +91,15 @@ private ShardingRuleConfiguration createShardingRuleConfig() { return result; } - private ShardingRule getShardingRule(final DataSource dataSource) throws NoSuchFieldException, IllegalAccessException { + @SneakyThrows + private ShardingRule getShardingRule(final DataSource dataSource) { Field field = dataSource.getClass().getDeclaredField("shardingContext"); field.setAccessible(true); return ((ShardingContext) field.get(dataSource)).getShardingRule(); } - private Properties getShardingProperties(final DataSource dataSource) throws NoSuchFieldException, IllegalAccessException { + @SneakyThrows + private Properties getShardingProperties(final DataSource dataSource) { Field shardingPropertiesField = dataSource.getClass().getDeclaredField("shardingProperties"); shardingPropertiesField.setAccessible(true); Field propsField = shardingPropertiesField.get(dataSource).getClass().getDeclaredField("props"); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/AbstractBaseExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/AbstractBaseExecutorTest.java index 6c26a50c44758..4450f6ce0adb6 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/AbstractBaseExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/AbstractBaseExecutorTest.java @@ -58,7 +58,7 @@ public abstract class AbstractBaseExecutorTest { private TestDMLExecutionEventListener dmlExecutionEventListener; @Before - public void setUp() throws SQLException, ReflectiveOperationException { + public void setUp() throws SQLException { MockitoAnnotations.initMocks(this); ExecutorExceptionHandler.setExceptionThrown(false); executeEngine = new ShardingExecuteEngine(Runtime.getRuntime().availableProcessors()); @@ -87,7 +87,7 @@ private void setConnection() throws SQLException { } @After - public void tearDown() throws ReflectiveOperationException { + public void tearDown() { ExecutorTestUtil.clear(); ShardingEventBusInstance.getInstance().unregister(dqlExecutionEventListener); ShardingEventBusInstance.getInstance().unregister(dmlExecutionEventListener); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java index d1882b80fc7b4..d4661f6979318 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java @@ -25,6 +25,7 @@ import io.shardingsphere.core.routing.BatchRouteUnit; import io.shardingsphere.core.routing.RouteUnit; import io.shardingsphere.core.routing.SQLUnit; +import lombok.SneakyThrows; import org.junit.Test; import java.lang.reflect.Field; @@ -52,51 +53,14 @@ public final class BatchPreparedStatementExecutorTest extends AbstractBaseExecut private BatchPreparedStatementExecutor actual; @Override - public void setUp() throws SQLException, ReflectiveOperationException { + public void setUp() throws SQLException { super.setUp(); actual = new BatchPreparedStatementExecutor(1, 1, 1, false, getConnection()); } - private void setSQLType(final SQLType sqlType) throws ReflectiveOperationException { - Field field = BatchPreparedStatementExecutor.class.getSuperclass().getDeclaredField("sqlType"); - field.setAccessible(true); - field.set(actual, sqlType); - } - - private void setExecuteGroups(final List preparedStatements) throws ReflectiveOperationException { - Collection> executeGroups = new LinkedList<>(); - List preparedStatementExecuteUnits = new LinkedList<>(); - executeGroups.add(new ShardingExecuteGroup<>(preparedStatementExecuteUnits)); - Collection routeUnits = new LinkedList<>(); - for (PreparedStatement each : preparedStatements) { - List> parameterSets = new LinkedList<>(); - parameterSets.add(Collections.singletonList((Object) 1)); - RouteUnit routeUnit = new RouteUnit("ds_0", new SQLUnit(SQL, parameterSets)); - BatchRouteUnit batchRouteUnit = new BatchRouteUnit(routeUnit); - batchRouteUnit.mapAddBatchCount(0); - batchRouteUnit.mapAddBatchCount(1); - routeUnits.add(batchRouteUnit); - preparedStatementExecuteUnits.add(new StatementExecuteUnit(routeUnit, each, ConnectionMode.MEMORY_STRICTLY)); - } - setFields(executeGroups, routeUnits); - } - - private void setFields( - final Collection> executeGroups, final Collection routeUnits) throws NoSuchFieldException, IllegalAccessException { - Field field = BatchPreparedStatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); - field.setAccessible(true); - field.set(actual, executeGroups); - field = BatchPreparedStatementExecutor.class.getDeclaredField("routeUnits"); - field.setAccessible(true); - field.set(actual, routeUnits); - field = BatchPreparedStatementExecutor.class.getDeclaredField("batchCount"); - field.setAccessible(true); - field.set(actual, 2); - } - @SuppressWarnings("unchecked") @Test - public void assertNoPreparedStatement() throws SQLException, ReflectiveOperationException { + public void assertNoPreparedStatement() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.executeBatch()).thenReturn(new int[] {0, 0}); setSQLType(SQLType.DQL); @@ -105,7 +69,7 @@ public void assertNoPreparedStatement() throws SQLException, ReflectiveOperation } @Test - public void assertExecuteBatchForSinglePreparedStatementSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteBatchForSinglePreparedStatementSuccess() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.executeBatch()).thenReturn(new int[] {10, 20}); setSQLType(SQLType.DQL); @@ -131,7 +95,7 @@ private PreparedStatement getPreparedStatement() throws SQLException { } @Test - public void assertExecuteBatchForMultiplePreparedStatementsSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteBatchForMultiplePreparedStatementsSuccess() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.executeBatch()).thenReturn(new int[] {10, 20}); @@ -150,7 +114,7 @@ public void assertExecuteBatchForMultiplePreparedStatementsSuccess() throws SQLE } @Test - public void assertExecuteBatchForSinglePreparedStatementFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteBatchForSinglePreparedStatementFailure() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.executeBatch()).thenThrow(exp); @@ -166,7 +130,7 @@ public void assertExecuteBatchForSinglePreparedStatementFailure() throws SQLExce } @Test - public void assertExecuteBatchForMultiplePreparedStatementsFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteBatchForMultiplePreparedStatementsFailure() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); @@ -183,4 +147,43 @@ public void assertExecuteBatchForMultiplePreparedStatementsFailure() throws SQLE verify(getEventCaller(), times(2)).verifyEventExecutionType(ShardingEventType.BEFORE_EXECUTE); verify(getEventCaller(), times(2)).verifyException(exp); } + + @SneakyThrows + private void setSQLType(final SQLType sqlType) { + Field field = BatchPreparedStatementExecutor.class.getSuperclass().getDeclaredField("sqlType"); + field.setAccessible(true); + field.set(actual, sqlType); + } + + + private void setExecuteGroups(final List preparedStatements) { + Collection> executeGroups = new LinkedList<>(); + List preparedStatementExecuteUnits = new LinkedList<>(); + executeGroups.add(new ShardingExecuteGroup<>(preparedStatementExecuteUnits)); + Collection routeUnits = new LinkedList<>(); + for (PreparedStatement each : preparedStatements) { + List> parameterSets = new LinkedList<>(); + parameterSets.add(Collections.singletonList((Object) 1)); + RouteUnit routeUnit = new RouteUnit("ds_0", new SQLUnit(SQL, parameterSets)); + BatchRouteUnit batchRouteUnit = new BatchRouteUnit(routeUnit); + batchRouteUnit.mapAddBatchCount(0); + batchRouteUnit.mapAddBatchCount(1); + routeUnits.add(batchRouteUnit); + preparedStatementExecuteUnits.add(new StatementExecuteUnit(routeUnit, each, ConnectionMode.MEMORY_STRICTLY)); + } + setFields(executeGroups, routeUnits); + } + + @SneakyThrows + private void setFields(final Collection> executeGroups, final Collection routeUnits) { + Field field = BatchPreparedStatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); + field.setAccessible(true); + field.set(actual, executeGroups); + field = BatchPreparedStatementExecutor.class.getDeclaredField("routeUnits"); + field.setAccessible(true); + field.set(actual, routeUnits); + field = BatchPreparedStatementExecutor.class.getDeclaredField("batchCount"); + field.setAccessible(true); + field.set(actual, 2); + } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java index 27138db1efb3f..76661f4ff9918 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java @@ -25,6 +25,7 @@ import io.shardingsphere.core.merger.QueryResult; import io.shardingsphere.core.routing.RouteUnit; import io.shardingsphere.core.routing.SQLUnit; +import lombok.SneakyThrows; import org.junit.Test; import java.lang.reflect.Field; @@ -57,32 +58,11 @@ public final class PreparedStatementExecutorTest extends AbstractBaseExecutorTes private PreparedStatementExecutor actual; @Override - public void setUp() throws SQLException, ReflectiveOperationException { + public void setUp() throws SQLException { super.setUp(); actual = new PreparedStatementExecutor(1, 1, 1, false, getConnection()); } - private void setSQLType(final SQLType sqlType) throws ReflectiveOperationException { - Field field = PreparedStatementExecutor.class.getSuperclass().getDeclaredField("sqlType"); - field.setAccessible(true); - field.set(actual, sqlType); - } - - private void setExecuteGroups(final List preparedStatements, final SQLType sqlType) throws ReflectiveOperationException { - Collection> executeGroups = new LinkedList<>(); - List preparedStatementExecuteUnits = new LinkedList<>(); - executeGroups.add(new ShardingExecuteGroup<>(preparedStatementExecuteUnits)); - for (PreparedStatement each : preparedStatements) { - List> parameterSets = new LinkedList<>(); - String sql = SQLType.DQL.equals(sqlType) ? DQL_SQL : DML_SQL; - parameterSets.add(Collections.singletonList((Object) 1)); - preparedStatementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, parameterSets)), each, ConnectionMode.MEMORY_STRICTLY)); - } - Field field = PreparedStatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); - field.setAccessible(true); - field.set(actual, executeGroups); - } - @Test public void assertNoStatement() throws SQLException { assertFalse(actual.execute()); @@ -91,7 +71,7 @@ public void assertNoStatement() throws SQLException { } @Test - public void assertExecuteQueryForSinglePreparedStatementSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteQueryForSinglePreparedStatementSuccess() throws SQLException{ PreparedStatement preparedStatement = getPreparedStatement(); ResultSet resultSet = mock(ResultSet.class); when(resultSet.getInt(1)).thenReturn(1); @@ -119,7 +99,7 @@ private PreparedStatement getPreparedStatement() throws SQLException { } @Test - public void assertExecuteQueryForMultiplePreparedStatementsSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteQueryForMultiplePreparedStatementsSuccess() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); ResultSet resultSet1 = mock(ResultSet.class); @@ -146,7 +126,7 @@ public void assertExecuteQueryForMultiplePreparedStatementsSuccess() throws SQLE } @Test - public void assertExecuteQueryForSinglePreparedStatementFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteQueryForSinglePreparedStatementFailure() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.executeQuery()).thenThrow(exp); @@ -163,7 +143,7 @@ public void assertExecuteQueryForSinglePreparedStatementFailure() throws SQLExce } @Test - public void assertExecuteQueryForMultiplePreparedStatementsFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteQueryForMultiplePreparedStatementsFailure() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); @@ -184,7 +164,7 @@ public void assertExecuteQueryForMultiplePreparedStatementsFailure() throws SQLE } @Test - public void assertExecuteUpdateForSinglePreparedStatementSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateForSinglePreparedStatementSuccess() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.executeUpdate()).thenReturn(10); setSQLType(SQLType.DML); @@ -200,7 +180,7 @@ public void assertExecuteUpdateForSinglePreparedStatementSuccess() throws SQLExc } @Test - public void assertExecuteUpdateForMultiplePreparedStatementsSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateForMultiplePreparedStatementsSuccess() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.executeUpdate()).thenReturn(10); @@ -219,7 +199,7 @@ public void assertExecuteUpdateForMultiplePreparedStatementsSuccess() throws SQL } @Test - public void assertExecuteUpdateForSinglePreparedStatementFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateForSinglePreparedStatementFailure() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.executeUpdate()).thenThrow(exp); @@ -236,7 +216,7 @@ public void assertExecuteUpdateForSinglePreparedStatementFailure() throws SQLExc } @Test - public void assertExecuteUpdateForMultiplePreparedStatementsFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateForMultiplePreparedStatementsFailure() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); @@ -256,7 +236,7 @@ public void assertExecuteUpdateForMultiplePreparedStatementsFailure() throws SQL } @Test - public void assertExecuteForSinglePreparedStatementSuccessWithDML() throws SQLException, ReflectiveOperationException { + public void assertExecuteForSinglePreparedStatementSuccessWithDML() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.execute()).thenReturn(false); setSQLType(SQLType.DML); @@ -272,7 +252,7 @@ public void assertExecuteForSinglePreparedStatementSuccessWithDML() throws SQLEx } @Test - public void assertExecuteForMultiplePreparedStatementsSuccessWithDML() throws SQLException, ReflectiveOperationException { + public void assertExecuteForMultiplePreparedStatementsSuccessWithDML() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.execute()).thenReturn(false); @@ -291,7 +271,7 @@ public void assertExecuteForMultiplePreparedStatementsSuccessWithDML() throws SQ } @Test - public void assertExecuteForSinglePreparedStatementFailureWithDML() throws SQLException, ReflectiveOperationException { + public void assertExecuteForSinglePreparedStatementFailureWithDML() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); SQLException exp = new SQLException(); when(preparedStatement.execute()).thenThrow(exp); @@ -308,7 +288,7 @@ public void assertExecuteForSinglePreparedStatementFailureWithDML() throws SQLEx } @Test - public void assertExecuteForMultiplePreparedStatementsFailureWithDML() throws SQLException, ReflectiveOperationException { + public void assertExecuteForMultiplePreparedStatementsFailureWithDML() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); SQLException exp = new SQLException(); @@ -328,7 +308,7 @@ public void assertExecuteForMultiplePreparedStatementsFailureWithDML() throws SQ } @Test - public void assertExecuteForSinglePreparedStatementWithDQL() throws SQLException, ReflectiveOperationException { + public void assertExecuteForSinglePreparedStatementWithDQL() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); when(preparedStatement.execute()).thenReturn(true); setSQLType(SQLType.DQL); @@ -344,7 +324,7 @@ public void assertExecuteForSinglePreparedStatementWithDQL() throws SQLException } @Test - public void assertExecuteForMultiplePreparedStatements() throws SQLException, ReflectiveOperationException { + public void assertExecuteForMultiplePreparedStatements() throws SQLException { PreparedStatement preparedStatement1 = getPreparedStatement(); PreparedStatement preparedStatement2 = getPreparedStatement(); when(preparedStatement1.execute()).thenReturn(true); @@ -361,4 +341,27 @@ public void assertExecuteForMultiplePreparedStatements() throws SQLException, Re verify(getEventCaller(), times(2)).verifyEventExecutionType(ShardingEventType.EXECUTE_SUCCESS); verify(getEventCaller(), times(0)).verifyException(null); } + + @SneakyThrows + private void setSQLType(final SQLType sqlType) { + Field field = PreparedStatementExecutor.class.getSuperclass().getDeclaredField("sqlType"); + field.setAccessible(true); + field.set(actual, sqlType); + } + + @SneakyThrows + private void setExecuteGroups(final List preparedStatements, final SQLType sqlType) { + Collection> executeGroups = new LinkedList<>(); + List preparedStatementExecuteUnits = new LinkedList<>(); + executeGroups.add(new ShardingExecuteGroup<>(preparedStatementExecuteUnits)); + for (PreparedStatement each : preparedStatements) { + List> parameterSets = new LinkedList<>(); + String sql = SQLType.DQL.equals(sqlType) ? DQL_SQL : DML_SQL; + parameterSets.add(Collections.singletonList((Object) 1)); + preparedStatementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, parameterSets)), each, ConnectionMode.MEMORY_STRICTLY)); + } + Field field = PreparedStatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); + field.setAccessible(true); + field.set(actual, executeGroups); + } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java index c9edb54e0e0f7..1ee93d4375d93 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java @@ -26,6 +26,7 @@ import io.shardingsphere.core.merger.QueryResult; import io.shardingsphere.core.routing.RouteUnit; import io.shardingsphere.core.routing.SQLUnit; +import lombok.SneakyThrows; import org.junit.Test; import java.lang.reflect.Field; @@ -58,7 +59,7 @@ public final class StatementExecutorTest extends AbstractBaseExecutorTest { private StatementExecutor actual; @Override - public void setUp() throws SQLException, ReflectiveOperationException { + public void setUp() throws SQLException { super.setUp(); actual = new StatementExecutor(1, 1, 1, getConnection()); } @@ -71,7 +72,7 @@ public void assertNoStatement() throws SQLException { } @Test - public void assertExecuteQueryForSingleStatementSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteQueryForSingleStatementSuccess() throws SQLException { Statement statement = getStatement(); ResultSet resultSet = mock(ResultSet.class); when(resultSet.getInt(1)).thenReturn(1); @@ -83,29 +84,8 @@ public void assertExecuteQueryForSingleStatementSuccess() throws SQLException, R verify(getEventCaller(), times(2)).verifyDataSource("ds_0"); } - private void setSQLType(final SQLType sqlType) throws ReflectiveOperationException { - Field field = StatementExecutor.class.getSuperclass().getDeclaredField("sqlType"); - field.setAccessible(true); - field.set(actual, sqlType); - } - - private void setExecuteGroups(final List statements, final SQLType sqlType) throws ReflectiveOperationException { - Collection> executeGroups = new LinkedList<>(); - List statementExecuteUnits = new LinkedList<>(); - executeGroups.add(new ShardingExecuteGroup<>(statementExecuteUnits)); - for (Statement each : statements) { - List> parameterSets = new LinkedList<>(); - String sql = SQLType.DQL.equals(sqlType) ? DQL_SQL : DML_SQL; - parameterSets.add(Collections.singletonList((Object) 1)); - statementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, parameterSets)), each, ConnectionMode.MEMORY_STRICTLY)); - } - Field field = StatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); - field.setAccessible(true); - field.set(actual, executeGroups); - } - @Test - public void assertExecuteQueryForMultipleStatementsSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteQueryForMultipleStatementsSuccess() throws SQLException { Statement statement1 = getStatement(); Statement statement2 = getStatement(); ResultSet resultSet1 = mock(ResultSet.class); @@ -128,7 +108,7 @@ public void assertExecuteQueryForMultipleStatementsSuccess() throws SQLException } @Test - public void assertExecuteQueryForSingleStatementFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteQueryForSingleStatementFailure() throws SQLException { Statement statement = getStatement(); SQLException exp = new SQLException(); when(statement.executeQuery(DQL_SQL)).thenThrow(exp); @@ -141,7 +121,7 @@ public void assertExecuteQueryForSingleStatementFailure() throws SQLException, R } @Test - public void assertExecuteQueryForMultipleStatementsFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteQueryForMultipleStatementsFailure() throws SQLException { Statement statement1 = getStatement(); Statement statement2 = getStatement(); SQLException exp = new SQLException(); @@ -162,7 +142,7 @@ public void assertExecuteQueryForMultipleStatementsFailure() throws SQLException } @Test - public void assertExecuteUpdateForSingleStatementSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateForSingleStatementSuccess() throws SQLException { Statement statement = getStatement(); when(statement.executeUpdate(DML_SQL)).thenReturn(10); setSQLType(SQLType.DML); @@ -178,7 +158,7 @@ public void assertExecuteUpdateForSingleStatementSuccess() throws SQLException, } @Test - public void assertExecuteUpdateForMultipleStatementsSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateForMultipleStatementsSuccess() throws SQLException { Statement statement1 = getStatement(); Statement statement2 = getStatement(); when(statement1.executeUpdate(DML_SQL)).thenReturn(10); @@ -197,7 +177,7 @@ public void assertExecuteUpdateForMultipleStatementsSuccess() throws SQLExceptio } @Test - public void assertExecuteUpdateForSingleStatementFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateForSingleStatementFailure() throws SQLException { Statement statement = getStatement(); SQLException exp = new SQLException(); when(statement.executeUpdate(DML_SQL)).thenThrow(exp); @@ -214,7 +194,7 @@ public void assertExecuteUpdateForSingleStatementFailure() throws SQLException, } @Test - public void assertExecuteUpdateForMultipleStatementsFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateForMultipleStatementsFailure() throws SQLException { Statement statement1 = getStatement(); Statement statement2 = getStatement(); SQLException exp = new SQLException(); @@ -234,7 +214,7 @@ public void assertExecuteUpdateForMultipleStatementsFailure() throws SQLExceptio } @Test - public void assertExecuteUpdateWithAutoGeneratedKeys() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateWithAutoGeneratedKeys() throws SQLException { Statement statement = getStatement(); when(statement.executeUpdate(DML_SQL, Statement.NO_GENERATED_KEYS)).thenReturn(10); setSQLType(SQLType.DML); @@ -250,7 +230,7 @@ public void assertExecuteUpdateWithAutoGeneratedKeys() throws SQLException, Refl } @Test - public void assertExecuteUpdateWithColumnIndexes() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateWithColumnIndexes() throws SQLException { Statement statement = getStatement(); when(statement.executeUpdate(DML_SQL, new int[] {1})).thenReturn(10); setSQLType(SQLType.DML); @@ -276,7 +256,7 @@ private Statement getStatement() throws SQLException { } @Test - public void assertExecuteUpdateWithColumnNames() throws SQLException, ReflectiveOperationException { + public void assertExecuteUpdateWithColumnNames() throws SQLException { Statement statement = getStatement(); when(statement.executeUpdate(DML_SQL, new String[] {"col"})).thenReturn(10); setSQLType(SQLType.DML); @@ -292,7 +272,7 @@ public void assertExecuteUpdateWithColumnNames() throws SQLException, Reflective } @Test - public void assertExecuteForSingleStatementSuccessWithDML() throws SQLException, ReflectiveOperationException { + public void assertExecuteForSingleStatementSuccessWithDML() throws SQLException { Statement statement = getStatement(); when(statement.execute(DML_SQL)).thenReturn(false); setSQLType(SQLType.DML); @@ -308,7 +288,7 @@ public void assertExecuteForSingleStatementSuccessWithDML() throws SQLException, } @Test - public void assertExecuteForMultipleStatementsSuccessWithDML() throws SQLException, ReflectiveOperationException { + public void assertExecuteForMultipleStatementsSuccessWithDML() throws SQLException { Statement statement1 = getStatement(); Statement statement2 = getStatement(); when(statement1.execute(DML_SQL)).thenReturn(false); @@ -327,7 +307,7 @@ public void assertExecuteForMultipleStatementsSuccessWithDML() throws SQLExcepti } @Test - public void assertExecuteForSingleStatementFailureWithDML() throws SQLException, ReflectiveOperationException { + public void assertExecuteForSingleStatementFailureWithDML() throws SQLException { Statement statement = getStatement(); SQLException exp = new SQLException(); when(statement.execute(DML_SQL)).thenThrow(exp); @@ -344,7 +324,7 @@ public void assertExecuteForSingleStatementFailureWithDML() throws SQLException, } @Test - public void assertExecuteForMultipleStatementsFailureWithDML() throws SQLException, ReflectiveOperationException { + public void assertExecuteForMultipleStatementsFailureWithDML() throws SQLException { Statement statement1 = getStatement(); Statement statement2 = getStatement(); SQLException exp = new SQLException(); @@ -364,7 +344,7 @@ public void assertExecuteForMultipleStatementsFailureWithDML() throws SQLExcepti } @Test - public void assertExecuteForSingleStatementWithDQL() throws SQLException, ReflectiveOperationException { + public void assertExecuteForSingleStatementWithDQL() throws SQLException { Statement statement = getStatement(); when(statement.execute(DQL_SQL)).thenReturn(true); setSQLType(SQLType.DQL); @@ -380,7 +360,7 @@ public void assertExecuteForSingleStatementWithDQL() throws SQLException, Reflec } @Test - public void assertExecuteForMultipleStatements() throws SQLException, ReflectiveOperationException { + public void assertExecuteForMultipleStatements() throws SQLException { Statement statement1 = getStatement(); Statement statement2 = getStatement(); when(statement1.execute(DQL_SQL)).thenReturn(true); @@ -399,7 +379,7 @@ public void assertExecuteForMultipleStatements() throws SQLException, Reflective } @Test - public void assertExecuteWithAutoGeneratedKeys() throws SQLException, ReflectiveOperationException { + public void assertExecuteWithAutoGeneratedKeys() throws SQLException { Statement statement = getStatement(); when(statement.execute(DML_SQL, Statement.NO_GENERATED_KEYS)).thenReturn(false); setSQLType(SQLType.DML); @@ -416,7 +396,7 @@ public void assertExecuteWithAutoGeneratedKeys() throws SQLException, Reflective } @Test - public void assertExecuteWithColumnIndexes() throws SQLException, ReflectiveOperationException { + public void assertExecuteWithColumnIndexes() throws SQLException { Statement statement = getStatement(); when(statement.execute(DML_SQL, new int[] {1})).thenReturn(false); setSQLType(SQLType.DML); @@ -432,7 +412,7 @@ public void assertExecuteWithColumnIndexes() throws SQLException, ReflectiveOper } @Test - public void assertExecuteWithColumnNames() throws SQLException, ReflectiveOperationException { + public void assertExecuteWithColumnNames() throws SQLException { Statement statement = getStatement(); when(statement.execute(DML_SQL, new String[] {"col"})).thenReturn(false); setSQLType(SQLType.DML); @@ -448,7 +428,7 @@ public void assertExecuteWithColumnNames() throws SQLException, ReflectiveOperat } @Test - public void assertOverallExceptionFailure() throws SQLException, ReflectiveOperationException { + public void assertOverallExceptionFailure() throws SQLException { ExecutorExceptionHandler.setExceptionThrown(true); Statement statement = getStatement(); SQLException exp = new SQLException(); @@ -462,4 +442,27 @@ public void assertOverallExceptionFailure() throws SQLException, ReflectiveOpera verify(getEventCaller()).verifyEventExecutionType(ShardingEventType.BEFORE_EXECUTE); verify(getEventCaller()).verifyEventExecutionType(ShardingEventType.EXECUTE_FAILURE); } + + @SneakyThrows + private void setExecuteGroups(final List statements, final SQLType sqlType) { + Collection> executeGroups = new LinkedList<>(); + List statementExecuteUnits = new LinkedList<>(); + executeGroups.add(new ShardingExecuteGroup<>(statementExecuteUnits)); + for (Statement each : statements) { + List> parameterSets = new LinkedList<>(); + String sql = SQLType.DQL.equals(sqlType) ? DQL_SQL : DML_SQL; + parameterSets.add(Collections.singletonList((Object) 1)); + statementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, parameterSets)), each, ConnectionMode.MEMORY_STRICTLY)); + } + Field field = StatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); + field.setAccessible(true); + field.set(actual, executeGroups); + } + + @SneakyThrows + private void setSQLType(final SQLType sqlType) { + Field field = StatementExecutor.class.getSuperclass().getDeclaredField("sqlType"); + field.setAccessible(true); + field.set(actual, sqlType); + } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/fixture/ExecutorTestUtil.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/fixture/ExecutorTestUtil.java index e25a0c949bdb1..b355433955ab7 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/fixture/ExecutorTestUtil.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/fixture/ExecutorTestUtil.java @@ -22,6 +22,7 @@ import io.shardingsphere.core.executor.sql.execute.threadlocal.ExecutorExceptionHandler; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import lombok.SneakyThrows; import java.lang.reflect.Field; @@ -46,10 +47,9 @@ public static void listen(final EventCaller eventCaller, final SQLExecutionEvent /** * Clear thread local. - * - * @throws ReflectiveOperationException reflective operation exception */ - public static void clear() throws ReflectiveOperationException { + @SneakyThrows + public static void clear() { Field field = ExecutorExceptionHandler.class.getDeclaredField("IS_EXCEPTION_THROWN"); field.setAccessible(true); ((ThreadLocal) field.get(ExecutorExceptionHandler.class)).remove(); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/ConnectionAdapterTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/ConnectionAdapterTest.java index b3998429bae60..a730b7141e276 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/ConnectionAdapterTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/ConnectionAdapterTest.java @@ -21,6 +21,7 @@ import io.shardingsphere.shardingjdbc.common.base.AbstractShardingJDBCDatabaseAndTableTest; import io.shardingsphere.shardingjdbc.jdbc.core.connection.ShardingConnection; import io.shardingsphere.shardingjdbc.jdbc.util.JDBCTestSQL; +import lombok.SneakyThrows; import org.junit.Test; import java.lang.reflect.Field; @@ -175,13 +176,10 @@ public void assertSetHoldability() throws SQLException { } @SuppressWarnings("unchecked") + @SneakyThrows private Multimap getCachedConnections(final AbstractConnectionAdapter connectionAdapter) { - try { - Field field = AbstractConnectionAdapter.class.getDeclaredField("cachedConnections"); - field.setAccessible(true); - return (Multimap) field.get(connectionAdapter); - } catch (final ReflectiveOperationException ex) { - throw new RuntimeException(ex); - } + Field field = AbstractConnectionAdapter.class.getDeclaredField("cachedConnections"); + field.setAccessible(true); + return (Multimap) field.get(connectionAdapter); } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/DataSourceAdapterTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/DataSourceAdapterTest.java index 6850daadf08a3..ee26b61e516b6 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/DataSourceAdapterTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/DataSourceAdapterTest.java @@ -17,7 +17,6 @@ package io.shardingsphere.shardingjdbc.jdbc.adapter; -import io.shardingsphere.core.exception.ShardingException; import io.shardingsphere.shardingjdbc.common.base.AbstractShardingJDBCDatabaseAndTableTest; import io.shardingsphere.shardingjdbc.jdbc.core.connection.ShardingConnection; import org.junit.Test; @@ -66,7 +65,7 @@ public void assertRecordMethodInvocationSuccess() { getShardingDataSource().replayMethodsInvocation(list); } - @Test(expected = ShardingException.class) + @Test(expected = NoSuchMethodException.class) public void assertRecordMethodInvocationFailure() { getShardingDataSource().recordMethodInvocation(String.class, "none", new Class[]{}, new Object[]{}); } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocationTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocationTest.java index 1fbc923a8816c..86fa0766b8c42 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocationTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/JdbcMethodInvocationTest.java @@ -17,19 +17,21 @@ package io.shardingsphere.shardingjdbc.jdbc.adapter.invocation; -import io.shardingsphere.core.exception.ShardingException; +import lombok.SneakyThrows; import org.junit.Test; public final class JdbcMethodInvocationTest { @Test - public void assertInvokeSuccess() throws NoSuchMethodException, SecurityException { + @SneakyThrows + public void assertInvokeSuccess() { JdbcMethodInvocation actual = new JdbcMethodInvocation(String.class.getMethod("length"), new Object[] {}); actual.invoke(""); } - @Test(expected = ShardingException.class) - public void assertInvokeFailure() throws NoSuchMethodException, SecurityException { + @Test(expected = IllegalAccessException.class) + @SneakyThrows + public void assertInvokeFailure() { JdbcMethodInvocation actual = new JdbcMethodInvocation(String.class.getDeclaredMethod("indexOfSupplementary", int.class, int.class), new Object[] {1, 1}); actual.invoke(""); } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/SetParameterMethodInvocationTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/SetParameterMethodInvocationTest.java index 92376142b8183..475b96be72adf 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/SetParameterMethodInvocationTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/jdbc/adapter/invocation/SetParameterMethodInvocationTest.java @@ -17,6 +17,7 @@ package io.shardingsphere.shardingjdbc.jdbc.adapter.invocation; +import lombok.SneakyThrows; import org.junit.Test; import java.sql.PreparedStatement; @@ -27,13 +28,15 @@ public final class SetParameterMethodInvocationTest { @Test - public void assertGetValue() throws NoSuchMethodException, SecurityException { + @SneakyThrows + public void assertGetValue() { SetParameterMethodInvocation actual = new SetParameterMethodInvocation(PreparedStatement.class.getMethod("setInt", int.class, int.class), new Object[] {1, 100}, 100); assertThat(actual.getValue(), is((Object) 100)); } @Test - public void assertChangeValueArgument() throws NoSuchMethodException, SecurityException { + @SneakyThrows + public void assertChangeValueArgument() { SetParameterMethodInvocation actual = new SetParameterMethodInvocation(PreparedStatement.class.getMethod("setInt", int.class, int.class), new Object[] {1, 100}, 100); actual.changeValueArgument(200); assertThat(actual.getArguments()[1], is((Object) 200)); diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java index 6b07dd1fa5ea7..45e87f2d2ceac 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java @@ -17,15 +17,14 @@ package io.shardingsphere.shardingjdbc.orchestration.spring.boot.util; -import io.shardingsphere.core.exception.ShardingException; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import lombok.SneakyThrows; import org.springframework.beans.factory.config.PlaceholderConfigurerSupport; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; @@ -40,7 +39,7 @@ public final class PropertyUtil { static { try { Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver"); - } catch (ClassNotFoundException e) { + } catch (ClassNotFoundException ignored) { springBootVersion = 2; } } @@ -64,47 +63,39 @@ public static T handle(final Environment environment, final String prefix, f } @SuppressWarnings("unchecked") + @SneakyThrows private static Object v1(final Environment environment, final String prefix) { - try { - Class resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver"); - Constructor resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class); - Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class); - Object resolverObject = resolverConstructor.newInstance(environment); - String prefixParam = prefix.endsWith(".") ? prefix : prefix + "."; - Method getPropertyMethod = resolverClass.getDeclaredMethod("getProperty", String.class); - Map dataSourceProps = (Map) getSubPropertiesMethod.invoke(resolverObject, prefixParam); - Map propertiesWithPlaceholderResolved = new HashMap<>(); - for (Entry entry : dataSourceProps.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (value instanceof String && ((String) value).contains( - PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX)) { - String resolvedValue = (String) getPropertyMethod.invoke(resolverObject, prefixParam + key); - propertiesWithPlaceholderResolved.put(key, resolvedValue); - } else { - propertiesWithPlaceholderResolved.put(key, value); - } + Class resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver"); + Constructor resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class); + Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class); + Object resolverObject = resolverConstructor.newInstance(environment); + String prefixParam = prefix.endsWith(".") ? prefix : prefix + "."; + Method getPropertyMethod = resolverClass.getDeclaredMethod("getProperty", String.class); + Map dataSourceProps = (Map) getSubPropertiesMethod.invoke(resolverObject, prefixParam); + Map propertiesWithPlaceholderResolved = new HashMap<>(); + for (Entry entry : dataSourceProps.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof String && ((String) value).contains( + PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX)) { + String resolvedValue = (String) getPropertyMethod.invoke(resolverObject, prefixParam + key); + propertiesWithPlaceholderResolved.put(key, resolvedValue); + } else { + propertiesWithPlaceholderResolved.put(key, value); } - return Collections.unmodifiableMap(propertiesWithPlaceholderResolved); - } catch (final ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException - | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { - throw new ShardingException(ex.getMessage(), ex); } + return Collections.unmodifiableMap(propertiesWithPlaceholderResolved); } + @SneakyThrows private static Object v2(final Environment environment, final String prefix, final Class targetClass) { - try { - Class binderClass = Class.forName("org.springframework.boot.context.properties.bind.Binder"); - Method getMethod = binderClass.getDeclaredMethod("get", Environment.class); - Method bindMethod = binderClass.getDeclaredMethod("bind", String.class, Class.class); - Object binderObject = getMethod.invoke(null, environment); - String prefixParam = prefix.endsWith(".") ? prefix.substring(0, prefix.length() - 1) : prefix; - Object bindResultObject = bindMethod.invoke(binderObject, prefixParam, targetClass); - Method resultGetMethod = bindResultObject.getClass().getDeclaredMethod("get"); - return resultGetMethod.invoke(bindResultObject); - } catch (final ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException ex) { - throw new ShardingException(ex.getMessage(), ex); - } + Class binderClass = Class.forName("org.springframework.boot.context.properties.bind.Binder"); + Method getMethod = binderClass.getDeclaredMethod("get", Environment.class); + Method bindMethod = binderClass.getDeclaredMethod("bind", String.class, Class.class); + Object binderObject = getMethod.invoke(null, environment); + String prefixParam = prefix.endsWith(".") ? prefix.substring(0, prefix.length() - 1) : prefix; + Object bindResultObject = bindMethod.invoke(binderObject, prefixParam, targetClass); + Method resultGetMethod = bindResultObject.getClass().getDeclaredMethod("get"); + return resultGetMethod.invoke(bindResultObject); } } diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/OrchestrationSpringBootMasterSlaveTest.java b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/OrchestrationSpringBootMasterSlaveTest.java index 7bff8691bdc33..2ea9fd6b6fbbf 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/OrchestrationSpringBootMasterSlaveTest.java +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/OrchestrationSpringBootMasterSlaveTest.java @@ -21,6 +21,7 @@ import io.shardingsphere.shardingjdbc.jdbc.core.datasource.MasterSlaveDataSource; import io.shardingsphere.shardingjdbc.orchestration.internal.datasource.OrchestrationMasterSlaveDataSource; import io.shardingsphere.shardingjdbc.spring.boot.util.EmbedTestingServer; +import lombok.SneakyThrows; import org.apache.commons.dbcp2.BasicDataSource; import org.junit.BeforeClass; import org.junit.Test; @@ -55,7 +56,8 @@ public static void init() { } @Test - public void assertWithMasterSlaveDataSource() throws ReflectiveOperationException { + @SneakyThrows + public void assertWithMasterSlaveDataSource() { assertTrue(dataSource instanceof OrchestrationMasterSlaveDataSource); Field field = OrchestrationMasterSlaveDataSource.class.getDeclaredField("dataSource"); field.setAccessible(true); diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/OrchestrationSpringBootShardingTest.java b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/OrchestrationSpringBootShardingTest.java index 45105d88ef7cc..c0da8db3fb0e8 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/OrchestrationSpringBootShardingTest.java +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/OrchestrationSpringBootShardingTest.java @@ -24,6 +24,7 @@ import io.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource; import io.shardingsphere.shardingjdbc.orchestration.internal.datasource.OrchestrationShardingDataSource; import io.shardingsphere.shardingjdbc.spring.boot.util.EmbedTestingServer; +import lombok.SneakyThrows; import org.apache.commons.dbcp2.BasicDataSource; import org.junit.BeforeClass; import org.junit.Test; @@ -58,14 +59,10 @@ public static void init() { } @Test - public void assertWithShardingDataSource() throws NoSuchFieldException, IllegalAccessException { + public void assertWithShardingDataSource() { assertTrue(dataSource instanceof OrchestrationShardingDataSource); - Field dataSourceField = OrchestrationShardingDataSource.class.getDeclaredField("dataSource"); - dataSourceField.setAccessible(true); - ShardingDataSource shardingDataSource = (ShardingDataSource) dataSourceField.get(dataSource); - Field field = ShardingDataSource.class.getDeclaredField("shardingContext"); - field.setAccessible(true); - ShardingContext shardingContext = (ShardingContext) field.get(shardingDataSource); + ShardingDataSource shardingDataSource = getFieldValue("dataSource", OrchestrationShardingDataSource.class, dataSource); + ShardingContext shardingContext = getFieldValue("shardingContext", ShardingDataSource.class, shardingDataSource); for (DataSource each : shardingDataSource.getDataSourceMap().values()) { assertThat(((BasicDataSource) each).getMaxTotal(), is(16)); } @@ -73,11 +70,16 @@ public void assertWithShardingDataSource() throws NoSuchFieldException, IllegalA Map configMap = new ConcurrentHashMap<>(); configMap.put("key1", "value1"); assertThat(ConfigMapContext.getInstance().getShardingConfig(), is(configMap)); - - Field propertiesField = ShardingDataSource.class.getDeclaredField("shardingProperties"); - propertiesField.setAccessible(true); - ShardingProperties shardingProperties = (ShardingProperties) propertiesField.get(shardingDataSource); + ShardingProperties shardingProperties = getFieldValue("shardingProperties", ShardingDataSource.class, shardingDataSource); assertTrue((Boolean) shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW)); assertThat((Integer) shardingProperties.getValue(ShardingPropertiesConstant.EXECUTOR_SIZE), is(100)); } + + @SuppressWarnings("unchecked") + @SneakyThrows + private T getFieldValue(final String fieldName, final Class fieldClass, final Object target) { + Field field = fieldClass.getDeclaredField(fieldName); + field.setAccessible(true); + return (T) field.get(target); + } } diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/orchestration/spring/util/FieldValueUtil.java b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/orchestration/spring/util/FieldValueUtil.java index 1dba45c31a8f0..7a03788de486e 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/orchestration/spring/util/FieldValueUtil.java +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/orchestration/spring/util/FieldValueUtil.java @@ -20,6 +20,7 @@ import com.google.common.base.Strings; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import lombok.SneakyThrows; import java.lang.reflect.Field; @@ -42,17 +43,11 @@ public static Object getFieldValue(final Object obj, final String fieldName, fin return getFieldValue(clazz, obj, fieldName); } + @SneakyThrows private static Object getFieldValue(final Class clazz, final Object obj, final String fieldName) { - try { - Field field = clazz.getDeclaredField(fieldName); - if (!field.isAccessible()) { - field.setAccessible(true); - } - return field.get(obj); - } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - return null; - } + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(obj); } /** diff --git a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java index 8f36ce82ff04a..dd461ab50acdf 100644 --- a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java +++ b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java @@ -17,15 +17,14 @@ package io.shardingsphere.shardingjdbc.spring.boot.util; -import io.shardingsphere.core.exception.ShardingException; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import lombok.SneakyThrows; import org.springframework.beans.factory.config.PlaceholderConfigurerSupport; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; @@ -40,7 +39,7 @@ public final class PropertyUtil { static { try { Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver"); - } catch (ClassNotFoundException e) { + } catch (ClassNotFoundException ignored) { springBootVersion = 2; } } @@ -64,47 +63,39 @@ public static T handle(final Environment environment, final String prefix, f } @SuppressWarnings("unchecked") + @SneakyThrows private static Object v1(final Environment environment, final String prefix) { - try { - Class resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver"); - Constructor resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class); - Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class); - Object resolverObject = resolverConstructor.newInstance(environment); - String prefixParam = prefix.endsWith(".") ? prefix : prefix + "."; - Method getPropertyMethod = resolverClass.getDeclaredMethod("getProperty", String.class); - Map dataSourceProps = (Map) getSubPropertiesMethod.invoke(resolverObject, prefixParam); - Map propertiesWithPlaceholderResolved = new HashMap<>(); - for (Entry entry : dataSourceProps.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (value instanceof String && ((String) value).contains( - PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX)) { - String resolvedValue = (String) getPropertyMethod.invoke(resolverObject, prefixParam + key); - propertiesWithPlaceholderResolved.put(key, resolvedValue); - } else { - propertiesWithPlaceholderResolved.put(key, value); - } + Class resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver"); + Constructor resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class); + Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class); + Object resolverObject = resolverConstructor.newInstance(environment); + String prefixParam = prefix.endsWith(".") ? prefix : prefix + "."; + Method getPropertyMethod = resolverClass.getDeclaredMethod("getProperty", String.class); + Map dataSourceProps = (Map) getSubPropertiesMethod.invoke(resolverObject, prefixParam); + Map propertiesWithPlaceholderResolved = new HashMap<>(); + for (Entry entry : dataSourceProps.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof String && ((String) value).contains( + PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX)) { + String resolvedValue = (String) getPropertyMethod.invoke(resolverObject, prefixParam + key); + propertiesWithPlaceholderResolved.put(key, resolvedValue); + } else { + propertiesWithPlaceholderResolved.put(key, value); } - return Collections.unmodifiableMap(propertiesWithPlaceholderResolved); - } catch (final ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException - | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { - throw new ShardingException(ex.getMessage(), ex); } + return Collections.unmodifiableMap(propertiesWithPlaceholderResolved); } + @SneakyThrows private static Object v2(final Environment environment, final String prefix, final Class targetClass) { - try { - Class binderClass = Class.forName("org.springframework.boot.context.properties.bind.Binder"); - Method getMethod = binderClass.getDeclaredMethod("get", Environment.class); - Method bindMethod = binderClass.getDeclaredMethod("bind", String.class, Class.class); - Object binderObject = getMethod.invoke(null, environment); - String prefixParam = prefix.endsWith(".") ? prefix.substring(0, prefix.length() - 1) : prefix; - Object bindResultObject = bindMethod.invoke(binderObject, prefixParam, targetClass); - Method resultGetMethod = bindResultObject.getClass().getDeclaredMethod("get"); - return resultGetMethod.invoke(bindResultObject); - } catch (final ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException ex) { - throw new ShardingException(ex.getMessage(), ex); - } + Class binderClass = Class.forName("org.springframework.boot.context.properties.bind.Binder"); + Method getMethod = binderClass.getDeclaredMethod("get", Environment.class); + Method bindMethod = binderClass.getDeclaredMethod("bind", String.class, Class.class); + Object binderObject = getMethod.invoke(null, environment); + String prefixParam = prefix.endsWith(".") ? prefix.substring(0, prefix.length() - 1) : prefix; + Object bindResultObject = bindMethod.invoke(binderObject, prefixParam, targetClass); + Method resultGetMethod = bindResultObject.getClass().getDeclaredMethod("get"); + return resultGetMethod.invoke(bindResultObject); } } diff --git a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/SpringBootShardingTest.java b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/SpringBootShardingTest.java index 17e2c06c673b1..873195843b558 100644 --- a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/SpringBootShardingTest.java +++ b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/test/java/io/shardingsphere/shardingjdbc/spring/boot/type/SpringBootShardingTest.java @@ -22,6 +22,7 @@ import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant; import io.shardingsphere.shardingjdbc.jdbc.core.ShardingContext; import io.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource; +import lombok.SneakyThrows; import org.apache.commons.dbcp2.BasicDataSource; import org.junit.Test; import org.junit.runner.RunWith; @@ -51,11 +52,9 @@ public class SpringBootShardingTest { private DataSource dataSource; @Test - public void assertWithShardingDataSource() throws NoSuchFieldException, IllegalAccessException { + public void assertWithShardingDataSource() { assertThat(dataSource, instanceOf(ShardingDataSource.class)); - Field field = ShardingDataSource.class.getDeclaredField("shardingContext"); - field.setAccessible(true); - ShardingContext shardingContext = (ShardingContext) field.get(dataSource); + ShardingContext shardingContext = getFieldValue("shardingContext", ShardingDataSource.class, dataSource); for (DataSource each : ((ShardingDataSource) dataSource).getDataSourceMap().values()) { assertThat(((BasicDataSource) each).getMaxTotal(), is(100)); } @@ -63,11 +62,16 @@ public void assertWithShardingDataSource() throws NoSuchFieldException, IllegalA Map configMap = new ConcurrentHashMap<>(); configMap.put("key1", "value1"); assertThat(ConfigMapContext.getInstance().getShardingConfig(), is(configMap)); - - Field propertiesField = ShardingDataSource.class.getDeclaredField("shardingProperties"); - propertiesField.setAccessible(true); - ShardingProperties shardingProperties = (ShardingProperties) propertiesField.get(dataSource); + ShardingProperties shardingProperties = getFieldValue("shardingProperties", ShardingDataSource.class, dataSource); assertTrue((Boolean) shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW)); assertThat((Integer) shardingProperties.getValue(ShardingPropertiesConstant.EXECUTOR_SIZE), is(100)); } + + @SuppressWarnings("unchecked") + @SneakyThrows + private T getFieldValue(final String fieldName, final Class fieldClass, final Object target) { + Field field = fieldClass.getDeclaredField(fieldName); + field.setAccessible(true); + return (T) field.get(target); + } } diff --git a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/spring/util/FieldValueUtil.java b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/spring/util/FieldValueUtil.java index 32bff56aa6493..1e667b5bbf265 100644 --- a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/spring/util/FieldValueUtil.java +++ b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/spring/util/FieldValueUtil.java @@ -20,6 +20,7 @@ import com.google.common.base.Strings; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import lombok.SneakyThrows; import java.lang.reflect.Field; @@ -42,17 +43,13 @@ public static Object getFieldValue(final Object obj, final String fieldName, fin return getFieldValue(clazz, obj, fieldName); } + @SneakyThrows private static Object getFieldValue(final Class clazz, final Object obj, final String fieldName) { - try { - Field field = clazz.getDeclaredField(fieldName); - if (!field.isAccessible()) { - field.setAccessible(true); - } - return field.get(obj); - } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - return null; + Field field = clazz.getDeclaredField(fieldName); + if (!field.isAccessible()) { + field.setAccessible(true); } + return field.get(obj); } /** diff --git a/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/ShardingTracerTest.java b/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/ShardingTracerTest.java index 1926baae5f5af..9dd5b3e802086 100644 --- a/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/ShardingTracerTest.java +++ b/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/ShardingTracerTest.java @@ -22,6 +22,7 @@ import io.opentracing.util.GlobalTracer; import io.shardingsphere.core.exception.ShardingException; import io.shardingsphere.opentracing.fixture.FooTracer; +import lombok.SneakyThrows; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -38,7 +39,7 @@ public final class ShardingTracerTest { @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + public void setUp() { System.setProperty("io.shardingsphere.opentracing.tracer.class", FooTracer.class.getName()); clearGlobalTracer(); } @@ -72,7 +73,8 @@ public void assertTracerClassError() { ShardingTracer.init(); } - private static void clearGlobalTracer() throws NoSuchFieldException, IllegalAccessException { + @SneakyThrows + private static void clearGlobalTracer() { Field tracerField = GlobalTracer.class.getDeclaredField("tracer"); tracerField.setAccessible(true); tracerField.set(GlobalTracer.class, NoopTracerFactory.create()); diff --git a/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/hook/BaseOpenTracingHookTest.java b/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/hook/BaseOpenTracingHookTest.java index 9dd515699128b..f1f6c31d90944 100644 --- a/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/hook/BaseOpenTracingHookTest.java +++ b/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/hook/BaseOpenTracingHookTest.java @@ -25,6 +25,7 @@ import io.opentracing.util.ThreadLocalActiveSpanSource; import io.shardingsphere.opentracing.ShardingTracer; import io.shardingsphere.opentracing.constant.ShardingErrorLogTags; +import lombok.SneakyThrows; import org.hamcrest.CoreMatchers; import org.junit.AfterClass; import org.junit.Before; @@ -47,7 +48,8 @@ public static void initTracer() { } @AfterClass - public static void releaseTracer() throws NoSuchFieldException, IllegalAccessException { + @SneakyThrows + public static void releaseTracer() { Field field = GlobalTracer.class.getDeclaredField("tracer"); field.setAccessible(true); field.set(GlobalTracer.class, NoopTracerFactory.create()); diff --git a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/DataSourceRepresenter.java b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/DataSourceRepresenter.java index 1bec7adbb9564..65c2473d34ab1 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/DataSourceRepresenter.java +++ b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/DataSourceRepresenter.java @@ -18,14 +18,13 @@ package io.shardingsphere.orchestration.internal.yaml.representer; import com.google.common.collect.Sets; -import io.shardingsphere.core.exception.ShardingException; +import lombok.SneakyThrows; import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import org.yaml.snakeyaml.nodes.Node; -import java.beans.IntrospectionException; import java.lang.reflect.Method; import java.util.Collection; import java.util.LinkedHashSet; @@ -51,26 +50,20 @@ public final class DataSourceRepresenter extends Representer { public DataSourceRepresenter(final Class clazz) { super(); - this.nullRepresenter = new NullRepresent(); + nullRepresenter = new NullRepresent(); propertyNames = getPropertyNames(clazz); } + @SneakyThrows @Override protected Set getProperties(final Class type) { - Set propertySet; - try { - propertySet = super.getProperties(type); - } catch (IntrospectionException ex) { - throw new ShardingException(ex); - } - Set filteredSet = new LinkedHashSet<>(); - for (Property prop : propertySet) { - String name = prop.getName(); - if (propertyNames.contains(name)) { - filteredSet.add(prop); + Set result = new LinkedHashSet<>(); + for (Property each : super.getProperties(type)) { + if (propertyNames.contains(each.getName())) { + result.add(each); } } - return filteredSet; + return result; } private Set getPropertyNames(final Class clazz) { diff --git a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/MasterSlaveConfigurationRepresenter.java b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/MasterSlaveConfigurationRepresenter.java index 4496704b0a418..7253c1bc51a80 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/MasterSlaveConfigurationRepresenter.java +++ b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/MasterSlaveConfigurationRepresenter.java @@ -17,14 +17,13 @@ package io.shardingsphere.orchestration.internal.yaml.representer; -import io.shardingsphere.core.exception.ShardingException; +import lombok.SneakyThrows; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import java.beans.IntrospectionException; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; @@ -45,25 +44,19 @@ public final class MasterSlaveConfigurationRepresenter extends Representer { public MasterSlaveConfigurationRepresenter() { super(); - this.nullRepresenter = new NullRepresent(); + nullRepresenter = new NullRepresent(); } @Override + @SneakyThrows protected Set getProperties(final Class type) { - Set propertySet; - try { - propertySet = super.getProperties(type); - } catch (IntrospectionException ex) { - throw new ShardingException(ex); - } - Set filteredSet = new LinkedHashSet<>(); - for (Property prop : propertySet) { - String name = prop.getName(); - if (!eliminatedPropertyNames.contains(name)) { - filteredSet.add(prop); + Set result = new LinkedHashSet<>(); + for (Property each : super.getProperties(type)) { + if (!eliminatedPropertyNames.contains(each.getName())) { + result.add(each); } } - return filteredSet; + return result; } private class NullRepresent implements Represent { diff --git a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/ProxyConfigurationRepresenter.java b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/ProxyConfigurationRepresenter.java index ff08dcc434f9e..9b0a9806376d8 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/ProxyConfigurationRepresenter.java +++ b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/ProxyConfigurationRepresenter.java @@ -17,14 +17,13 @@ package io.shardingsphere.orchestration.internal.yaml.representer; -import io.shardingsphere.core.exception.ShardingException; +import lombok.SneakyThrows; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import java.beans.IntrospectionException; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; @@ -46,25 +45,19 @@ public final class ProxyConfigurationRepresenter extends Representer { public ProxyConfigurationRepresenter() { super(); - this.nullRepresenter = new NullRepresent(); + nullRepresenter = new NullRepresent(); } + @SneakyThrows @Override protected Set getProperties(final Class type) { - Set propertySet; - try { - propertySet = super.getProperties(type); - } catch (IntrospectionException ex) { - throw new ShardingException(ex); - } - Set filteredSet = new LinkedHashSet<>(); - for (Property prop : propertySet) { - String name = prop.getName(); - if (!eliminatedPropertyNames.contains(name)) { - filteredSet.add(prop); + Set result = new LinkedHashSet<>(); + for (Property each : super.getProperties(type)) { + if (!eliminatedPropertyNames.contains(each.getName())) { + result.add(each); } } - return filteredSet; + return result; } private class NullRepresent implements Represent { diff --git a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/ShardingConfigurationRepresenter.java b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/ShardingConfigurationRepresenter.java index 366f993824196..0b6436ed1f62a 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/ShardingConfigurationRepresenter.java +++ b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/yaml/representer/ShardingConfigurationRepresenter.java @@ -17,14 +17,13 @@ package io.shardingsphere.orchestration.internal.yaml.representer; -import io.shardingsphere.core.exception.ShardingException; +import lombok.SneakyThrows; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import java.beans.IntrospectionException; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; @@ -46,25 +45,19 @@ public final class ShardingConfigurationRepresenter extends Representer { public ShardingConfigurationRepresenter() { super(); - this.nullRepresenter = new NullRepresent(); + nullRepresenter = new NullRepresent(); } + @SneakyThrows @Override protected Set getProperties(final Class type) { - Set propertySet; - try { - propertySet = super.getProperties(type); - } catch (IntrospectionException ex) { - throw new ShardingException(ex); - } - Set filteredSet = new LinkedHashSet<>(); - for (Property prop : propertySet) { - String name = prop.getName(); - if (!eliminatedPropertyNames.contains(name)) { - filteredSet.add(prop); + Set result = new LinkedHashSet<>(); + for (Property each : super.getProperties(type)) { + if (!eliminatedPropertyNames.contains(each.getName())) { + result.add(each); } } - return filteredSet; + return result; } private class NullRepresent implements Represent { diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCBackendDataSource.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCBackendDataSource.java index cb3130d52c65e..b2d1bc207ab8f 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCBackendDataSource.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCBackendDataSource.java @@ -27,7 +27,6 @@ import lombok.Getter; import javax.sql.DataSource; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; @@ -151,7 +150,7 @@ private void closeOriginalDataSources() { try { Method method = each.getClass().getDeclaredMethod("close"); method.invoke(each); - } catch (final NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { + } catch (final ReflectiveOperationException ignored) { } } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/response/mysql/MySQLResponseHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/response/mysql/MySQLResponseHandler.java index 0063cad01d250..43de55f1361a4 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/response/mysql/MySQLResponseHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/response/mysql/MySQLResponseHandler.java @@ -19,7 +19,6 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; -import io.shardingsphere.core.exception.ShardingException; import io.shardingsphere.core.metadata.datasource.DataSourceMetaData; import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.shardingproxy.backend.netty.client.response.ResponseHandler; @@ -37,10 +36,10 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.handshake.HandshakePacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.handshake.HandshakeResponse41Packet; import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; @@ -92,22 +91,19 @@ protected void auth(final ChannelHandlerContext context, final ByteBuf byteBuf) } } + @SneakyThrows private byte[] securePasswordAuthentication(final byte[] password, final byte[] authPluginData) { - try { - MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); - byte[] part1 = messageDigest.digest(password); - messageDigest.reset(); - byte[] part2 = messageDigest.digest(part1); - messageDigest.reset(); - messageDigest.update(authPluginData); - byte[] result = messageDigest.digest(part2); - for (int i = 0; i < result.length; i++) { - result[i] = (byte) (result[i] ^ part1[i]); - } - return result; - } catch (final NoSuchAlgorithmException ex) { - throw new ShardingException(ex); + MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); + byte[] part1 = messageDigest.digest(password); + messageDigest.reset(); + byte[] part2 = messageDigest.digest(part1); + messageDigest.reset(); + messageDigest.update(authPluginData); + byte[] result = messageDigest.digest(part2); + for (int i = 0; i < result.length; i++) { + result[i] = (byte) (result[i] ^ part1[i]); } + return result; } @Override diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegisterTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegisterTest.java index 8c377e19f1de4..f0ee9c602a7dc 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegisterTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegisterTest.java @@ -18,6 +18,7 @@ package io.shardingsphere.shardingproxy.listener; import io.shardingsphere.shardingproxy.config.ProxyContext; +import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -37,7 +38,8 @@ public final class ProxyListenerRegisterTest { private ProxyContext proxyContext; @Before - public void setUp() throws ReflectiveOperationException { + @SneakyThrows + public void setUp() { Field field = ProxyListenerRegister.class.getDeclaredField("proxyContext"); field.setAccessible(true); field.set(proxyListenerRegister, proxyContext); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/CommandPacketFactoryTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/CommandPacketFactoryTest.java index fd72bd278eec1..eefe1b00ff6ae 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/CommandPacketFactoryTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/CommandPacketFactoryTest.java @@ -35,6 +35,7 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.binary.prepare.ComStmtPreparePacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.text.fieldlist.ComFieldListPacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.text.query.ComQueryPacket; +import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -64,12 +65,13 @@ public final class CommandPacketFactoryTest { private FrontendHandler frontendHandler; @Before - public void setUp() throws ReflectiveOperationException { + public void setUp() { setProxyContextRuleRegistryMap(); setFrontendHandlerSchema(); } - private void setProxyContextRuleRegistryMap() throws ReflectiveOperationException { + @SneakyThrows + private void setProxyContextRuleRegistryMap() { RuleRegistry ruleRegistry = mock(RuleRegistry.class); ShardingMetaData metaData = mock(ShardingMetaData.class); when(ruleRegistry.getMetaData()).thenReturn(metaData); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacketTest.java index 7ac0ae5790256..b11cd2f3fd936 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacketTest.java @@ -27,6 +27,7 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.ErrPacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.OKPacket; +import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,7 +54,8 @@ public final class ComInitDbPacketTest { private FrontendHandler frontendHandler; @Before - public void setUp() throws ReflectiveOperationException { + @SneakyThrows + public void setUp() { List schemaNames = new ArrayList<>(1); schemaNames.add(ShardingConstant.LOGIC_SCHEMA_NAME); Field field = ProxyContext.class.getDeclaredField("schemaNames"); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/BinaryStatementRegistryTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/BinaryStatementRegistryTest.java index 6ade2db11f5e6..f759aed1bd3ef 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/BinaryStatementRegistryTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/BinaryStatementRegistryTest.java @@ -31,7 +31,7 @@ public final class BinaryStatementRegistryTest { @Before @After - public void reset() throws ReflectiveOperationException { + public void reset() { BinaryStatementRegistryUtil.reset(); } diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacketTest.java index 2549bdee6685f..f59df6e87377c 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacketTest.java @@ -29,6 +29,7 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.binary.BinaryStatementRegistry; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.binary.fixture.BinaryStatementRegistryUtil; +import lombok.SneakyThrows; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -62,17 +63,18 @@ public final class ComStmtExecutePacketTest { private FrontendHandler frontendHandler; @Before - public void setUp() throws ReflectiveOperationException { + public void setUp() { setProxyContextNIOConfig(); } @Before @After - public void reset() throws ReflectiveOperationException { + public void reset() { BinaryStatementRegistryUtil.reset(); } - private void setProxyContextNIOConfig() throws ReflectiveOperationException { + @SneakyThrows + private void setProxyContextNIOConfig() { Field field = ProxyContext.class.getDeclaredField("useNIO"); field.setAccessible(true); field.set(ProxyContext.getInstance(), true); @@ -93,7 +95,7 @@ public void assertWrite() throws SQLException { } @Test - public void assertExecute() throws ReflectiveOperationException, SQLException { + public void assertExecute() throws SQLException { BinaryStatementRegistry.getInstance().register("SELECT id FROM tbl WHERE id=?", 1); BackendHandler backendHandler = mock(BackendHandler.class); when(payload.readInt4()).thenReturn(1); @@ -114,7 +116,8 @@ public void assertExecute() throws ReflectiveOperationException, SQLException { assertFalse(packet.next()); } - private void setBackendHandler(final ComStmtExecutePacket packet, final BackendHandler backendHandler) throws ReflectiveOperationException { + @SneakyThrows + private void setBackendHandler(final ComStmtExecutePacket packet, final BackendHandler backendHandler) { Field field = ComStmtExecutePacket.class.getDeclaredField("backendHandler"); field.setAccessible(true); field.set(packet, backendHandler); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/fixture/BinaryStatementRegistryUtil.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/fixture/BinaryStatementRegistryUtil.java index c34efd55c311a..d81d3f84c4b6c 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/fixture/BinaryStatementRegistryUtil.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/fixture/BinaryStatementRegistryUtil.java @@ -20,6 +20,7 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.binary.BinaryStatementRegistry; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import lombok.SneakyThrows; import java.lang.reflect.Field; import java.util.Map; @@ -30,10 +31,9 @@ public final class BinaryStatementRegistryUtil { /** * Reset {@code BinaryStatementRegistry}. - * - * @throws ReflectiveOperationException reflective operation exception */ - public static void reset() throws ReflectiveOperationException { + @SneakyThrows + public static void reset() { Field statementIdAssignerField = BinaryStatementRegistry.class.getDeclaredField("statementIdAssigner"); statementIdAssignerField.setAccessible(true); ((Map) statementIdAssignerField.get(BinaryStatementRegistry.getInstance())).clear(); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacketTest.java index 1ed9813df7b35..d7fb8235569f5 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacketTest.java @@ -37,6 +37,7 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.ColumnDefinition41Packet; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.binary.fixture.BinaryStatementRegistryUtil; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.EofPacket; +import lombok.SneakyThrows; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Before; @@ -68,18 +69,19 @@ public final class ComStmtPreparePacketTest { private FrontendHandler frontendHandler; @Before - public void setUp() throws ReflectiveOperationException { + public void setUp() { setProxyContextRuleRegistryMap(); setFrontendHandlerSchema(); } @Before @After - public void reset() throws ReflectiveOperationException { + public void reset() { BinaryStatementRegistryUtil.reset(); } - private void setProxyContextRuleRegistryMap() throws ReflectiveOperationException { + @SneakyThrows + private void setProxyContextRuleRegistryMap() { RuleRegistry ruleRegistry = mock(RuleRegistry.class); ShardingMetaData metaData = mock(ShardingMetaData.class); when(ruleRegistry.getMetaData()).thenReturn(metaData); @@ -104,7 +106,7 @@ public void assertWrite() { } @Test - public void assertExecuteForQueryWithParameters() throws ReflectiveOperationException { + public void assertExecuteForQueryWithParameters() { SelectStatement selectStatement = new SelectStatement(); selectStatement.setParametersIndex(1); selectStatement.getTables().add(new Table("tbl", Optional.absent())); @@ -124,7 +126,7 @@ public void assertExecuteForQueryWithParameters() throws ReflectiveOperationExce } @Test - public void assertExecuteForQueryWithoutParameters() throws ReflectiveOperationException { + public void assertExecuteForQueryWithoutParameters() { SelectStatement selectStatement = new SelectStatement(); selectStatement.getTables().add(new Table("tbl", Optional.absent())); selectStatement.getItems().addAll(Collections.singletonList(new CommonSelectItem("1", Optional.absent()))); @@ -136,7 +138,7 @@ public void assertExecuteForQueryWithoutParameters() throws ReflectiveOperationE } @Test - public void assertExecuteForInsertWithoutParameters() throws ReflectiveOperationException { + public void assertExecuteForInsertWithoutParameters() { InsertStatement insertStatement = new InsertStatement(); insertStatement.getTables().add(new Table("tbl", Optional.absent())); Optional actual = getComStmtPreparePacketWithMockedSQLParsingEngine("INSERT INTO tbl VALUES(1)", insertStatement).execute(); @@ -147,7 +149,7 @@ public void assertExecuteForInsertWithoutParameters() throws ReflectiveOperation } @Test - public void assertExecuteForDALWithoutParameters() throws ReflectiveOperationException { + public void assertExecuteForDALWithoutParameters() { ShowTablesStatement showTablesStatement = new ShowTablesStatement(); Optional actual = getComStmtPreparePacketWithMockedSQLParsingEngine("SHOW TABLES", showTablesStatement).execute(); assertTrue(actual.isPresent()); @@ -156,7 +158,8 @@ public void assertExecuteForDALWithoutParameters() throws ReflectiveOperationExc assertThat(actual.get().getHeadPacket().getSequenceId(), is(1)); } - private ComStmtPreparePacket getComStmtPreparePacketWithMockedSQLParsingEngine(final String sql, final SQLStatement sqlStatement) throws ReflectiveOperationException { + @SneakyThrows + private ComStmtPreparePacket getComStmtPreparePacketWithMockedSQLParsingEngine(final String sql, final SQLStatement sqlStatement) { when(payload.readStringEOF()).thenReturn(sql); ComStmtPreparePacket result = new ComStmtPreparePacket(1, payload, frontendHandler); SQLParsingEngine sqlParsingEngine = mock(SQLParsingEngine.class); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/fieldlist/ComFieldListPacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/fieldlist/ComFieldListPacketTest.java index 2b3642f514dbb..a34cc70f8babd 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/fieldlist/ComFieldListPacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/fieldlist/ComFieldListPacketTest.java @@ -32,6 +32,7 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.FieldCountPacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.EofPacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.ErrPacket; +import lombok.SneakyThrows; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -76,7 +77,7 @@ public void assertWrite() { } @Test - public void assertExecuteWhenSuccess() throws SQLException, ReflectiveOperationException { + public void assertExecuteWhenSuccess() throws SQLException { when(payload.readStringNul()).thenReturn("tbl"); when(payload.readStringEOF()).thenReturn("-"); when(backendHandler.next()).thenReturn(true, false); @@ -103,7 +104,7 @@ private void assertEofPacket(final EofPacket actual) { } @Test - public void assertExecuteWhenFailure() throws SQLException, ReflectiveOperationException { + public void assertExecuteWhenFailure() throws SQLException { when(payload.readStringNul()).thenReturn("tbl"); when(payload.readStringEOF()).thenReturn("-"); CommandResponsePackets expected = new CommandResponsePackets(new ErrPacket(1, ServerErrorCode.ER_STD_UNKNOWN_EXCEPTION, "unknown")); @@ -115,7 +116,8 @@ public void assertExecuteWhenFailure() throws SQLException, ReflectiveOperationE assertThat(actual.get(), is(expected)); } - private void setBackendHandler(final ComFieldListPacket packet) throws ReflectiveOperationException { + @SneakyThrows + private void setBackendHandler(final ComFieldListPacket packet) { Field field = ComFieldListPacket.class.getDeclaredField("backendHandler"); field.setAccessible(true); field.set(packet, backendHandler); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacketTest.java index 5e5dfbc073ebf..57236698dec76 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacketTest.java @@ -40,6 +40,7 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.OKPacket; import lombok.Getter; import lombok.Setter; +import lombok.SneakyThrows; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Before; @@ -77,7 +78,7 @@ public final class ComQueryPacketTest { private Listener listener; @Before - public void setUp() throws ReflectiveOperationException { + public void setUp() { setProxyContextNIOConfig(); setProxyContextRuleRegistryMap(); setFrontendHandlerSchema(); @@ -87,18 +88,20 @@ public void setUp() throws ReflectiveOperationException { } @After - public void tearDown() throws ReflectiveOperationException { + public void tearDown() { ShardingEventBusInstance.getInstance().unregister(listener); setTransactionType(null); } - private void setProxyContextNIOConfig() throws ReflectiveOperationException { + @SneakyThrows + private void setProxyContextNIOConfig() { Field field = ProxyContext.class.getDeclaredField("useNIO"); field.setAccessible(true); field.set(ProxyContext.getInstance(), true); } - private void setProxyContextRuleRegistryMap() throws ReflectiveOperationException { + @SneakyThrows + private void setProxyContextRuleRegistryMap() { RuleRegistry ruleRegistry = mock(RuleRegistry.class); Map ruleRegistryMap = new HashMap<>(); ruleRegistryMap.put(ShardingConstant.LOGIC_SCHEMA_NAME, ruleRegistry); @@ -111,7 +114,8 @@ private void setFrontendHandlerSchema() { when(frontendHandler.getCurrentSchema()).thenReturn(ShardingConstant.LOGIC_SCHEMA_NAME); } - private void setTransactionType(final TransactionType transactionType) throws ReflectiveOperationException { + @SneakyThrows + private void setTransactionType(final TransactionType transactionType) { Field transactionTypeField = ProxyContext.class.getDeclaredField("transactionType"); transactionTypeField.setAccessible(true); transactionTypeField.set(ProxyContext.getInstance(), transactionType); @@ -127,7 +131,7 @@ public void assertWrite() { } @Test - public void assertExecuteWithoutTransaction() throws SQLException, ReflectiveOperationException { + public void assertExecuteWithoutTransaction() throws SQLException { when(payload.readStringEOF()).thenReturn("SELECT id FROM tbl"); BackendHandler backendHandler = mock(BackendHandler.class); when(backendHandler.next()).thenReturn(true, false); @@ -149,14 +153,15 @@ public void assertExecuteWithoutTransaction() throws SQLException, ReflectiveOpe assertFalse(packet.next()); } - private void setBackendHandler(final ComQueryPacket packet, final BackendHandler backendHandler) throws ReflectiveOperationException { + @SneakyThrows + private void setBackendHandler(final ComQueryPacket packet, final BackendHandler backendHandler) { Field field = ComQueryPacket.class.getDeclaredField("backendHandler"); field.setAccessible(true); field.set(packet, backendHandler); } @Test - public void assertExecuteTCLWithLocalTransaction() throws SQLException, ReflectiveOperationException { + public void assertExecuteTCLWithLocalTransaction() throws SQLException { setTransactionType(TransactionType.LOCAL); when(payload.readStringEOF()).thenReturn("COMMIT"); ComQueryPacket packet = new ComQueryPacket(1, 1000, payload, backendConnection, frontendHandler); @@ -167,7 +172,7 @@ public void assertExecuteTCLWithLocalTransaction() throws SQLException, Reflecti } @Test - public void assertExecuteTCLWithXATransaction() throws SQLException, ReflectiveOperationException { + public void assertExecuteTCLWithXATransaction() throws SQLException { setTransactionType(TransactionType.XA); when(payload.readStringEOF()).thenReturn("COMMIT"); ComQueryPacket packet = new ComQueryPacket(1, 1000, payload, backendConnection, frontendHandler); @@ -178,7 +183,7 @@ public void assertExecuteTCLWithXATransaction() throws SQLException, ReflectiveO } @Test - public void assertExecuteRollbackWithXATransaction() throws SQLException, ReflectiveOperationException { + public void assertExecuteRollbackWithXATransaction() throws SQLException { setTransactionType(TransactionType.XA); listener.setExpected(TransactionOperationType.ROLLBACK); when(payload.readStringEOF()).thenReturn("ROLLBACK"); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthorityHandlerTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthorityHandlerTest.java index aff4cb176a8b6..9d1437b19d413 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthorityHandlerTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthorityHandlerTest.java @@ -20,6 +20,7 @@ import com.google.common.primitives.Bytes; import io.shardingsphere.core.rule.ProxyAuthority; import io.shardingsphere.shardingproxy.config.ProxyContext; +import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; @@ -38,19 +39,21 @@ public final class AuthorityHandlerTest { private final byte[] part2 = {83, 121, 75, 81, 87, 56, 120, 112, 73, 109, 77, 69}; @Before - public void setUp() throws ReflectiveOperationException { + public void setUp() { initProxyAuthorityForProxyContext(); initAuthPluginDataForAuthorityHandler(); } - private void initProxyAuthorityForProxyContext() throws ReflectiveOperationException { + @SneakyThrows + private void initProxyAuthorityForProxyContext() { ProxyAuthority proxyAuthority = new ProxyAuthority(); Field field = ProxyContext.class.getDeclaredField("proxyAuthority"); field.setAccessible(true); field.set(ProxyContext.getInstance(), proxyAuthority); } - private void initAuthPluginDataForAuthorityHandler() throws ReflectiveOperationException { + @SneakyThrows + private void initAuthPluginDataForAuthorityHandler() { AuthPluginData authPluginData = new AuthPluginData(part1, part2); Field field = AuthorityHandler.class.getDeclaredField("authPluginData"); field.setAccessible(true); diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/ConnectionIdGeneratorTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/ConnectionIdGeneratorTest.java index d581ef598c162..f10956e456497 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/ConnectionIdGeneratorTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/ConnectionIdGeneratorTest.java @@ -17,6 +17,7 @@ package io.shardingsphere.shardingproxy.transport.mysql.packet.handshake; +import lombok.SneakyThrows; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -31,24 +32,25 @@ public final class ConnectionIdGeneratorTest { @Before @After - public void resetConnectionId() throws ReflectiveOperationException { + public void resetConnectionId() { setCurrentConnectionId(0); } - private void setCurrentConnectionId(final int connectionId) throws ReflectiveOperationException { - Field field = ConnectionIdGenerator.class.getDeclaredField("currentId"); - field.setAccessible(true); - field.set(ConnectionIdGenerator.getInstance(), connectionId); - } - @Test public void assertNextId() { assertEquals(ConnectionIdGenerator.getInstance().nextId(), 1); } @Test - public void assertMaxNextId() throws ReflectiveOperationException { + public void assertMaxNextId() { setCurrentConnectionId(Integer.MAX_VALUE); assertThat(ConnectionIdGenerator.getInstance().nextId(), is(1)); } + + @SneakyThrows + private void setCurrentConnectionId(final int connectionId) { + Field field = ConnectionIdGenerator.class.getDeclaredField("currentId"); + field.setAccessible(true); + field.set(ConnectionIdGenerator.getInstance(), connectionId); + } } diff --git a/sharding-sql-test/src/main/java/io/shardingsphere/test/sql/SQLCasesLoader.java b/sharding-sql-test/src/main/java/io/shardingsphere/test/sql/SQLCasesLoader.java index bfc71324c6af7..097d77aaf0c7e 100644 --- a/sharding-sql-test/src/main/java/io/shardingsphere/test/sql/SQLCasesLoader.java +++ b/sharding-sql-test/src/main/java/io/shardingsphere/test/sql/SQLCasesLoader.java @@ -19,12 +19,12 @@ import com.google.common.base.Preconditions; import com.google.common.base.Strings; +import lombok.SneakyThrows; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -69,13 +69,10 @@ public static SQLCasesLoader getInstance() { return INSTANCE; } + @SneakyThrows private static Map loadSQLCases(final String path) { File file = new File(SQLCasesLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath()); - try { - return file.isFile() ? loadSQLCasesFromJar(path, file) : loadSQLCasesFromTargetDirectory(path); - } catch (final IOException | JAXBException ex) { - throw new RuntimeException(ex); - } + return file.isFile() ? loadSQLCasesFromJar(path, file) : loadSQLCasesFromTargetDirectory(path); } private static Map loadSQLCasesFromJar(final String path, final File file) throws IOException, JAXBException { @@ -92,7 +89,7 @@ private static Map loadSQLCasesFromJar(final String path, final return result; } - private static Map loadSQLCasesFromTargetDirectory(final String path) throws FileNotFoundException, JAXBException { + private static Map loadSQLCasesFromTargetDirectory(final String path) { Map result = new TreeMap<>(); URL url = SQLCasesLoader.class.getClassLoader().getResource(path); if (null == url) { @@ -112,7 +109,8 @@ private static Map loadSQLCasesFromTargetDirectory(final String return result; } - private static void loadSQLCasesFromDirectory(final Map sqlStatementMap, final File file) throws FileNotFoundException, JAXBException { + @SneakyThrows + private static void loadSQLCasesFromDirectory(final Map sqlStatementMap, final File file) { if (file.isDirectory()) { File[] files = file.listFiles(); if (null == files) { @@ -126,14 +124,14 @@ private static void loadSQLCasesFromDirectory(final Map sqlStat } } - private static void fillSQLMap(final Map sqlCaseMap, final InputStream inputStream) throws FileNotFoundException, JAXBException { + private static void fillSQLMap(final Map sqlCaseMap, final InputStream inputStream) throws JAXBException { SQLCases sqlCases = (SQLCases) JAXBContext.newInstance(SQLCases.class).createUnmarshaller().unmarshal(inputStream); for (SQLCase each : sqlCases.getSqlCases()) { sqlCaseMap.put(each.getId(), each); } } - private static void fillSQLMap(final Map sqlCaseMap, final InputStream inputStream, final String sqlType) throws FileNotFoundException, JAXBException { + private static void fillSQLMap(final Map sqlCaseMap, final InputStream inputStream, final String sqlType) throws JAXBException { SQLCases sqlCases = (SQLCases) JAXBContext.newInstance(SQLCases.class).createUnmarshaller().unmarshal(inputStream); for (SQLCase each : sqlCases.getSqlCases()) { each.setSqlType(sqlType); diff --git a/sharding-transaction/src/test/java/io/shardingsphere/transaction/listener/xa/XATransactionListenerTest.java b/sharding-transaction/src/test/java/io/shardingsphere/transaction/listener/xa/XATransactionListenerTest.java index ea1423b8dfa74..905e3f5adef0d 100644 --- a/sharding-transaction/src/test/java/io/shardingsphere/transaction/listener/xa/XATransactionListenerTest.java +++ b/sharding-transaction/src/test/java/io/shardingsphere/transaction/listener/xa/XATransactionListenerTest.java @@ -22,6 +22,7 @@ import io.shardingsphere.core.event.ShardingEventBusInstance; import io.shardingsphere.core.event.transaction.xa.XATransactionEvent; import io.shardingsphere.transaction.manager.ShardingTransactionManager; +import lombok.SneakyThrows; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -45,7 +46,8 @@ public final class XATransactionListenerTest { private ShardingTransactionManager shardingTransactionManager; @Before - public void setUp() throws ReflectiveOperationException { + @SneakyThrows + public void setUp() { Field field = XATransactionListener.class.getDeclaredField("shardingTransactionManager"); field.setAccessible(true); field.set(xaTransactionListener, shardingTransactionManager); diff --git a/sharding-transaction/src/test/java/io/shardingsphere/transaction/manager/xa/atomikos/AtomikosTransactionManagerTest.java b/sharding-transaction/src/test/java/io/shardingsphere/transaction/manager/xa/atomikos/AtomikosTransactionManagerTest.java index c83444583ca90..ce20edc967ee9 100644 --- a/sharding-transaction/src/test/java/io/shardingsphere/transaction/manager/xa/atomikos/AtomikosTransactionManagerTest.java +++ b/sharding-transaction/src/test/java/io/shardingsphere/transaction/manager/xa/atomikos/AtomikosTransactionManagerTest.java @@ -23,6 +23,7 @@ import io.shardingsphere.core.constant.transaction.TransactionOperationType; import io.shardingsphere.core.event.transaction.xa.XATransactionEvent; import io.shardingsphere.core.rule.DataSourceParameter; +import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -51,7 +52,8 @@ public final class AtomikosTransactionManagerTest { private UserTransactionManager userTransactionManager; @Before - public void setUp() throws ReflectiveOperationException { + @SneakyThrows + public void setUp() { Field field = AtomikosTransactionManager.class.getDeclaredField("USER_TRANSACTION_MANAGER"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers");