From fdae62f78b176d5f2aa260b54dfc5d2d3845ca5e Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 16:47:29 +0800 Subject: [PATCH 01/34] refactor all test for sharding-core --- .../test/java/io/shardingsphere/AllTests.java | 32 +++++++++++++++++++ .../core/{AllTests.java => AllCoreTests.java} | 4 +-- 2 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 sharding-core/src/test/java/io/shardingsphere/AllTests.java rename sharding-core/src/test/java/io/shardingsphere/core/{AllTests.java => AllCoreTests.java} (94%) diff --git a/sharding-core/src/test/java/io/shardingsphere/AllTests.java b/sharding-core/src/test/java/io/shardingsphere/AllTests.java new file mode 100644 index 0000000000000..f268e64075e4e --- /dev/null +++ b/sharding-core/src/test/java/io/shardingsphere/AllTests.java @@ -0,0 +1,32 @@ +/* + * Copyright 2016-2018 shardingsphere.io. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *

+ */ + +package io.shardingsphere; + +import io.shardingsphere.api.AllApiTests; +import io.shardingsphere.core.AllCoreTests; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AllApiTests.class, + AllCoreTests.class + }) +public final class AllTests { +} diff --git a/sharding-core/src/test/java/io/shardingsphere/core/AllTests.java b/sharding-core/src/test/java/io/shardingsphere/core/AllCoreTests.java similarity index 94% rename from sharding-core/src/test/java/io/shardingsphere/core/AllTests.java rename to sharding-core/src/test/java/io/shardingsphere/core/AllCoreTests.java index effc80cfdd92d..d257c8db607f6 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/AllTests.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/AllCoreTests.java @@ -17,7 +17,6 @@ package io.shardingsphere.core; -import io.shardingsphere.api.AllApiTests; import io.shardingsphere.core.constant.AllConstantsTests; import io.shardingsphere.core.executor.AllExecutorTests; import io.shardingsphere.core.hint.AllHintTests; @@ -36,7 +35,6 @@ @RunWith(Suite.class) @SuiteClasses({ AllConstantsTests.class, - AllApiTests.class, AllUtilTests.class, AllMetaDataTests.class, AllParsingTests.class, @@ -48,5 +46,5 @@ AllHintTests.class, AllYamlTests.class }) -public final class AllTests { +public final class AllCoreTests { } From fd7b68c6acdfe445c2a14844cf63dd2f0571cb24 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 16:51:17 +0800 Subject: [PATCH 02/34] remove useless log --- .../io/shardingsphere/core/keygen/DefaultKeyGenerator.java | 7 ------- .../groupby/aggregation/AccumulationAggregationUnit.java | 3 --- .../dql/groupby/aggregation/AverageAggregationUnit.java | 3 --- .../dql/groupby/aggregation/ComparableAggregationUnit.java | 4 ---- .../core/routing/type/complex/CartesianRoutingEngine.java | 3 --- .../core/routing/type/complex/ComplexRoutingEngine.java | 3 --- .../core/routing/type/hint/DatabaseHintRoutingEngine.java | 4 ---- 7 files changed, 27 deletions(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/keygen/DefaultKeyGenerator.java b/sharding-core/src/main/java/io/shardingsphere/core/keygen/DefaultKeyGenerator.java index 7f38f54150597..9218ca139991b 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/keygen/DefaultKeyGenerator.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/keygen/DefaultKeyGenerator.java @@ -19,11 +19,8 @@ import com.google.common.base.Preconditions; import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import java.text.SimpleDateFormat; import java.util.Calendar; -import java.util.Date; /** * Default distributed primary key generator. @@ -45,7 +42,6 @@ * * @author gaohongtao */ -@Slf4j public final class DefaultKeyGenerator implements KeyGenerator { public static final long EPOCH; @@ -108,9 +104,6 @@ public synchronized Number generateKey() { sequence = 0; } lastTime = currentMillis; - if (log.isDebugEnabled()) { - log.debug("{}-{}-{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(lastTime)), workerId, sequence); - } return ((currentMillis - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | (workerId << WORKER_ID_LEFT_SHIFT_BITS) | sequence; } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/AccumulationAggregationUnit.java b/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/AccumulationAggregationUnit.java index 6daf8854fd5c8..317473f4dbf93 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/AccumulationAggregationUnit.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/AccumulationAggregationUnit.java @@ -18,7 +18,6 @@ package io.shardingsphere.core.merger.dql.groupby.aggregation; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import java.math.BigDecimal; import java.util.List; @@ -29,7 +28,6 @@ * @author zhangliang */ @RequiredArgsConstructor -@Slf4j public final class AccumulationAggregationUnit implements AggregationUnit { private BigDecimal result; @@ -43,7 +41,6 @@ public void merge(final List> values) { result = new BigDecimal("0"); } result = result.add(new BigDecimal(values.get(0).toString())); - log.trace("Accumulation result: {}", result.toString()); } @Override diff --git a/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/AverageAggregationUnit.java b/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/AverageAggregationUnit.java index faa76d46ae184..8f8dcd4b48d23 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/AverageAggregationUnit.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/AverageAggregationUnit.java @@ -18,7 +18,6 @@ package io.shardingsphere.core.merger.dql.groupby.aggregation; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import java.math.BigDecimal; import java.util.List; @@ -29,7 +28,6 @@ * @author gaohongtao */ @RequiredArgsConstructor -@Slf4j public final class AverageAggregationUnit implements AggregationUnit { private BigDecimal count; @@ -49,7 +47,6 @@ public void merge(final List> values) { } count = count.add(new BigDecimal(values.get(0).toString())); sum = sum.add(new BigDecimal(values.get(1).toString())); - log.trace("AVG result COUNT: {} SUM: {}", count, sum); } @Override diff --git a/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/ComparableAggregationUnit.java b/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/ComparableAggregationUnit.java index 2808faa88a5ef..71ad5282329e9 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/ComparableAggregationUnit.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/groupby/aggregation/ComparableAggregationUnit.java @@ -18,7 +18,6 @@ package io.shardingsphere.core.merger.dql.groupby.aggregation; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import java.util.List; @@ -28,7 +27,6 @@ * @author gaohongtao */ @RequiredArgsConstructor -@Slf4j public final class ComparableAggregationUnit implements AggregationUnit { private final boolean asc; @@ -43,13 +41,11 @@ public void merge(final List> values) { } if (null == result) { result = values.get(0); - log.trace("Comparable result: {}", result); return; } int comparedValue = ((Comparable) values.get(0)).compareTo(result); if (asc && comparedValue < 0 || !asc && comparedValue > 0) { result = values.get(0); - log.trace("Comparable result: {}", result); } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/routing/type/complex/CartesianRoutingEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/routing/type/complex/CartesianRoutingEngine.java index 2acc8c94e5b78..08dbb8a4da6c2 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/routing/type/complex/CartesianRoutingEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/routing/type/complex/CartesianRoutingEngine.java @@ -27,7 +27,6 @@ import io.shardingsphere.core.routing.type.TableUnit; import io.shardingsphere.core.routing.type.TableUnits; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Collection; @@ -45,7 +44,6 @@ * @author maxiaoguang */ @RequiredArgsConstructor -@Slf4j public final class CartesianRoutingEngine implements RoutingEngine { private final Collection routingResults; @@ -58,7 +56,6 @@ public RoutingResult route() { List> routingTableGroups = toRoutingTableGroups(entry.getKey(), actualTableGroups); result.getTableUnits().getTableUnits().addAll(getTableUnits(entry.getKey(), Sets.cartesianProduct(routingTableGroups)).getTableUnits()); } - log.trace("cartesian tables sharding result: {}", result); return result; } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/routing/type/complex/ComplexRoutingEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/routing/type/complex/ComplexRoutingEngine.java index d1724b04db61b..eb3f365877bd5 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/routing/type/complex/ComplexRoutingEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/routing/type/complex/ComplexRoutingEngine.java @@ -29,7 +29,6 @@ import io.shardingsphere.core.rule.ShardingRule; import io.shardingsphere.core.rule.TableRule; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Collection; @@ -42,7 +41,6 @@ * @author zhangliang */ @RequiredArgsConstructor -@Slf4j public final class ComplexRoutingEngine implements RoutingEngine { private final ShardingRule shardingRule; @@ -73,7 +71,6 @@ public String apply(final TableRule input) { } } } - log.trace("mixed tables sharding result: {}", result); if (result.isEmpty()) { throw new ShardingException("Cannot find table rule and default data source with logic tables: '%s'", logicTables); } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/routing/type/hint/DatabaseHintRoutingEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/routing/type/hint/DatabaseHintRoutingEngine.java index 5ce855f8fb1a3..e4f97216e2eef 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/routing/type/hint/DatabaseHintRoutingEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/routing/type/hint/DatabaseHintRoutingEngine.java @@ -26,7 +26,6 @@ import io.shardingsphere.core.routing.type.RoutingResult; import io.shardingsphere.core.routing.type.TableUnit; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import java.util.Collection; import java.util.Collections; @@ -39,7 +38,6 @@ * @author maxiaoguang */ @RequiredArgsConstructor -@Slf4j public final class DatabaseHintRoutingEngine implements RoutingEngine { private final Collection dataSourceNames; @@ -50,11 +48,9 @@ public final class DatabaseHintRoutingEngine implements RoutingEngine { public RoutingResult route() { Optional shardingValue = HintManagerHolder.getDatabaseShardingValue(HintManagerHolder.DB_TABLE_NAME); Preconditions.checkState(shardingValue.isPresent()); - log.debug("Before database sharding only db:{} sharding values: {}", dataSourceNames, shardingValue.get()); Collection routingDataSources; routingDataSources = databaseShardingStrategy.doSharding(dataSourceNames, Collections.singletonList(shardingValue.get())); Preconditions.checkState(!routingDataSources.isEmpty(), "no database route info"); - log.debug("After database sharding only result: {}", routingDataSources); RoutingResult result = new RoutingResult(); for (String each : routingDataSources) { result.getTableUnits().getTableUnits().add(new TableUnit(each)); From d7cd6df8de5308fc4f06d0c66990715c92747244 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 17:03:59 +0800 Subject: [PATCH 03/34] use hikari to test --- .../resources/yaml/master-slave-rule.yaml | 12 +++---- .../test/resources/yaml/optimize-rule.yaml | 8 ++--- .../src/test/resources/yaml/parser-rule.yaml | 8 ++--- .../src/test/resources/yaml/rewrite-rule.yaml | 8 ++--- .../test/resources/yaml/sharding-rule.yaml | 34 +++++++++---------- 5 files changed, 35 insertions(+), 35 deletions(-) diff --git a/sharding-core/src/test/resources/yaml/master-slave-rule.yaml b/sharding-core/src/test/resources/yaml/master-slave-rule.yaml index f7e8e4d9ab8fb..912edb59606a4 100644 --- a/sharding-core/src/test/resources/yaml/master-slave-rule.yaml +++ b/sharding-core/src/test/resources/yaml/master-slave-rule.yaml @@ -1,17 +1,17 @@ dataSources: - master_ds: !!org.apache.commons.dbcp2.BasicDataSource + master_ds: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:master_ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:master_ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - slave_ds_0: !!org.apache.commons.dbcp2.BasicDataSource + slave_ds_0: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:slave_ds_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:slave_ds_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - slave_ds_1: !!org.apache.commons.dbcp2.BasicDataSource + slave_ds_1: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:slave_ds_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:slave_ds_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: diff --git a/sharding-core/src/test/resources/yaml/optimize-rule.yaml b/sharding-core/src/test/resources/yaml/optimize-rule.yaml index 4066ce18891eb..5ccf5fc85ee3a 100644 --- a/sharding-core/src/test/resources/yaml/optimize-rule.yaml +++ b/sharding-core/src/test/resources/yaml/optimize-rule.yaml @@ -1,12 +1,12 @@ dataSources: - ds_0: !!org.apache.commons.dbcp2.BasicDataSource + ds_0: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:db0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:db0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - ds_1: !!org.apache.commons.dbcp2.BasicDataSource + ds_1: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: diff --git a/sharding-core/src/test/resources/yaml/parser-rule.yaml b/sharding-core/src/test/resources/yaml/parser-rule.yaml index 915ddaf06fabb..4ebcfe56865e6 100644 --- a/sharding-core/src/test/resources/yaml/parser-rule.yaml +++ b/sharding-core/src/test/resources/yaml/parser-rule.yaml @@ -1,12 +1,12 @@ dataSources: - db0: !!org.apache.commons.dbcp2.BasicDataSource + db0: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:db0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:db0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - db1: !!org.apache.commons.dbcp2.BasicDataSource + db1: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: diff --git a/sharding-core/src/test/resources/yaml/rewrite-rule.yaml b/sharding-core/src/test/resources/yaml/rewrite-rule.yaml index 7a30e9fb02947..06719ca16986b 100644 --- a/sharding-core/src/test/resources/yaml/rewrite-rule.yaml +++ b/sharding-core/src/test/resources/yaml/rewrite-rule.yaml @@ -1,12 +1,12 @@ dataSources: - db0: !!org.apache.commons.dbcp2.BasicDataSource + db0: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:db0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:db0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - db1: !!org.apache.commons.dbcp2.BasicDataSource + db1: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: diff --git a/sharding-core/src/test/resources/yaml/sharding-rule.yaml b/sharding-core/src/test/resources/yaml/sharding-rule.yaml index de891667e2ac9..57aa4b7ccdf63 100644 --- a/sharding-core/src/test/resources/yaml/sharding-rule.yaml +++ b/sharding-core/src/test/resources/yaml/sharding-rule.yaml @@ -1,39 +1,39 @@ dataSources: - master_ds_0: !!org.apache.commons.dbcp2.BasicDataSource + master_ds_0: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:master_ds_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:master_ds_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - master_ds_0_slave_0: !!org.apache.commons.dbcp2.BasicDataSource + master_ds_0_slave_0: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:master_ds_0_slave_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:master_ds_0_slave_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - master_ds_0_slave_1: !!org.apache.commons.dbcp2.BasicDataSource + master_ds_0_slave_1: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:master_ds_0_slave_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:master_ds_0_slave_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - master_ds_1: !!org.apache.commons.dbcp2.BasicDataSource + master_ds_1: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:master_ds_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:master_ds_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - master_ds_1_slave_0: !!org.apache.commons.dbcp2.BasicDataSource + master_ds_1_slave_0: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:master_ds_1_slave_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:master_ds_1_slave_0;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - master_ds_1_slave_1: !!org.apache.commons.dbcp2.BasicDataSource + master_ds_1_slave_1: !!com.zaxxer.hikari.HikariDataSource driverClassName: org.h2.Driver - url: jdbc:h2:mem:master_ds_1_slave_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + jdbcUrl: jdbc:h2:mem:master_ds_1_slave_1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL + username: sa + password: + default_ds: !!com.zaxxer.hikari.HikariDataSource + driverClassName: org.h2.Driver + jdbcUrl: jdbc:h2:mem:default_ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL username: sa password: - default_ds: !!org.apache.commons.dbcp2.BasicDataSource - driverClassName: org.h2.Driver - url: jdbc:h2:mem:default_ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL - username: sa - password: shardingRule: tables: From fce76473c3d4655ff2581d779e8fb66bd9744009 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 17:05:02 +0800 Subject: [PATCH 04/34] remove useless dependency for sharding-core --- sharding-core/pom.xml | 39 +++++++++++---------------------------- 1 file changed, 11 insertions(+), 28 deletions(-) diff --git a/sharding-core/pom.xml b/sharding-core/pom.xml index cb22e92ad49f0..c7553371bc4b6 100644 --- a/sharding-core/pom.xml +++ b/sharding-core/pom.xml @@ -10,11 +10,8 @@ sharding-core ${project.artifactId} + - - org.projectlombok - lombok - com.google.guava guava @@ -32,6 +29,15 @@ org.yaml snakeyaml + + org.slf4j + slf4j-api + + + + org.projectlombok + lombok + io.shardingsphere @@ -39,6 +45,7 @@ ${project.version} test + junit junit @@ -51,30 +58,6 @@ com.h2database h2 - - mysql - mysql-connector-java - - - org.postgresql - postgresql - - - com.microsoft.sqlserver - mssql-jdbc - - - org.slf4j - slf4j-api - - - org.apache.commons - commons-dbcp2 - - - commons-pool - commons-pool - com.zaxxer HikariCP-java7 From 286e4720cfba9cd4e9071c8c3c439934d5dce4bd Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 17:16:43 +0800 Subject: [PATCH 05/34] remove useless dependencies for sharding-jdbc-core --- sharding-jdbc/pom.xml | 20 ++++++++--- sharding-jdbc/sharding-jdbc-core/pom.xml | 46 +++++++++--------------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/sharding-jdbc/pom.xml b/sharding-jdbc/pom.xml index bbe526937a8f0..8f93a65d27870 100644 --- a/sharding-jdbc/pom.xml +++ b/sharding-jdbc/pom.xml @@ -33,8 +33,8 @@ mockito-core - com.h2database - h2 + com.zaxxer + HikariCP-java7 org.apache.commons @@ -45,12 +45,24 @@ commons-pool - org.apache.curator - curator-test + com.h2database + h2 mysql mysql-connector-java + + org.postgresql + postgresql + + + com.microsoft.sqlserver + mssql-jdbc + + + org.apache.curator + curator-test + diff --git a/sharding-jdbc/sharding-jdbc-core/pom.xml b/sharding-jdbc/sharding-jdbc-core/pom.xml index d32b2da2e312d..e9580a06f1f22 100644 --- a/sharding-jdbc/sharding-jdbc-core/pom.xml +++ b/sharding-jdbc/sharding-jdbc-core/pom.xml @@ -15,10 +15,6 @@ ${project.version} - - org.projectlombok - lombok - com.google.guava guava @@ -37,6 +33,11 @@ snakeyaml + + org.projectlombok + lombok + + io.shardingsphere sharding-sql-test @@ -52,24 +53,8 @@ mockito-core - com.h2database - h2 - - - mysql - mysql-connector-java - - - org.postgresql - postgresql - - - com.microsoft.sqlserver - mssql-jdbc - - - org.slf4j - slf4j-api + com.zaxxer + HikariCP-java7 org.apache.commons @@ -80,17 +65,20 @@ commons-pool - com.zaxxer - HikariCP-java7 + com.h2database + h2 - ch.qos.logback - logback-classic + mysql + mysql-connector-java - com.zaxxer - HikariCP-java6 - 2.3.13 + org.postgresql + postgresql + + + com.microsoft.sqlserver + mssql-jdbc From 8c594289ed128422665f4f3bb9b2ec05a3a68421 Mon Sep 17 00:00:00 2001 From: tuohai666 Date: Thu, 27 Sep 2018 19:44:30 +0800 Subject: [PATCH 06/34] remove synchronized in NewInstanceServiceLoader --- .../spi/NewInstanceServiceLoader.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) 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 f417e4bf9697c..abee185144ca6 100644 --- a/sharding-core/src/main/java/io/shardingsphere/spi/NewInstanceServiceLoader.java +++ b/sharding-core/src/main/java/io/shardingsphere/spi/NewInstanceServiceLoader.java @@ -1,3 +1,20 @@ +/* + * Copyright 2016-2018 shardingsphere.io. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *

+ */ + package io.shardingsphere.spi; import io.shardingsphere.core.exception.ShardingException; @@ -7,7 +24,6 @@ import java.util.Collection; import java.util.LinkedList; import java.util.ServiceLoader; -import java.util.concurrent.CopyOnWriteArrayList; /** * SPI service loader for new instance for every call. @@ -18,7 +34,7 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class NewInstanceServiceLoader { - private final Collection> serviceClasses = new CopyOnWriteArrayList<>(); + private final Collection> serviceClasses = new LinkedList<>(); /** * Creates a new service class loader for the given service type. @@ -28,7 +44,7 @@ public final class NewInstanceServiceLoader { * @return new service class loader */ @SuppressWarnings("unchecked") - public static synchronized NewInstanceServiceLoader load(final Class service) { + public static NewInstanceServiceLoader load(final Class service) { NewInstanceServiceLoader result = new NewInstanceServiceLoader(); for (T each : ServiceLoader.load(service)) { result.serviceClasses.add(each.getClass()); From a84ce382277c9a1ca8114a3b20dfd275a1e280c4 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 19:51:54 +0800 Subject: [PATCH 07/34] add Pattern.CASE_INSENSITIVE for ms sql --- .../datasource/dialect/SQLServerDataSourceMetaData.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java index 791faa9aeaaad..03d4d9d41a343 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java @@ -41,8 +41,8 @@ public final class SQLServerDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:(microsoft:)?sqlserver://([\\w\\-\\.]+):?([0-9]*);DatabaseName=([\\w\\-]+)"); - + private final Pattern pattern = Pattern.compile("jdbc:(microsoft:)?sqlserver://([\\w\\-\\.]+):?([0-9]*);DatabaseName=([\\w\\-]+)", Pattern.CASE_INSENSITIVE); + public SQLServerDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); if (matcher.find()) { From a943ca91945f0bfb7c14f3fe5030cc25e0581fb8 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 19:52:02 +0800 Subject: [PATCH 08/34] add Pattern.CASE_INSENSITIVE for pg --- .../datasource/dialect/PostgreSQLDataSourceMetaData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java index 066897eeeccb4..6db5429123f60 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java @@ -41,7 +41,7 @@ public final class PostgreSQLDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:postgresql://([\\w\\-\\.]+):?([0-9]*)/([\\w\\-]+)"); + private final Pattern pattern = Pattern.compile("jdbc:postgresql://([\\w\\-\\.]+):?([0-9]*)/([\\w\\-]+)", Pattern.CASE_INSENSITIVE); public PostgreSQLDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); From f20519237b5078ef1e4c5176872f079a1f2af454 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 19:52:11 +0800 Subject: [PATCH 09/34] add Pattern.CASE_INSENSITIVE for oracle --- .../metadata/datasource/dialect/OracleDataSourceMetaData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java index 544c79c36017f..6a415cc189cd0 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java @@ -41,7 +41,7 @@ public final class OracleDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:oracle:thin:@/{0,2}([\\w\\-\\.]+):?([0-9]*)[:/]([\\w\\-]+)"); + private final Pattern pattern = Pattern.compile("jdbc:oracle:thin:@/{0,2}([\\w\\-\\.]+):?([0-9]*)[:/]([\\w\\-]+)", Pattern.CASE_INSENSITIVE); public OracleDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); From c802e7a8f1697d217f53725858e0fafed81c443d Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 19:52:25 +0800 Subject: [PATCH 10/34] add Pattern.CASE_INSENSITIVE for mysql --- .../metadata/datasource/dialect/MySQLDataSourceMetaData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java index 6f30733573563..77f19f947ae5b 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java @@ -41,7 +41,7 @@ public final class MySQLDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:mysql://([\\w\\-\\.]+):?([0-9]*)/([\\w\\-]+);?\\w*"); + private final Pattern pattern = Pattern.compile("jdbc:mysql://([\\w\\-\\.]+):?([0-9]*)/([\\w\\-]+);?\\w*", Pattern.CASE_INSENSITIVE); public MySQLDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); From 415cf5c9bd519f95ee52c67e9005fe87732e7e98 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 19:52:44 +0800 Subject: [PATCH 11/34] add Pattern.CASE_INSENSITIVE for h2 --- .../core/metadata/datasource/dialect/H2DataSourceMetaData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java index 38487251c2dd5..accfa6c171453 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java @@ -40,7 +40,7 @@ public final class H2DataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:h2:(mem|~)[:/]([\\w\\-]+);?\\w*"); + private final Pattern pattern = Pattern.compile("jdbc:h2:(mem|~)[:/]([\\w\\-]+);?\\w*", Pattern.CASE_INSENSITIVE); public H2DataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); From efcfc6bea29614000ddf258b324eb83134772897 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 20:19:20 +0800 Subject: [PATCH 12/34] pattern.pattern() --- .../datasource/dialect/SQLServerDataSourceMetaData.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java index 03d4d9d41a343..8ec50d4048fd3 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java @@ -41,16 +41,16 @@ public final class SQLServerDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:(microsoft:)?sqlserver://([\\w\\-\\.]+):?([0-9]*);DatabaseName=([\\w\\-]+)", Pattern.CASE_INSENSITIVE); + private final Pattern pattern = Pattern.compile("jdbc:(microsoft:)?sqlserver://([\\w\\-\\.]+):?([0-9]*);(DatabaseName|database)=([\\w\\-]+)", Pattern.CASE_INSENSITIVE); public SQLServerDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); if (matcher.find()) { hostName = matcher.group(2); port = Strings.isNullOrEmpty(matcher.group(3)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(3)); - schemeName = matcher.group(4); + schemeName = matcher.group(5); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } From 913b5d365e01ed466e1ef61e39ed989361ff8510 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 20:20:29 +0800 Subject: [PATCH 13/34] update error info --- .../core/metadata/datasource/dialect/H2DataSourceMetaData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java index accfa6c171453..c3f0b37ad602b 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java @@ -49,7 +49,7 @@ public H2DataSourceMetaData(final String url) { port = DEFAULT_PORT; schemeName = matcher.group(2); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } From 59b9abf7f65a16942e6f3c6f7bc0801c863fa8ee Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 20:20:38 +0800 Subject: [PATCH 14/34] update error info for mysql --- .../metadata/datasource/dialect/MySQLDataSourceMetaData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java index 77f19f947ae5b..b8b0a121fb867 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java @@ -50,7 +50,7 @@ public MySQLDataSourceMetaData(final String url) { port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2)); schemeName = matcher.group(3); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } From 78c38da1f0b140608d0c74bcdf44fe4300dc5533 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 20:20:49 +0800 Subject: [PATCH 15/34] update error info for oracle --- .../metadata/datasource/dialect/OracleDataSourceMetaData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java index 6a415cc189cd0..9cbaf1518ad57 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java @@ -50,7 +50,7 @@ public OracleDataSourceMetaData(final String url) { port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2)); schemeName = matcher.group(3); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } From 78721892d6c5431317bd6f8fb1794d8bc1477bb7 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 27 Sep 2018 20:20:59 +0800 Subject: [PATCH 16/34] update error info for pg --- .../datasource/dialect/PostgreSQLDataSourceMetaData.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java index 6db5429123f60..8dd813f99fc76 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java @@ -50,7 +50,7 @@ public PostgreSQLDataSourceMetaData(final String url) { port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2)); schemeName = matcher.group(3); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } From a502022308d0bc9258c8dc0e27d28565ccc7574b Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 20:25:44 +0800 Subject: [PATCH 17/34] add lombok to public dependencies --- pom.xml | 7 +++++++ sharding-core/pom.xml | 5 ----- sharding-jdbc/pom.xml | 5 ----- sharding-jdbc/sharding-jdbc-core/pom.xml | 5 ----- .../sharding-jdbc-spring-boot-starter/pom.xml | 4 ---- .../sharding-jdbc-spring-namespace/pom.xml | 4 ---- sharding-opentracing/pom.xml | 4 ---- sharding-orchestration/pom.xml | 4 ---- sharding-proxy/pom.xml | 4 ---- sharding-sql-test/pom.xml | 4 ---- sharding-transaction/pom.xml | 4 ---- 11 files changed, 7 insertions(+), 43 deletions(-) diff --git a/pom.xml b/pom.xml index 85a236fce0f65..6940ffa29cf97 100644 --- a/pom.xml +++ b/pom.xml @@ -335,6 +335,13 @@ + + + org.projectlombok + lombok + + + diff --git a/sharding-core/pom.xml b/sharding-core/pom.xml index c7553371bc4b6..e35f51b13036b 100644 --- a/sharding-core/pom.xml +++ b/sharding-core/pom.xml @@ -34,11 +34,6 @@ slf4j-api - - org.projectlombok - lombok - - io.shardingsphere sharding-sql-test diff --git a/sharding-jdbc/pom.xml b/sharding-jdbc/pom.xml index 8f93a65d27870..92dbda117fab9 100644 --- a/sharding-jdbc/pom.xml +++ b/sharding-jdbc/pom.xml @@ -19,11 +19,6 @@ - - org.projectlombok - lombok - - junit junit diff --git a/sharding-jdbc/sharding-jdbc-core/pom.xml b/sharding-jdbc/sharding-jdbc-core/pom.xml index e9580a06f1f22..845b615263c30 100644 --- a/sharding-jdbc/sharding-jdbc-core/pom.xml +++ b/sharding-jdbc/sharding-jdbc-core/pom.xml @@ -33,11 +33,6 @@ snakeyaml - - org.projectlombok - lombok - - io.shardingsphere sharding-sql-test diff --git a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/pom.xml b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/pom.xml index 806015c25ec98..91dcc86d47ca8 100644 --- a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/pom.xml +++ b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/pom.xml @@ -15,9 +15,5 @@ org.springframework.boot spring-boot-starter-test - - org.projectlombok - lombok - diff --git a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-namespace/pom.xml b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-namespace/pom.xml index 9fc8e4d9a24cc..c0f4abe126d4a 100644 --- a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-namespace/pom.xml +++ b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-namespace/pom.xml @@ -15,9 +15,5 @@ org.springframework spring-test - - org.projectlombok - lombok - diff --git a/sharding-opentracing/pom.xml b/sharding-opentracing/pom.xml index c1f1c3dec0933..e0f43826e1d34 100644 --- a/sharding-opentracing/pom.xml +++ b/sharding-opentracing/pom.xml @@ -18,10 +18,6 @@ ${project.version} - - org.projectlombok - lombok - com.google.guava guava diff --git a/sharding-orchestration/pom.xml b/sharding-orchestration/pom.xml index cbb68aa1fe95e..e8a50a4372fbb 100644 --- a/sharding-orchestration/pom.xml +++ b/sharding-orchestration/pom.xml @@ -31,10 +31,6 @@ ${project.version} - - org.projectlombok - lombok - com.google.guava guava diff --git a/sharding-proxy/pom.xml b/sharding-proxy/pom.xml index 8a11616897e93..fa21aa89274d6 100644 --- a/sharding-proxy/pom.xml +++ b/sharding-proxy/pom.xml @@ -59,10 +59,6 @@ mysql-connector-java runtime - - org.projectlombok - lombok - junit junit diff --git a/sharding-sql-test/pom.xml b/sharding-sql-test/pom.xml index 1771450aa8ef1..90658df50c60f 100644 --- a/sharding-sql-test/pom.xml +++ b/sharding-sql-test/pom.xml @@ -12,10 +12,6 @@ ${project.artifactId} - - org.projectlombok - lombok - com.google.guava guava diff --git a/sharding-transaction/pom.xml b/sharding-transaction/pom.xml index 6437ad3ece908..161054888bb21 100644 --- a/sharding-transaction/pom.xml +++ b/sharding-transaction/pom.xml @@ -43,10 +43,6 @@ slf4j-api - - org.projectlombok - lombok - ch.qos.logback logback-classic From faed55a14d618053314ec8673fe812f5c49abe57 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 20:33:37 +0800 Subject: [PATCH 18/34] add guava to public dependencies --- pom.xml | 5 +++++ sharding-core/pom.xml | 4 ---- sharding-jdbc/sharding-jdbc-core/pom.xml | 4 ---- sharding-opentracing/pom.xml | 4 ---- sharding-orchestration/pom.xml | 4 ---- sharding-proxy/pom.xml | 5 +---- sharding-sql-test/pom.xml | 5 ----- sharding-transaction/pom.xml | 4 ---- 8 files changed, 6 insertions(+), 29 deletions(-) diff --git a/pom.xml b/pom.xml index 6940ffa29cf97..0b80137b88c58 100644 --- a/pom.xml +++ b/pom.xml @@ -336,6 +336,11 @@ + + com.google.guava + guava + + org.projectlombok lombok diff --git a/sharding-core/pom.xml b/sharding-core/pom.xml index e35f51b13036b..333ea7c9b7224 100644 --- a/sharding-core/pom.xml +++ b/sharding-core/pom.xml @@ -12,10 +12,6 @@ ${project.artifactId} - - com.google.guava - guava - org.apache.commons commons-lang3 diff --git a/sharding-jdbc/sharding-jdbc-core/pom.xml b/sharding-jdbc/sharding-jdbc-core/pom.xml index 845b615263c30..adb94aac8d404 100644 --- a/sharding-jdbc/sharding-jdbc-core/pom.xml +++ b/sharding-jdbc/sharding-jdbc-core/pom.xml @@ -15,10 +15,6 @@ ${project.version} - - com.google.guava - guava - org.apache.commons commons-lang3 diff --git a/sharding-opentracing/pom.xml b/sharding-opentracing/pom.xml index e0f43826e1d34..51d6ba7619427 100644 --- a/sharding-opentracing/pom.xml +++ b/sharding-opentracing/pom.xml @@ -18,10 +18,6 @@ ${project.version} - - com.google.guava - guava - io.opentracing opentracing-util diff --git a/sharding-orchestration/pom.xml b/sharding-orchestration/pom.xml index e8a50a4372fbb..8faff6cefb9f8 100644 --- a/sharding-orchestration/pom.xml +++ b/sharding-orchestration/pom.xml @@ -31,10 +31,6 @@ ${project.version} - - com.google.guava - guava - org.apache.curator curator-framework diff --git a/sharding-proxy/pom.xml b/sharding-proxy/pom.xml index fa21aa89274d6..a373ea5752d54 100644 --- a/sharding-proxy/pom.xml +++ b/sharding-proxy/pom.xml @@ -32,10 +32,7 @@ sharding-opentracing ${project.version} - - com.google.guava - guava - + io.netty netty-all diff --git a/sharding-sql-test/pom.xml b/sharding-sql-test/pom.xml index 90658df50c60f..f895e7bd763ce 100644 --- a/sharding-sql-test/pom.xml +++ b/sharding-sql-test/pom.xml @@ -12,11 +12,6 @@ ${project.artifactId} - - com.google.guava - guava - - junit junit diff --git a/sharding-transaction/pom.xml b/sharding-transaction/pom.xml index 161054888bb21..a588c79fbbc2c 100644 --- a/sharding-transaction/pom.xml +++ b/sharding-transaction/pom.xml @@ -18,10 +18,6 @@ ${project.parent.version} - - com.google.guava - guava - javax.transaction jta From 9f06c3321dfa9c68a8daa8383ef9c3909cda4388 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 21:01:44 +0800 Subject: [PATCH 19/34] add junit, hamcrest and mockito to public dependencies --- pom.xml | 29 +++++++++++++++++----- sharding-core/pom.xml | 8 ------ sharding-jdbc/pom.xml | 8 ------ sharding-jdbc/sharding-jdbc-core/pom.xml | 9 +------ sharding-jdbc/sharding-jdbc-spring/pom.xml | 9 +------ sharding-opentracing/pom.xml | 8 ------ sharding-orchestration/pom.xml | 8 ------ sharding-proxy/pom.xml | 12 --------- sharding-sql-test/pom.xml | 7 ------ sharding-transaction/pom.xml | 9 ------- 10 files changed, 25 insertions(+), 82 deletions(-) diff --git a/pom.xml b/pom.xml index 0b80137b88c58..9397aaaa7b6ef 100644 --- a/pom.xml +++ b/pom.xml @@ -224,6 +224,12 @@ ${junit.version} test + + org.hamcrest + hamcrest-library + ${hamcrest.version} + test + org.mockito mockito-core @@ -290,12 +296,6 @@ ${hikari-cp.version} test - - org.hamcrest - hamcrest-library - ${hamcrest.version} - test - org.springframework spring-test @@ -345,6 +345,23 @@ org.projectlombok lombok + + + junit + junit + + + org.hamcrest + hamcrest-library + + + org.mockito + mockito-core + + + org.mockito + mockito-inline + diff --git a/sharding-core/pom.xml b/sharding-core/pom.xml index 333ea7c9b7224..015daa87ce4ca 100644 --- a/sharding-core/pom.xml +++ b/sharding-core/pom.xml @@ -37,14 +37,6 @@ test - - junit - junit - - - org.mockito - mockito-core - com.h2database h2 diff --git a/sharding-jdbc/pom.xml b/sharding-jdbc/pom.xml index 92dbda117fab9..ec98171c6655a 100644 --- a/sharding-jdbc/pom.xml +++ b/sharding-jdbc/pom.xml @@ -19,14 +19,6 @@ - - junit - junit - - - org.mockito - mockito-core - com.zaxxer HikariCP-java7 diff --git a/sharding-jdbc/sharding-jdbc-core/pom.xml b/sharding-jdbc/sharding-jdbc-core/pom.xml index adb94aac8d404..0f27498a3f5dd 100644 --- a/sharding-jdbc/sharding-jdbc-core/pom.xml +++ b/sharding-jdbc/sharding-jdbc-core/pom.xml @@ -35,14 +35,7 @@ ${project.version} test - - junit - junit - - - org.mockito - mockito-core - + com.zaxxer HikariCP-java7 diff --git a/sharding-jdbc/sharding-jdbc-spring/pom.xml b/sharding-jdbc/sharding-jdbc-spring/pom.xml index 7ab4fb9013087..b94ca2e5e024a 100644 --- a/sharding-jdbc/sharding-jdbc-spring/pom.xml +++ b/sharding-jdbc/sharding-jdbc-spring/pom.xml @@ -22,14 +22,7 @@ sharding-jdbc-core ${project.version} - - junit - junit - - - org.hamcrest - hamcrest-library - + org.apache.commons commons-dbcp2 diff --git a/sharding-opentracing/pom.xml b/sharding-opentracing/pom.xml index 51d6ba7619427..e683507063bad 100644 --- a/sharding-opentracing/pom.xml +++ b/sharding-opentracing/pom.xml @@ -27,14 +27,6 @@ opentracing-mock - - junit - junit - - - org.mockito - mockito-core - ch.qos.logback logback-classic diff --git a/sharding-orchestration/pom.xml b/sharding-orchestration/pom.xml index 8faff6cefb9f8..44f39c1a8592b 100644 --- a/sharding-orchestration/pom.xml +++ b/sharding-orchestration/pom.xml @@ -60,14 +60,6 @@ guava-retrying - - junit - junit - - - org.mockito - mockito-core - com.h2database h2 diff --git a/sharding-proxy/pom.xml b/sharding-proxy/pom.xml index a373ea5752d54..6dd9fd15adc11 100644 --- a/sharding-proxy/pom.xml +++ b/sharding-proxy/pom.xml @@ -56,18 +56,6 @@ mysql-connector-java runtime - - junit - junit - - - org.hamcrest - hamcrest-library - - - org.mockito - mockito-core - commons-codec commons-codec diff --git a/sharding-sql-test/pom.xml b/sharding-sql-test/pom.xml index f895e7bd763ce..fad09f261cd5e 100644 --- a/sharding-sql-test/pom.xml +++ b/sharding-sql-test/pom.xml @@ -10,11 +10,4 @@ sharding-sql-test ${project.artifactId} - - - - junit - junit - - diff --git a/sharding-transaction/pom.xml b/sharding-transaction/pom.xml index a588c79fbbc2c..93b0f57e57087 100644 --- a/sharding-transaction/pom.xml +++ b/sharding-transaction/pom.xml @@ -43,15 +43,6 @@ ch.qos.logback logback-classic - - - junit - junit - - - org.mockito - mockito-core - mysql mysql-connector-java From b61261fd56465d39272522a3155203bbf7522218 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 21:16:17 +0800 Subject: [PATCH 20/34] remove commons-lang3 dependency for sharding-core module --- sharding-core/pom.xml | 4 --- .../parsing/parser/context/OrderItem.java | 8 ++---- .../parsing/lexer/analyzer/TokenizerTest.java | 26 +++++++++++-------- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/sharding-core/pom.xml b/sharding-core/pom.xml index 015daa87ce4ca..1d4825411b8f8 100644 --- a/sharding-core/pom.xml +++ b/sharding-core/pom.xml @@ -12,10 +12,6 @@ ${project.artifactId} - - org.apache.commons - commons-lang3 - org.codehaus.groovy groovy diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/context/OrderItem.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/context/OrderItem.java index 6ea581743588c..2b027c39ccaa4 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/context/OrderItem.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/context/OrderItem.java @@ -19,10 +19,10 @@ import com.google.common.base.Optional; import io.shardingsphere.core.constant.OrderDirection; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import org.apache.commons.lang3.builder.HashCodeBuilder; /** * Order item. @@ -31,6 +31,7 @@ */ @Getter @Setter +@EqualsAndHashCode @ToString public final class OrderItem { @@ -132,9 +133,4 @@ private boolean qualifiedNameEquals(final OrderItem orderItem) { private boolean indexEquals(final OrderItem orderItem) { return -1 != index && index == orderItem.getIndex(); } - - @Override - public int hashCode() { - return HashCodeBuilder.reflectionHashCode(this); - } } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/lexer/analyzer/TokenizerTest.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/lexer/analyzer/TokenizerTest.java index 96a81a528e95a..389c5d64e55a6 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/lexer/analyzer/TokenizerTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/lexer/analyzer/TokenizerTest.java @@ -22,12 +22,10 @@ import io.shardingsphere.core.parsing.lexer.token.Symbol; import io.shardingsphere.core.parsing.lexer.token.Token; import io.shardingsphere.core.parsing.lexer.token.TokenType; -import org.apache.commons.lang3.builder.EqualsBuilder; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; public final class TokenizerTest { @@ -119,7 +117,7 @@ public void assertScanVariable() { private void assertScanVariable(final String sql, final String literals) { String formatSql = String.format(sql, literals); Tokenizer tokenizer = new Tokenizer(formatSql, dictionary, formatSql.indexOf("@")); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanVariable(), new Token(Literals.VARIABLE, literals, formatSql.indexOf("WHERE") - 1))); + assertToken(tokenizer.scanVariable(), new Token(Literals.VARIABLE, literals, formatSql.indexOf("WHERE") - 1)); } @Test @@ -148,30 +146,36 @@ public void assertScanNumber() { private void assertScanNumber(final String sql, final String literals, final TokenType type) { String formatSql = String.format(sql, literals); Tokenizer tokenizer = new Tokenizer(formatSql, dictionary, sql.indexOf("=") + 1); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanNumber(), new Token(type, literals, formatSql.length()))); + assertToken(tokenizer.scanNumber(), new Token(type, literals, formatSql.length())); } private void assertScanHexDecimal(final String sql, final String literals, final TokenType type) { String formatSql = String.format(sql, literals); Tokenizer tokenizer = new Tokenizer(formatSql, dictionary, sql.indexOf("=") + 1); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanHexDecimal(), new Token(type, literals, formatSql.length()))); + assertToken(tokenizer.scanHexDecimal(), new Token(type, literals, formatSql.length())); } @Test public void assertScanNChars() { String sql = "SELECT * FROM ORDER, XX_TABLE AS `table` WHERE YY=N'xx' And group =-1 GROUP BY YY"; Tokenizer tokenizer = new Tokenizer(sql, dictionary, sql.indexOf("ORDER")); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanIdentifier(), new Token(Literals.IDENTIFIER, "ORDER", sql.indexOf(",")))); + assertToken(tokenizer.scanIdentifier(), new Token(Literals.IDENTIFIER, "ORDER", sql.indexOf(","))); tokenizer = new Tokenizer(sql, dictionary, sql.indexOf("GROUP")); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanIdentifier(), new Token(DefaultKeyword.GROUP, "GROUP", sql.indexOf("BY") - 1))); + assertToken(tokenizer.scanIdentifier(), new Token(DefaultKeyword.GROUP, "GROUP", sql.indexOf("BY") - 1)); tokenizer = new Tokenizer(sql, dictionary, sql.indexOf("`")); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanIdentifier(), new Token(Literals.IDENTIFIER, "`table`", sql.indexOf("WHERE") - 1))); + assertToken(tokenizer.scanIdentifier(), new Token(Literals.IDENTIFIER, "`table`", sql.indexOf("WHERE") - 1)); tokenizer = new Tokenizer(sql, dictionary, sql.indexOf("YY")); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanIdentifier(), new Token(Literals.IDENTIFIER, "YY", sql.indexOf("=")))); + assertToken(tokenizer.scanIdentifier(), new Token(Literals.IDENTIFIER, "YY", sql.indexOf("="))); tokenizer = new Tokenizer(sql, dictionary, sql.indexOf("=-")); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanSymbol(), new Token(Symbol.EQ, "=", sql.indexOf("=-") + 1))); + assertToken(tokenizer.scanSymbol(), new Token(Symbol.EQ, "=", sql.indexOf("=-") + 1)); tokenizer = new Tokenizer(sql, dictionary, sql.indexOf("'")); - assertTrue(EqualsBuilder.reflectionEquals(tokenizer.scanChars(), new Token(Literals.CHARS, "xx", sql.indexOf("And") - 1))); + assertToken(tokenizer.scanChars(), new Token(Literals.CHARS, "xx", sql.indexOf("And") - 1)); + } + + private void assertToken(final Token actual, final Token expected) { + assertThat(actual.getType(), is(expected.getType())); + assertThat(actual.getLiterals(), is(expected.getLiterals())); + assertThat(actual.getEndPosition(), is(expected.getEndPosition())); } @Test(expected = UnterminatedCharException.class) From c9b0f2e70e84b58ef32959aa0ad248eb3ce8162a Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 21:40:37 +0800 Subject: [PATCH 21/34] remove commons-lang3 dependency for sharding-core module --- pom.xml | 30 ++++++++----------- sharding-jdbc/sharding-jdbc-core/pom.xml | 4 --- .../env/schema/SchemaEnvironmentManager.java | 5 ++-- ...OrchestrationMasterSlaveNamespaceTest.java | 11 ++++--- 4 files changed, 19 insertions(+), 31 deletions(-) diff --git a/pom.xml b/pom.xml index 9397aaaa7b6ef..8b897295e0468 100644 --- a/pom.xml +++ b/pom.xml @@ -27,7 +27,6 @@ 18.0 2.0.0 - 3.6 2.4.5 1.16 4.1.16.Final @@ -43,16 +42,16 @@ 1.16.4 [4.3.6.RELEASE,5.0.0.M1) [1.5.0.RELEASE,2.0.0.M1) - 1.6 - 2.2.0 - 5.1.42 + 4.12 + 1.3 + 2.7.21 1.4.196 + 5.1.42 9.4.1212 6.1.7.jre7-preview + 2.2.0 + 1.6 2.4.11 - 4.12 - 1.3 - 2.7.21 3.3 3.1.0 @@ -95,11 +94,6 @@ guava-retrying ${guava-retrying.version} - - org.apache.commons - commons-lang3 - ${common-lang3} - org.codehaus.groovy groovy @@ -248,6 +242,12 @@ ${mockito.version} test + + com.zaxxer + HikariCP-java7 + ${hikari-cp.version} + test + commons-pool commons-pool @@ -290,12 +290,6 @@ ${mssql.version} test - - com.zaxxer - HikariCP-java7 - ${hikari-cp.version} - test - org.springframework spring-test diff --git a/sharding-jdbc/sharding-jdbc-core/pom.xml b/sharding-jdbc/sharding-jdbc-core/pom.xml index 0f27498a3f5dd..c6a025179a4c5 100644 --- a/sharding-jdbc/sharding-jdbc-core/pom.xml +++ b/sharding-jdbc/sharding-jdbc-core/pom.xml @@ -15,10 +15,6 @@ ${project.version} - - org.apache.commons - commons-lang3 - org.codehaus.groovy groovy diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/dbtest/env/schema/SchemaEnvironmentManager.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/dbtest/env/schema/SchemaEnvironmentManager.java index 450e9731cb6bc..78de4b3fbec25 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/dbtest/env/schema/SchemaEnvironmentManager.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/dbtest/env/schema/SchemaEnvironmentManager.java @@ -24,7 +24,6 @@ import io.shardingsphere.dbtest.env.datasource.DataSourceUtil; import lombok.AccessLevel; import lombok.NoArgsConstructor; -import org.apache.commons.lang3.StringUtils; import org.h2.tools.RunScript; import javax.sql.DataSource; @@ -150,7 +149,7 @@ private static void createTable(final SchemaEnvironment databaseEnvironmentSchem for (String each : databaseEnvironmentSchema.getDatabases()) { DataSource dataSource = DataSourceUtil.createDataSource(databaseType, each); try (Connection connection = dataSource.getConnection(); - StringReader stringReader = new StringReader(StringUtils.join(databaseEnvironmentSchema.getTableCreateSQLs(), ";\n"))) { + StringReader stringReader = new StringReader(Joiner.on(";\n").join(databaseEnvironmentSchema.getTableCreateSQLs()))) { RunScript.execute(connection, stringReader); } } @@ -174,7 +173,7 @@ private static void dropTable(final SchemaEnvironment databaseEnvironmentSchema, for (String each : databaseEnvironmentSchema.getDatabases()) { DataSource dataSource = DataSourceUtil.createDataSource(databaseType, each); try (Connection connection = dataSource.getConnection(); - StringReader stringReader = new StringReader(StringUtils.join(databaseEnvironmentSchema.getTableDropSQLs(), ";\n"))) { + StringReader stringReader = new StringReader(Joiner.on(";\n").join(databaseEnvironmentSchema.getTableDropSQLs()))) { RunScript.execute(connection, stringReader); } catch (final SQLException ex) { // TODO table maybe not exist diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/orchestration/spring/OrchestrationMasterSlaveNamespaceTest.java b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/orchestration/spring/OrchestrationMasterSlaveNamespaceTest.java index 1df57fed57d80..f8c4c7d52f143 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/orchestration/spring/OrchestrationMasterSlaveNamespaceTest.java +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingsphere/shardingjdbc/orchestration/spring/OrchestrationMasterSlaveNamespaceTest.java @@ -29,7 +29,6 @@ import io.shardingsphere.shardingjdbc.orchestration.spring.datasource.OrchestrationSpringMasterSlaveDataSource; import io.shardingsphere.shardingjdbc.orchestration.spring.util.EmbedTestingServer; import io.shardingsphere.shardingjdbc.orchestration.spring.util.FieldValueUtil; -import org.apache.commons.lang3.builder.EqualsBuilder; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; @@ -74,20 +73,20 @@ public void assertTypeMasterSlaveDataSource() { @Test public void assertRefMasterSlaveDataSource() { - MasterSlaveLoadBalanceAlgorithm randomStrategy = this.applicationContext.getBean("randomStrategy", MasterSlaveLoadBalanceAlgorithm.class); + MasterSlaveLoadBalanceAlgorithm randomStrategy = applicationContext.getBean("randomStrategy", MasterSlaveLoadBalanceAlgorithm.class); MasterSlaveRule masterSlaveRule = getMasterSlaveRule("refMasterSlaveDataSourceOrchestration"); - assertTrue(EqualsBuilder.reflectionEquals(masterSlaveRule.getLoadBalanceAlgorithm(), randomStrategy)); + assertThat(masterSlaveRule.getLoadBalanceAlgorithm(), is(randomStrategy)); } private MasterSlaveRule getMasterSlaveRule(final String masterSlaveDataSourceName) { - OrchestrationMasterSlaveDataSource masterSlaveDataSource = this.applicationContext.getBean(masterSlaveDataSourceName, OrchestrationMasterSlaveDataSource.class); + OrchestrationMasterSlaveDataSource masterSlaveDataSource = applicationContext.getBean(masterSlaveDataSourceName, OrchestrationMasterSlaveDataSource.class); MasterSlaveDataSource dataSource = (MasterSlaveDataSource) FieldValueUtil.getFieldValue(masterSlaveDataSource, "dataSource", true); return dataSource.getMasterSlaveRule(); } @Test public void assertConfigMapDataSource() { - Object masterSlaveDataSource = this.applicationContext.getBean("configMapDataSourceOrchestration"); + Object masterSlaveDataSource = applicationContext.getBean("configMapDataSourceOrchestration"); Map configMap = new HashMap<>(); configMap.put("key1", "value1"); assertThat(ConfigMapContext.getInstance().getMasterSlaveConfig(), is(configMap)); @@ -101,7 +100,7 @@ public void assertProperties() { } private ShardingProperties getShardingProperties(final String masterSlaveDataSourceName) { - OrchestrationSpringMasterSlaveDataSource masterSlaveDataSource = this.applicationContext.getBean(masterSlaveDataSourceName, OrchestrationSpringMasterSlaveDataSource.class); + OrchestrationSpringMasterSlaveDataSource masterSlaveDataSource = applicationContext.getBean(masterSlaveDataSourceName, OrchestrationSpringMasterSlaveDataSource.class); MasterSlaveDataSource dataSource = (MasterSlaveDataSource) FieldValueUtil.getFieldValue(masterSlaveDataSource, "dataSource", true); return dataSource.getShardingProperties(); } From 332e6246900624c76fb2034ab124d8464e005d89 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 22:08:20 +0800 Subject: [PATCH 22/34] add slf4j and logback to public dependencies --- pom.xml | 87 ++++++++++++------- sharding-core/pom.xml | 8 -- .../pom.xml | 15 ++-- sharding-jdbc/sharding-jdbc-spring/pom.xml | 4 - sharding-opentracing/pom.xml | 5 -- sharding-orchestration/pom.xml | 4 - sharding-proxy/pom.xml | 13 ++- sharding-transaction/pom.xml | 8 -- 8 files changed, 68 insertions(+), 76 deletions(-) diff --git a/pom.xml b/pom.xml index 8b897295e0468..5427f51bd4897 100644 --- a/pom.xml +++ b/pom.xml @@ -26,32 +26,41 @@ zh_CN 18.0 - 2.0.0 + 1.7.7 + 2.4.5 1.16 + 4.1.16.Final 1.10 + 1.1 4.0.4 + + 2.10.0 1.7.0 3.4.0 - 2.10.0 + 2.0.0 + 0.30.0 - 1.7.7 - 1.2.0 + 1.16.4 + [4.3.6.RELEASE,5.0.0.M1) [1.5.0.RELEASE,2.0.0.M1) + 4.12 1.3 2.7.21 + 1.2.0 + 1.4.196 5.1.42 9.4.1212 6.1.7.jre7-preview + 2.4.11 2.2.0 1.6 - 2.4.11 3.3 3.1.0 @@ -90,10 +99,16 @@ ${guava.version} - com.github.rholder - guava-retrying - ${guava-retrying.version} + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + org.codehaus.groovy groovy @@ -105,6 +120,7 @@ snakeyaml ${snakeyaml.version} + io.netty netty-all @@ -115,16 +131,7 @@ commons-codec ${commons-codec.version} - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - jcl-over-slf4j - ${slf4j.version} - + javax.transaction jta @@ -145,6 +152,7 @@ transactions-jdbc ${atomikos.version} + org.apache.curator curator-framework @@ -181,6 +189,12 @@ grpc-stub ${grpc.version} + + com.github.rholder + guava-retrying + ${guava-retrying.version} + + io.opentracing opentracing-util @@ -242,6 +256,19 @@ ${mockito.version} test + + ch.qos.logback + logback-classic + ${logback.version} + + + org.slf4j + slf4j-api + + + test + + com.zaxxer HikariCP-java7 @@ -302,18 +329,6 @@ ${curator.version} test - - ch.qos.logback - logback-classic - ${logback.version} - - - org.slf4j - slf4j-api - - - test - org.springframework.boot spring-boot-starter-test @@ -334,6 +349,14 @@ com.google.guava guava + + org.slf4j + slf4j-api + + + org.slf4j + jcl-over-slf4j + org.projectlombok @@ -356,6 +379,10 @@ org.mockito mockito-inline + + ch.qos.logback + logback-classic + diff --git a/sharding-core/pom.xml b/sharding-core/pom.xml index 1d4825411b8f8..5cfc297cec432 100644 --- a/sharding-core/pom.xml +++ b/sharding-core/pom.xml @@ -21,10 +21,6 @@ org.yaml snakeyaml - - org.slf4j - slf4j-api - io.shardingsphere @@ -41,9 +37,5 @@ com.zaxxer HikariCP-java7 - - ch.qos.logback - logback-classic - diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml index bcbb0fb5b3b2c..1d0678c06ccab 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml @@ -8,6 +8,12 @@ sharding-jdbc-orchestration-spring-namespace + + io.shardingsphere + sharding-jdbc-spring-namespace + ${project.version} + + org.springframework spring-context-support @@ -16,15 +22,6 @@ org.springframework spring-test - - org.slf4j - jcl-over-slf4j - - - io.shardingsphere - sharding-jdbc-spring-namespace - ${project.version} - diff --git a/sharding-jdbc/sharding-jdbc-spring/pom.xml b/sharding-jdbc/sharding-jdbc-spring/pom.xml index b94ca2e5e024a..3fe7ac0ae1065 100644 --- a/sharding-jdbc/sharding-jdbc-spring/pom.xml +++ b/sharding-jdbc/sharding-jdbc-spring/pom.xml @@ -39,10 +39,6 @@ com.h2database h2 - - ch.qos.logback - logback-classic - org.springframework.boot spring-boot-configuration-processor diff --git a/sharding-opentracing/pom.xml b/sharding-opentracing/pom.xml index e683507063bad..3360f4ee3c06a 100644 --- a/sharding-opentracing/pom.xml +++ b/sharding-opentracing/pom.xml @@ -26,10 +26,5 @@ io.opentracing opentracing-mock - - - ch.qos.logback - logback-classic - diff --git a/sharding-orchestration/pom.xml b/sharding-orchestration/pom.xml index 44f39c1a8592b..eb7fdd3946f53 100644 --- a/sharding-orchestration/pom.xml +++ b/sharding-orchestration/pom.xml @@ -80,10 +80,6 @@ mysql mysql-connector-java - - ch.qos.logback - logback-classic - diff --git a/sharding-proxy/pom.xml b/sharding-proxy/pom.xml index 6dd9fd15adc11..71338ec65e0b8 100644 --- a/sharding-proxy/pom.xml +++ b/sharding-proxy/pom.xml @@ -37,15 +37,16 @@ io.netty netty-all + + commons-codec + commons-codec + com.zaxxer HikariCP-java7 compile - - org.slf4j - slf4j-api - + ch.qos.logback logback-classic @@ -56,10 +57,6 @@ mysql-connector-java runtime - - commons-codec - commons-codec - diff --git a/sharding-transaction/pom.xml b/sharding-transaction/pom.xml index 93b0f57e57087..2a4fc1a1aebc6 100644 --- a/sharding-transaction/pom.xml +++ b/sharding-transaction/pom.xml @@ -34,15 +34,7 @@ com.atomikos transactions-jdbc - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - mysql mysql-connector-java From 22df5a68e3c85c09dccbfbb628a2efbfa56a3a50 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 22:28:01 +0800 Subject: [PATCH 23/34] refine sharding-orchestration pom --- sharding-orchestration/pom.xml | 67 +------------------ .../sharding-orchestration-core/pom.xml | 6 ++ .../sharding-orchestration-reg/pom.xml | 36 ++++++++++ sharding-proxy/pom.xml | 4 +- 4 files changed, 45 insertions(+), 68 deletions(-) diff --git a/sharding-orchestration/pom.xml b/sharding-orchestration/pom.xml index eb7fdd3946f53..dd27a4398f4fd 100644 --- a/sharding-orchestration/pom.xml +++ b/sharding-orchestration/pom.xml @@ -11,76 +11,11 @@ sharding-orchestration pom ${project.artifactId} - + sharding-orchestration-core sharding-orchestration-reg - - - - io.shardingsphere - sharding-core - ${project.version} - - - - - io.shardingsphere - sharding-jdbc-core - ${project.version} - - - - org.apache.curator - curator-framework - - - org.apache.curator - curator-client - - - org.apache.curator - curator-recipes - - - io.grpc - grpc-netty - - - io.grpc - grpc-protobuf - - - io.grpc - grpc-stub - - - com.github.rholder - guava-retrying - - - - com.h2database - h2 - - - org.apache.commons - commons-dbcp2 - - - commons-pool - commons-pool - - - org.apache.curator - curator-test - - - mysql - mysql-connector-java - - diff --git a/sharding-orchestration/sharding-orchestration-core/pom.xml b/sharding-orchestration/sharding-orchestration-core/pom.xml index cdcf4b92e7da9..ad14180a1c1a6 100644 --- a/sharding-orchestration/sharding-orchestration-core/pom.xml +++ b/sharding-orchestration/sharding-orchestration-core/pom.xml @@ -16,6 +16,12 @@ sharding-orchestration-reg ${project.version} + + io.shardingsphere + sharding-core + ${project.version} + + io.shardingsphere sharding-jdbc-core diff --git a/sharding-orchestration/sharding-orchestration-reg/pom.xml b/sharding-orchestration/sharding-orchestration-reg/pom.xml index 3c5fc30c2dac8..42f901ce4c31d 100644 --- a/sharding-orchestration/sharding-orchestration-reg/pom.xml +++ b/sharding-orchestration/sharding-orchestration-reg/pom.xml @@ -9,5 +9,41 @@ 4.0.0 sharding-orchestration-reg + + + + org.apache.curator + curator-framework + + + org.apache.curator + curator-client + + + org.apache.curator + curator-recipes + + + io.grpc + grpc-netty + + + io.grpc + grpc-protobuf + + + io.grpc + grpc-stub + + + com.github.rholder + guava-retrying + + + + org.apache.curator + curator-test + + diff --git a/sharding-proxy/pom.xml b/sharding-proxy/pom.xml index 71338ec65e0b8..1382c466b13cf 100644 --- a/sharding-proxy/pom.xml +++ b/sharding-proxy/pom.xml @@ -19,12 +19,12 @@ io.shardingsphere - sharding-orchestration-core + sharding-transaction ${project.version} io.shardingsphere - sharding-transaction + sharding-orchestration-core ${project.version} From b2bc6e237434f5774ac6be330bc8d29cc7b81cd0 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 22:51:46 +0800 Subject: [PATCH 24/34] refine sharding-jdbc pom --- sharding-jdbc/pom.xml | 35 ----------------- sharding-jdbc/sharding-jdbc-core/pom.xml | 10 ----- .../pom.xml | 39 ++++++++++++++++--- .../pom.xml | 4 +- .../pom.xml | 4 +- .../sharding-jdbc-orchestration/pom.xml | 38 ++++++++++++++++++ 6 files changed, 74 insertions(+), 56 deletions(-) diff --git a/sharding-jdbc/pom.xml b/sharding-jdbc/pom.xml index ec98171c6655a..f24c03a89d544 100644 --- a/sharding-jdbc/pom.xml +++ b/sharding-jdbc/pom.xml @@ -17,39 +17,4 @@ sharding-jdbc-orchestration sharding-jdbc-orchestration-spring - - - - com.zaxxer - HikariCP-java7 - - - org.apache.commons - commons-dbcp2 - - - commons-pool - commons-pool - - - com.h2database - h2 - - - mysql - mysql-connector-java - - - org.postgresql - postgresql - - - com.microsoft.sqlserver - mssql-jdbc - - - org.apache.curator - curator-test - - diff --git a/sharding-jdbc/sharding-jdbc-core/pom.xml b/sharding-jdbc/sharding-jdbc-core/pom.xml index c6a025179a4c5..7a615aeec702c 100644 --- a/sharding-jdbc/sharding-jdbc-core/pom.xml +++ b/sharding-jdbc/sharding-jdbc-core/pom.xml @@ -15,16 +15,6 @@ ${project.version} - - org.codehaus.groovy - groovy - indy - - - org.yaml - snakeyaml - - io.shardingsphere sharding-sql-test diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration-spring/pom.xml index 0f26915c2096e..337964e38c580 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/pom.xml @@ -17,21 +17,50 @@ - - io.shardingsphere - sharding-orchestration-core - ${project.version} - io.shardingsphere sharding-jdbc-orchestration ${project.version} + org.springframework.boot spring-boot-configuration-processor true + + + org.apache.curator + curator-test + + + com.zaxxer + HikariCP-java7 + + + org.apache.commons + commons-dbcp2 + + + commons-pool + commons-pool + + + com.h2database + h2 + + + mysql + mysql-connector-java + + + org.postgresql + postgresql + + + com.microsoft.sqlserver + mssql-jdbc + diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/pom.xml index 256450d391a1c..74d66bea994b2 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/pom.xml @@ -6,7 +6,7 @@ 3.0.0.M4-SNAPSHOT sharding-jdbc-orchestration-spring-boot-starter - + org.springframework.boot @@ -18,5 +18,3 @@ - - diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml index 1d0678c06ccab..dbcae08bcb546 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml @@ -6,7 +6,7 @@ 3.0.0.M4-SNAPSHOT sharding-jdbc-orchestration-spring-namespace - + io.shardingsphere @@ -24,5 +24,3 @@ - - diff --git a/sharding-jdbc/sharding-jdbc-orchestration/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration/pom.xml index c2c46e3535499..9ac8680990d62 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration/pom.xml @@ -11,10 +11,48 @@ sharding-jdbc-orchestration + + io.shardingsphere + sharding-jdbc-core + ${project.version} + io.shardingsphere sharding-orchestration-core ${project.version} + + + org.apache.curator + curator-test + + + com.zaxxer + HikariCP-java7 + + + org.apache.commons + commons-dbcp2 + + + commons-pool + commons-pool + + + com.h2database + h2 + + + mysql + mysql-connector-java + + + org.postgresql + postgresql + + + com.microsoft.sqlserver + mssql-jdbc + From af646481cf5bcfec4c67fc89518236242dc48206 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 23:04:05 +0800 Subject: [PATCH 25/34] refine sharding-jdbc-spring and sharding-jdbc-orchestration-spring pom --- .../pom.xml | 29 ------------------- .../pom.xml | 5 ++++ sharding-jdbc/sharding-jdbc-spring/pom.xml | 16 ---------- .../sharding-jdbc-spring-boot-starter/pom.xml | 5 ++++ 4 files changed, 10 insertions(+), 45 deletions(-) diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration-spring/pom.xml index 337964e38c580..120357fa945bc 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/pom.xml @@ -23,12 +23,6 @@ ${project.version} - - org.springframework.boot - spring-boot-configuration-processor - true - - org.apache.curator curator-test @@ -49,28 +43,5 @@ com.h2database h2 - - mysql - mysql-connector-java - - - org.postgresql - postgresql - - - com.microsoft.sqlserver - mssql-jdbc - - - - - io.shardingsphere - sharding-sphere - ${project.parent.version} - pom - import - - - diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/pom.xml index 74d66bea994b2..288d46f8ae3ac 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/pom.xml @@ -12,6 +12,11 @@ org.springframework.boot spring-boot-starter + + org.springframework.boot + spring-boot-configuration-processor + true + org.springframework.boot spring-boot-starter-test diff --git a/sharding-jdbc/sharding-jdbc-spring/pom.xml b/sharding-jdbc/sharding-jdbc-spring/pom.xml index 3fe7ac0ae1065..55866fc8e49d2 100644 --- a/sharding-jdbc/sharding-jdbc-spring/pom.xml +++ b/sharding-jdbc/sharding-jdbc-spring/pom.xml @@ -39,21 +39,5 @@ com.h2database h2 - - org.springframework.boot - spring-boot-configuration-processor - true - - - - - io.shardingsphere - sharding-sphere - ${project.parent.version} - pom - import - - - diff --git a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/pom.xml b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/pom.xml index 91dcc86d47ca8..1338c8447e108 100644 --- a/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/pom.xml +++ b/sharding-jdbc/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/pom.xml @@ -11,6 +11,11 @@ org.springframework.boot spring-boot-starter + + org.springframework.boot + spring-boot-configuration-processor + true + org.springframework.boot spring-boot-starter-test From 2d8ba86cb20dd2a9fa517aa7e485ba9ffbbcf5f8 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 23:14:10 +0800 Subject: [PATCH 26/34] decouple orchestration and jdbc --- sharding-orchestration/sharding-orchestration-core/pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/sharding-orchestration/sharding-orchestration-core/pom.xml b/sharding-orchestration/sharding-orchestration-core/pom.xml index ad14180a1c1a6..a9e1566824fd9 100644 --- a/sharding-orchestration/sharding-orchestration-core/pom.xml +++ b/sharding-orchestration/sharding-orchestration-core/pom.xml @@ -21,11 +21,5 @@ sharding-core ${project.version} - - - io.shardingsphere - sharding-jdbc-core - ${project.version} - From 412411ca3798cd9c1899a8857946ed1712dfe58f Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 27 Sep 2018 23:48:21 +0800 Subject: [PATCH 27/34] remove sharding-jdbc-plugin from sharding-sphere --- .../plugin/keygen/HostNameKeyGenerator.java | 62 --------- .../plugin/keygen/IPKeyGenerator.java | 56 -------- .../plugin/keygen/IPSectionKeyGenerator.java | 81 ------------ .../plugin/keygen/AllTests.java | 29 ----- .../keygen/HostNameKeyGeneratorTest.java | 121 ----------------- .../plugin/keygen/IPKeyGeneratorTest.java | 109 ---------------- .../keygen/IPSectionKeyGeneratorTest.java | 123 ------------------ 7 files changed, 581 deletions(-) delete mode 100644 sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/HostNameKeyGenerator.java delete mode 100644 sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/IPKeyGenerator.java delete mode 100644 sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/IPSectionKeyGenerator.java delete mode 100644 sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/AllTests.java delete mode 100644 sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/HostNameKeyGeneratorTest.java delete mode 100644 sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/IPKeyGeneratorTest.java delete mode 100644 sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/IPSectionKeyGeneratorTest.java diff --git a/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/HostNameKeyGenerator.java b/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/HostNameKeyGenerator.java deleted file mode 100644 index 14cfbb62dff47..0000000000000 --- a/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/HostNameKeyGenerator.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016-2018 shardingsphere.io. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *

- */ - -package io.shardingsphere.plugin.keygen; - -import io.shardingsphere.core.keygen.DefaultKeyGenerator; -import io.shardingsphere.core.keygen.KeyGenerator; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * 根据机器名最后的数字编号获取工作进程Id.如果线上机器命名有统一规范,建议使用此种方式. - * 列如机器的HostName为:dangdang-db-sharding-dev-01(公司名-部门名-服务名-环境名-编号) - * ,会截取HostName最后的编号01作为workerId. - * - * @author DonneyYoung - **/ -public final class HostNameKeyGenerator implements KeyGenerator { - - private final DefaultKeyGenerator defaultKeyGenerator = new DefaultKeyGenerator(); - - static { - initWorkerId(); - } - - static void initWorkerId() { - InetAddress address; - Long workerId; - try { - address = InetAddress.getLocalHost(); - } catch (final UnknownHostException e) { - throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!"); - } - String hostName = address.getHostName(); - try { - workerId = Long.valueOf(hostName.replace(hostName.replaceAll("\\d+$", ""), "")); - } catch (final NumberFormatException e) { - throw new IllegalArgumentException(String.format("Wrong hostname:%s, hostname must be end with number!", hostName)); - } - DefaultKeyGenerator.setWorkerId(workerId); - } - - @Override - public Number generateKey() { - return defaultKeyGenerator.generateKey(); - } -} diff --git a/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/IPKeyGenerator.java b/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/IPKeyGenerator.java deleted file mode 100644 index 43bfabd535cd5..0000000000000 --- a/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/IPKeyGenerator.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2016-2018 shardingsphere.io. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *

- */ - -package io.shardingsphere.plugin.keygen; - -import io.shardingsphere.core.keygen.DefaultKeyGenerator; -import io.shardingsphere.core.keygen.KeyGenerator; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * 根据机器IP获取工作进程Id,如果线上机器的IP二进制表示的最后10位不重复,建议使用此种方式 - * ,列如机器的IP为192.168.1.108,二进制表示:11000000 10101000 00000001 01101100 - * ,截取最后10位 01 01101100,转为十进制364,设置workerId为364. - * - * @author DonneyYoung - */ -public final class IPKeyGenerator implements KeyGenerator { - - private final DefaultKeyGenerator defaultKeyGenerator = new DefaultKeyGenerator(); - - static { - initWorkerId(); - } - - static void initWorkerId() { - InetAddress address; - try { - address = InetAddress.getLocalHost(); - } catch (final UnknownHostException e) { - throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!"); - } - byte[] ipAddressByteArray = address.getAddress(); - DefaultKeyGenerator.setWorkerId((long) (((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) << Byte.SIZE) + (ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF))); - } - - @Override - public Number generateKey() { - return defaultKeyGenerator.generateKey(); - } -} diff --git a/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/IPSectionKeyGenerator.java b/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/IPSectionKeyGenerator.java deleted file mode 100644 index 653a0f82c857f..0000000000000 --- a/sharding-jdbc-plugin/src/main/java/io/shardingsphere/plugin/keygen/IPSectionKeyGenerator.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2016-2018 shardingsphere.io. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *

- */ - -package io.shardingsphere.plugin.keygen; - -import io.shardingsphere.core.keygen.DefaultKeyGenerator; -import io.shardingsphere.core.keygen.KeyGenerator; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * 浏览 {@link IPKeyGenerator} workerId生成的规则后,感觉对服务器IP后10位(特别是IPV6)数值比较约束. - * - *

- * 有以下优化思路: - * 因为workerId最大限制是2^10,我们生成的workerId只要满足小于最大workerId即可。 - * 1.针对IPV4: - * ....IP最大 255.255.255.255。而(255+255+255+255) < 1024。 - * ....因此采用IP段数值相加即可生成唯一的workerId,不受IP位限制。 - * 2.针对IPV6: - * ....IP最大ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff - * ....为了保证相加生成出的workerId < 1024,思路是将每个bit位的后6位相加。这样在一定程度上也可以满足workerId不重复的问题。 - *

- * 使用这种IP生成workerId的方法,必须保证IP段相加不能重复 - * - * @author DogFc - */ -public final class IPSectionKeyGenerator implements KeyGenerator { - - private final DefaultKeyGenerator defaultKeyGenerator = new DefaultKeyGenerator(); - - static { - initWorkerId(); - } - - static void initWorkerId() { - InetAddress address; - try { - address = InetAddress.getLocalHost(); - } catch (final UnknownHostException e) { - throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!"); - } - byte[] ipAddressByteArray = address.getAddress(); - long workerId = 0L; - switch (ipAddressByteArray.length) { - case 4: - for (byte byteNum : ipAddressByteArray) { - workerId += byteNum & 0xFF; - } - break; - case 16: - for (byte byteNum : ipAddressByteArray) { - workerId += byteNum & 0B111111; - } - break; - default: - throw new IllegalStateException("Bad LocalHost InetAddress, please check your network!"); - } - DefaultKeyGenerator.setWorkerId(workerId); - } - - @Override - public Number generateKey() { - return defaultKeyGenerator.generateKey(); - } -} diff --git a/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/AllTests.java b/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/AllTests.java deleted file mode 100644 index 13e12c7d6cf3f..0000000000000 --- a/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/AllTests.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2016-2018 shardingsphere.io. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *

- */ - -package io.shardingsphere.plugin.keygen; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@SuiteClasses({ - HostNameKeyGeneratorTest.class, - IPKeyGeneratorTest.class - }) -public final class AllTests { -} diff --git a/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/HostNameKeyGeneratorTest.java b/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/HostNameKeyGeneratorTest.java deleted file mode 100644 index cba6869479b0c..0000000000000 --- a/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/HostNameKeyGeneratorTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2016-2018 shardingsphere.io. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *

- */ - -package io.shardingsphere.plugin.keygen; - -import io.shardingsphere.core.keygen.DefaultKeyGenerator; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.lang.reflect.Field; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(HostNameKeyGenerator.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class HostNameKeyGeneratorTest { - - private static InetAddress rightAddress; - - private static InetAddress wrongAddress; - - @Rule - public ExpectedException exception = ExpectedException.none(); - - @BeforeClass - public static void init() throws UnknownHostException { - String ipv4 = "192.168.1.108"; - byte[] ipv4Byte = new byte[4]; - String[] ipv4StingArray = ipv4.split("\\."); - for (int i = 0; i < 4; i++) { - ipv4Byte[i] = (byte) Integer.valueOf(ipv4StingArray[i]).intValue(); - } - rightAddress = InetAddress.getByAddress("dangdang-db-sharding-dev-233", ipv4Byte); - wrongAddress = InetAddress.getByAddress("dangdang-db-sharding-dev", ipv4Byte); - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddress); - HostNameKeyGenerator.initWorkerId(); - } - - @Test - public void assertRightHostName() throws UnknownHostException, NoSuchFieldException, IllegalAccessException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddress); - HostNameKeyGenerator.initWorkerId(); - Field workerIdField = DefaultKeyGenerator.class.getDeclaredField("workerId"); - workerIdField.setAccessible(true); - assertThat(workerIdField.getLong(DefaultKeyGenerator.class), is(233L)); - } - - @Test - public void assertUnknownHost() throws UnknownHostException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException()); - exception.expect(IllegalStateException.class); - exception.expectMessage("Cannot get LocalHost InetAddress, please check your network!"); - HostNameKeyGenerator.initWorkerId(); - } - - @Test - public void assertWrongHostName() throws UnknownHostException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(wrongAddress); - exception.expect(IllegalArgumentException.class); - exception.expectMessage(String.format("Wrong hostname:%s, hostname must be end with number!", wrongAddress.getHostName())); - HostNameKeyGenerator.initWorkerId(); - } - - @Test - public void assertGenerateId() throws UnknownHostException, ExecutionException, InterruptedException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddress); - HostNameKeyGenerator.initWorkerId(); - int threadNumber = Runtime.getRuntime().availableProcessors() << 1; - ExecutorService executor = Executors.newFixedThreadPool(threadNumber); - final int taskNumber = threadNumber << 2; - final HostNameKeyGenerator keyGenerator = new HostNameKeyGenerator(); - Set hashSet = new HashSet<>(); - for (int i = 0; i < taskNumber; i++) { - hashSet.add(executor.submit(new Callable() { - - @Override - public Long call() { - return (Long) keyGenerator.generateKey(); - } - }).get()); - } - assertThat(hashSet.size(), is(taskNumber)); - } -} diff --git a/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/IPKeyGeneratorTest.java b/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/IPKeyGeneratorTest.java deleted file mode 100644 index 353bbd7a2dd1f..0000000000000 --- a/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/IPKeyGeneratorTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2016-2018 shardingsphere.io. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *

- */ - -package io.shardingsphere.plugin.keygen; - -import io.shardingsphere.core.keygen.DefaultKeyGenerator; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.lang.reflect.Field; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(IPKeyGenerator.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class IPKeyGeneratorTest { - - private static InetAddress address; - - @Rule - public ExpectedException exception = ExpectedException.none(); - - @BeforeClass - public static void init() throws UnknownHostException { - String ipv4 = "192.168.1.108"; - byte[] ipv4Byte = new byte[4]; - String[] ipv4StingArray = ipv4.split("\\."); - for (int i = 0; i < 4; i++) { - ipv4Byte[i] = (byte) Integer.valueOf(ipv4StingArray[i]).intValue(); - } - address = InetAddress.getByAddress("dangdang-db-sharding-dev-233", ipv4Byte); - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(address); - IPKeyGenerator.initWorkerId(); - } - - @Test - public void assertIP() throws UnknownHostException, NoSuchFieldException, IllegalAccessException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(address); - IPKeyGenerator.initWorkerId(); - Field workerIdField = DefaultKeyGenerator.class.getDeclaredField("workerId"); - workerIdField.setAccessible(true); - assertThat(workerIdField.getLong(DefaultKeyGenerator.class), is(364L)); - } - - @Test - public void assertUnknownHost() throws UnknownHostException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException()); - exception.expect(IllegalStateException.class); - exception.expectMessage("Cannot get LocalHost InetAddress, please check your network!"); - IPKeyGenerator.initWorkerId(); - } - - @Test - public void generateId() throws UnknownHostException, ExecutionException, InterruptedException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(address); - IPKeyGenerator.initWorkerId(); - int threadNumber = Runtime.getRuntime().availableProcessors() << 1; - ExecutorService executor = Executors.newFixedThreadPool(threadNumber); - final int taskNumber = threadNumber << 2; - final IPKeyGenerator keyGenerator = new IPKeyGenerator(); - Set hashSet = new HashSet<>(); - for (int i = 0; i < taskNumber; i++) { - hashSet.add(executor.submit(new Callable() { - - @Override - public Long call() { - return (Long) keyGenerator.generateKey(); - } - }).get()); - } - assertThat(hashSet.size(), is(taskNumber)); - } -} diff --git a/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/IPSectionKeyGeneratorTest.java b/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/IPSectionKeyGeneratorTest.java deleted file mode 100644 index 5807492f582e6..0000000000000 --- a/sharding-jdbc-plugin/src/test/java/io/shardingsphere/plugin/keygen/IPSectionKeyGeneratorTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2016-2018 shardingsphere.io. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *

- */ - -package io.shardingsphere.plugin.keygen; - -import io.shardingsphere.core.keygen.DefaultKeyGenerator; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.lang.reflect.Field; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(IPSectionKeyGenerator.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@SuppressWarnings("all") -public class IPSectionKeyGeneratorTest { - - private static InetAddress ipv4Address; - - private static InetAddress ipv6Address; - - @Rule - public ExpectedException exception = ExpectedException.none(); - - @BeforeClass - public static void init() throws UnknownHostException { - String ipv4 = "192.168.1.1"; - byte[] ipv4Byte = new byte[4]; - String[] ipv4StingArray = ipv4.split("\\."); - for (int i = 0; i < 4; i++) { - ipv4Byte[i] = (byte) Integer.valueOf(ipv4StingArray[i]).intValue(); - } - ipv4Address = InetAddress.getByAddress("dangdang-db-sharding-dev-233", ipv4Byte); - - String ipv6 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; - ipv6Address = InetAddress.getByName(ipv6); - } - - @Test - public void assertIPV4() throws UnknownHostException, NoSuchFieldException, IllegalAccessException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(ipv4Address); - IPSectionKeyGenerator.initWorkerId(); - Field workerIdField = DefaultKeyGenerator.class.getDeclaredField("workerId"); - workerIdField.setAccessible(true); - assertThat(workerIdField.getLong(DefaultKeyGenerator.class), is(362L)); - } - - @Test - public void assertIPV6() throws UnknownHostException, NoSuchFieldException, IllegalAccessException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(ipv6Address); - IPSectionKeyGenerator.initWorkerId(); - Field workerIdField = DefaultKeyGenerator.class.getDeclaredField("workerId"); - workerIdField.setAccessible(true); - assertThat(workerIdField.getLong(DefaultKeyGenerator.class), is(1008L)); - } - - @Test - public void assertUnknownHost() throws UnknownHostException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException()); - exception.expect(IllegalStateException.class); - exception.expectMessage("Cannot get LocalHost InetAddress, please check your network!"); - IPSectionKeyGenerator.initWorkerId(); - } - - @Test - public void generateId() throws UnknownHostException, ExecutionException, InterruptedException { - PowerMockito.mockStatic(InetAddress.class); - PowerMockito.when(InetAddress.getLocalHost()).thenReturn(ipv4Address); - IPSectionKeyGenerator.initWorkerId(); - int threadNumber = Runtime.getRuntime().availableProcessors() << 1; - ExecutorService executor = Executors.newFixedThreadPool(threadNumber); - - final int taskNumber = threadNumber << 2; - final IPSectionKeyGenerator ipSectionKeyGenerator = new IPSectionKeyGenerator(); - Set hashSet = new HashSet<>(); - for (int i = 0; i < taskNumber; i++) { - hashSet.add(executor.submit(new Callable() { - - @Override - public Long call() { - return (Long) ipSectionKeyGenerator.generateKey(); - } - }).get()); - } - assertThat(hashSet.size(), is(taskNumber)); - } -} From 2635e4b4568f283b51fbed59931395416268028f Mon Sep 17 00:00:00 2001 From: tristaZero Date: Fri, 28 Sep 2018 10:36:51 +0800 Subject: [PATCH 28/34] createShardingDataSource() --- .../OrchestrationSpringBootConfiguration.java | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java index 489000bae04c2..2e4373e9b8a55 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java @@ -18,6 +18,7 @@ package io.shardingsphere.shardingjdbc.orchestration.spring.boot; import com.google.common.base.Preconditions; +import com.google.common.base.Strings; import io.shardingsphere.core.exception.ShardingException; import io.shardingsphere.core.rule.ShardingRule; import io.shardingsphere.orchestration.config.OrchestrationType; @@ -48,6 +49,7 @@ * Orchestration spring boot sharding and master-slave configuration. * * @author caohao + * @author panjuan */ @Configuration @EnableConfigurationProperties({SpringBootShardingRuleConfigurationProperties.class, SpringBootMasterSlaveRuleConfigurationProperties.class, SpringBootOrchestrationConfigurationProperties.class}) @@ -74,10 +76,21 @@ public class OrchestrationSpringBootConfiguration implements EnvironmentAware { public DataSource dataSource() throws SQLException { OrchestrationType type = orchestrationProperties.getType(); Preconditions.checkState(null != type, "Missing the type of datasource configuration in orchestration configuration"); - if (OrchestrationType.SHARDING == type) { - ShardingDataSource shardingDataSource = new ShardingDataSource( - dataSourceMap, new ShardingRule(shardingProperties.getShardingRuleConfiguration(), dataSourceMap.keySet()), shardingProperties.getConfigMap(), shardingProperties.getProps()); - return new OrchestrationShardingDataSource(shardingDataSource, orchestrationProperties.getOrchestrationConfiguration()); + return OrchestrationType.SHARDING == type ? createShardingDataSource() : createMasterSlaveDataSource(); + } + + private DataSource createShardingDataSource() throws SQLException { + if (shardingProperties.getTables().isEmpty()) { + return new OrchestrationShardingDataSource(orchestrationProperties.getOrchestrationConfiguration()); + } + ShardingDataSource shardingDataSource = new ShardingDataSource( + dataSourceMap, new ShardingRule(shardingProperties.getShardingRuleConfiguration(), dataSourceMap.keySet()), shardingProperties.getConfigMap(), shardingProperties.getProps()); + return new OrchestrationShardingDataSource(shardingDataSource, orchestrationProperties.getOrchestrationConfiguration()); + } + + private DataSource createMasterSlaveDataSource() throws SQLException { + if (Strings.isNullOrEmpty(masterSlaveProperties.getMasterDataSourceName())) { + return new OrchestrationShardingDataSource(orchestrationProperties.getOrchestrationConfiguration()); } MasterSlaveDataSource masterSlaveDataSource = new MasterSlaveDataSource( dataSourceMap, masterSlaveProperties.getMasterSlaveRuleConfiguration(), masterSlaveProperties.getConfigMap(), masterSlaveProperties.getProps()); From d7256339546926e1595ed6301d75cb4f01bbecbd Mon Sep 17 00:00:00 2001 From: tristaZero Date: Fri, 28 Sep 2018 11:32:06 +0800 Subject: [PATCH 29/34] createMasterSlaveDataSource() --- .../spring/boot/OrchestrationSpringBootConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java index 2e4373e9b8a55..634cdb5a7b706 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingsphere/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java @@ -90,7 +90,7 @@ private DataSource createShardingDataSource() throws SQLException { private DataSource createMasterSlaveDataSource() throws SQLException { if (Strings.isNullOrEmpty(masterSlaveProperties.getMasterDataSourceName())) { - return new OrchestrationShardingDataSource(orchestrationProperties.getOrchestrationConfiguration()); + return new OrchestrationMasterSlaveDataSource(orchestrationProperties.getOrchestrationConfiguration()); } MasterSlaveDataSource masterSlaveDataSource = new MasterSlaveDataSource( dataSourceMap, masterSlaveProperties.getMasterSlaveRuleConfiguration(), masterSlaveProperties.getConfigMap(), masterSlaveProperties.getProps()); From 191d076009e82a669546551c96c89a627b940bfb Mon Sep 17 00:00:00 2001 From: terrymanu Date: Fri, 28 Sep 2018 11:41:46 +0800 Subject: [PATCH 30/34] add sharding-jdbc-core depen for orche --- sharding-orchestration/sharding-orchestration-core/pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sharding-orchestration/sharding-orchestration-core/pom.xml b/sharding-orchestration/sharding-orchestration-core/pom.xml index a9e1566824fd9..ad14180a1c1a6 100644 --- a/sharding-orchestration/sharding-orchestration-core/pom.xml +++ b/sharding-orchestration/sharding-orchestration-core/pom.xml @@ -21,5 +21,11 @@ sharding-core ${project.version} + + + io.shardingsphere + sharding-jdbc-core + ${project.version} + From 23f89fa3de386663860841b911dbf2f1637deb75 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Fri, 28 Sep 2018 11:44:21 +0800 Subject: [PATCH 31/34] remove invalid maven --- .../sharding-jdbc-orchestration-spring-namespace/pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml index dbcae08bcb546..db8b59dbfe3bc 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml @@ -8,12 +8,6 @@ sharding-jdbc-orchestration-spring-namespace - - io.shardingsphere - sharding-jdbc-spring-namespace - ${project.version} - - org.springframework spring-context-support From 65a976b881b6cd0fcc57b919cbe40f20a32a75d2 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Fri, 28 Sep 2018 11:59:20 +0800 Subject: [PATCH 32/34] add sharding-jdbc-spring-namespace for test score on sharding-jdbc-orchestration-spring-namespace --- .../sharding-jdbc-orchestration-spring-namespace/pom.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml index db8b59dbfe3bc..1ea2e138fd470 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml +++ b/sharding-jdbc/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/pom.xml @@ -8,6 +8,13 @@ sharding-jdbc-orchestration-spring-namespace + + io.shardingsphere + sharding-jdbc-spring-namespace + ${project.version} + test + + org.springframework spring-context-support From b4ea029c52109337f57a24eaa6458e36ecbf22e3 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Fri, 28 Sep 2018 12:09:14 +0800 Subject: [PATCH 33/34] Improve combability with cobertura --- pom.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pom.xml b/pom.xml index 5427f51bd4897..66cd041761393 100644 --- a/pom.xml +++ b/pom.xml @@ -597,6 +597,9 @@ xml true + + lombok.Generated + io/shardingsphere/**/*Test.class io/shardingsphere/**/Test*.class From 0623d395708191a30fa1a58827218b916641baae Mon Sep 17 00:00:00 2001 From: terrymanu Date: Fri, 28 Sep 2018 14:19:39 +0800 Subject: [PATCH 34/34] use @SneakyThrow to instead of never occurred exception --- .../spi/NewInstanceServiceLoader.java | 9 +- .../executor/fixture/ExecutorTestUtil.java | 8 +- .../ExecutorExceptionHandlerTest.java | 2 +- .../core/keygen/DefaultKeyGeneratorTest.java | 4 +- .../asserts/ParserResultSetLoader.java | 11 +-- .../asserts/condition/ConditionAssert.java | 12 ++- ...tractShardingPreparedStatementAdapter.java | 17 ++-- .../jdbc/adapter/WrapperAdapter.java | 9 +- .../invocation/JdbcMethodInvocation.java | 10 +-- .../datasource/MasterSlaveDataSource.java | 3 +- .../assertion/IntegrateTestCasesLoader.java | 14 ++- .../api/ShardingDataSourceFactoryTest.java | 13 +-- .../executor/AbstractBaseExecutorTest.java | 4 +- .../BatchPreparedStatementExecutorTest.java | 89 ++++++++++--------- .../PreparedStatementExecutorTest.java | 75 ++++++++-------- .../executor/StatementExecutorTest.java | 89 ++++++++++--------- .../executor/fixture/ExecutorTestUtil.java | 6 +- .../jdbc/adapter/ConnectionAdapterTest.java | 12 ++- .../jdbc/adapter/DataSourceAdapterTest.java | 3 +- .../invocation/JdbcMethodInvocationTest.java | 10 ++- .../SetParameterMethodInvocationTest.java | 7 +- .../spring/boot/util/PropertyUtil.java | 69 +++++++------- ...rchestrationSpringBootMasterSlaveTest.java | 4 +- .../OrchestrationSpringBootShardingTest.java | 24 ++--- .../spring/util/FieldValueUtil.java | 15 ++-- .../spring/boot/util/PropertyUtil.java | 69 +++++++------- .../boot/type/SpringBootShardingTest.java | 20 +++-- .../spring/util/FieldValueUtil.java | 15 ++-- .../opentracing/ShardingTracerTest.java | 6 +- .../hook/BaseOpenTracingHookTest.java | 4 +- .../representer/DataSourceRepresenter.java | 25 ++---- .../MasterSlaveConfigurationRepresenter.java | 23 ++--- .../ProxyConfigurationRepresenter.java | 23 ++--- .../ShardingConfigurationRepresenter.java | 23 ++--- .../datasource/JDBCBackendDataSource.java | 3 +- .../response/mysql/MySQLResponseHandler.java | 28 +++--- .../listener/ProxyListenerRegisterTest.java | 4 +- .../command/CommandPacketFactoryTest.java | 6 +- .../admin/initdb/ComInitDbPacketTest.java | 4 +- .../binary/BinaryStatementRegistryTest.java | 2 +- .../execute/ComStmtExecutePacketTest.java | 13 +-- .../fixture/BinaryStatementRegistryUtil.java | 6 +- .../prepare/ComStmtPreparePacketTest.java | 19 ++-- .../fieldlist/ComFieldListPacketTest.java | 8 +- .../query/text/query/ComQueryPacketTest.java | 25 +++--- .../handshake/AuthorityHandlerTest.java | 9 +- .../handshake/ConnectionIdGeneratorTest.java | 18 ++-- .../test/sql/SQLCasesLoader.java | 18 ++-- .../xa/XATransactionListenerTest.java | 4 +- .../AtomikosTransactionManagerTest.java | 4 +- 50 files changed, 436 insertions(+), 462 deletions(-) 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");