From 57b0a276be17aeaefe97f9ef7dcdc777d55c0bc6 Mon Sep 17 00:00:00 2001 From: tuohai666 Date: Thu, 18 Oct 2018 16:16:11 +0800 Subject: [PATCH 01/10] typo --- sharding-proxy/src/main/resources/conf/config-sharding.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding-proxy/src/main/resources/conf/config-sharding.yaml b/sharding-proxy/src/main/resources/conf/config-sharding.yaml index 09cf66f7455df..b834ef08536ca 100644 --- a/sharding-proxy/src/main/resources/conf/config-sharding.yaml +++ b/sharding-proxy/src/main/resources/conf/config-sharding.yaml @@ -45,7 +45,7 @@ # inline: # shardingColumn: order_id # algorithmExpression: t_order_item_${order_id % 2} -# keyGeneratorColumnName: order_item_id +# keyGeneratorColumnName: order_item_id # bindingTables: # - t_order,t_order_item # defaultDatabaseStrategy: From a64ce890bdadda240d1830da23e74bf00080d933 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 18 Oct 2018 17:12:37 +0800 Subject: [PATCH 02/10] remove native-zookeeper --- pom.xml | 6 - .../sharding-orchestration-reg/pom.xml | 1 - .../pom.xml | 30 -- .../NativeZookeeperExceptionHandler.java | 60 --- .../NativeZookeeperRegistryCenter.java | 245 ------------ .../client/action/ContentionCallback.java | 31 -- .../natived/client/action/IAction.java | 136 ------- .../natived/client/action/IClient.java | 103 ----- .../natived/client/action/IExecStrategy.java | 42 -- .../natived/client/action/IGroupAction.java | 58 --- .../natived/client/action/IProvider.java | 185 --------- .../client/action/ITransactionProvider.java | 39 -- .../natived/client/cache/CacheStrategy.java | 28 -- .../natived/client/cache/PathNode.java | 96 ----- .../natived/client/cache/PathResolve.java | 78 ---- .../natived/client/cache/PathStatus.java | 28 -- .../natived/client/cache/PathTree.java | 369 ------------------ .../client/election/LeaderElection.java | 122 ------ .../client/retry/AsyncRetryCenter.java | 74 ---- .../client/retry/DelayPolicyExecutor.java | 70 ---- .../client/retry/DelayRetryPolicy.java | 56 --- .../natived/client/retry/RetryCallable.java | 82 ---- .../client/retry/RetryResultCallable.java | 51 --- .../natived/client/retry/RetryThread.java | 114 ------ .../natived/client/utility/PathUtil.java | 192 --------- .../client/utility/ZookeeperConstants.java | 64 --- .../natived/client/zookeeper/CacheClient.java | 125 ------ .../client/zookeeper/ClientFactory.java | 131 ------- .../natived/client/zookeeper/UsualClient.java | 189 --------- .../client/zookeeper/base/BaseClient.java | 181 --------- .../zookeeper/base/BaseClientFactory.java | 98 ----- .../client/zookeeper/base/BaseContext.java | 55 --- .../client/zookeeper/base/BaseOperation.java | 82 ---- .../natived/client/zookeeper/base/Holder.java | 172 -------- .../operation/CreateAllNeedOperation.java | 55 --- .../operation/CreateCurrentOperation.java | 54 --- .../operation/DeleteAllChildrenOperation.java | 48 --- .../DeleteCurrentBranchOperation.java | 48 --- .../operation/DeleteCurrentOperation.java | 47 --- .../zookeeper/operation/UpdateOperation.java | 50 --- .../zookeeper/provider/BaseProvider.java | 157 -------- .../provider/TransactionProvider.java | 50 --- .../zookeeper/section/ClientContext.java | 62 --- .../client/zookeeper/section/ClientTask.java | 53 --- .../client/zookeeper/section/Connection.java | 69 ---- .../zookeeper/section/StrategyType.java | 33 -- .../zookeeper/section/WatcherCreator.java | 50 --- .../section/ZookeeperEventListener.java | 52 --- .../strategy/AsyncRetryStrategy.java | 134 ------- .../zookeeper/strategy/BaseStrategy.java | 47 --- .../strategy/ContentionStrategy.java | 252 ------------ .../zookeeper/strategy/SyncRetryStrategy.java | 166 -------- .../strategy/TransactionContendStrategy.java | 150 ------- .../zookeeper/strategy/UsualStrategy.java | 170 -------- .../transaction/BaseTransaction.java | 123 ------ .../transaction/ZooKeeperTransaction.java | 91 ----- ...phere.orchestration.reg.api.RegistryCenter | 1 - .../natived/AllNativeZookeeperTests.java | 38 -- .../natived/client/cache/PathResolveTest.java | 60 --- .../natived/client/cache/PathTreeTest.java | 202 ---------- .../natived/client/retry/TestCallable.java | 51 --- .../client/retry/TestResultCallable.java | 51 --- .../client/util/EmbedTestingServer.java | 62 --- .../client/zookeeper/AllBaseTests.java | 28 -- .../zookeeper/SyncRetryStrategyTest.java | 237 ----------- .../client/zookeeper/UsualClientTest.java | 163 -------- .../client/zookeeper/base/BaseClientTest.java | 321 --------------- .../client/zookeeper/base/BaseTest.java | 39 -- .../client/zookeeper/base/StartWaitTest.java | 50 --- .../client/zookeeper/base/TestClient.java | 47 --- .../client/zookeeper/base/TestHolder.java | 54 --- .../client/zookeeper/base/TestSupport.java | 52 --- .../src/test/resources/logback-test.xml | 19 - .../pom.xml | 5 + 74 files changed, 5 insertions(+), 6829 deletions(-) delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/pom.xml delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/NativeZookeeperExceptionHandler.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/NativeZookeeperRegistryCenter.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/ContentionCallback.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IAction.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IClient.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IExecStrategy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IGroupAction.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IProvider.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/ITransactionProvider.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/CacheStrategy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathNode.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathResolve.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathStatus.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathTree.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/election/LeaderElection.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/AsyncRetryCenter.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/DelayPolicyExecutor.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/DelayRetryPolicy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryCallable.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryResultCallable.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryThread.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/utility/PathUtil.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/utility/ZookeeperConstants.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/CacheClient.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/ClientFactory.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/UsualClient.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClient.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClientFactory.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseContext.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseOperation.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/Holder.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/CreateAllNeedOperation.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/CreateCurrentOperation.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteAllChildrenOperation.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteCurrentBranchOperation.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteCurrentOperation.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/UpdateOperation.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/provider/BaseProvider.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/provider/TransactionProvider.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ClientContext.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ClientTask.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/Connection.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/StrategyType.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/WatcherCreator.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ZookeeperEventListener.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/AsyncRetryStrategy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/BaseStrategy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/ContentionStrategy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/SyncRetryStrategy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/TransactionContendStrategy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/UsualStrategy.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/transaction/BaseTransaction.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/transaction/ZooKeeperTransaction.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/resources/META-INF/services/io.shardingsphere.orchestration.reg.api.RegistryCenter delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/AllNativeZookeeperTests.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathResolveTest.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathTreeTest.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/TestCallable.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/TestResultCallable.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/util/EmbedTestingServer.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/AllBaseTests.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/SyncRetryStrategyTest.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/UsualClientTest.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClientTest.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseTest.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/StartWaitTest.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestClient.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestHolder.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestSupport.java delete mode 100644 sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/resources/logback-test.xml diff --git a/pom.xml b/pom.xml index ada9b7fc5a97a..035efdee98049 100644 --- a/pom.xml +++ b/pom.xml @@ -39,7 +39,6 @@ 1.1 4.0.4 - 3.4.6 2.10.0 1.7.0 3.4.0 @@ -156,11 +155,6 @@ ${atomikos.version} - - org.apache.zookeeper - zookeeper - ${zookeeper.version} - org.apache.curator curator-framework diff --git a/sharding-orchestration/sharding-orchestration-reg/pom.xml b/sharding-orchestration/sharding-orchestration-reg/pom.xml index 1a2c4e20ebabd..4a328091af2e5 100644 --- a/sharding-orchestration/sharding-orchestration-reg/pom.xml +++ b/sharding-orchestration/sharding-orchestration-reg/pom.xml @@ -14,7 +14,6 @@ sharding-orchestration-reg-api sharding-orchestration-reg-zookeeper-curator - sharding-orchestration-reg-native-zookeeper sharding-orchestration-reg-etcd diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/pom.xml b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/pom.xml deleted file mode 100644 index 8d4de8deca0b1..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 4.0.0 - - io.shardingsphere - sharding-orchestration-reg - 3.0.0.M5-SNAPSHOT - - sharding-orchestration-reg-native-zookeeper - - - - io.shardingsphere - sharding-orchestration-reg-api - ${project.version} - - - - org.apache.zookeeper - zookeeper - - - - org.apache.curator - curator-test - - - diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/NativeZookeeperExceptionHandler.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/NativeZookeeperExceptionHandler.java deleted file mode 100644 index 5285bf94713d1..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/NativeZookeeperExceptionHandler.java +++ /dev/null @@ -1,60 +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.orchestration.reg.zookeeper.natived; - -import io.shardingsphere.orchestration.reg.exception.RegistryCenterException; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.KeeperException.ConnectionLossException; -import org.apache.zookeeper.KeeperException.NoNodeException; -import org.apache.zookeeper.KeeperException.NodeExistsException; - -/** - * Native zookeeper exception handler. - * - * @author zhangliang - */ -@Slf4j -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class NativeZookeeperExceptionHandler { - - /** - * Handle exception. - * - *

Ignore interrupt and connection invalid exception.

- * - * @param cause to be handled exception - */ - public static void handleException(final Exception cause) { - if (null == cause) { - return; - } - if (isIgnoredException(cause) || null != cause.getCause() && isIgnoredException(cause.getCause())) { - log.debug("Ignored exception for: {}", cause.getMessage()); - } else if (cause instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } else { - throw new RegistryCenterException(cause); - } - } - - private static boolean isIgnoredException(final Throwable cause) { - return cause instanceof ConnectionLossException || cause instanceof NoNodeException || cause instanceof NodeExistsException; - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/NativeZookeeperRegistryCenter.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/NativeZookeeperRegistryCenter.java deleted file mode 100644 index 2cc8ba1224b52..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/NativeZookeeperRegistryCenter.java +++ /dev/null @@ -1,245 +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.orchestration.reg.zookeeper.natived; - -import com.google.common.base.Charsets; -import com.google.common.base.Optional; -import com.google.common.base.Strings; -import io.shardingsphere.orchestration.reg.api.RegistryCenter; -import io.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration; -import io.shardingsphere.orchestration.reg.listener.DataChangedEvent; -import io.shardingsphere.orchestration.reg.listener.EventListener; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.cache.PathTree; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.DelayRetryPolicy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.ClientFactory; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.StrategyType; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.ZooDefs; - -import java.io.IOException; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; - -/** - * Registry center for native zookeeper. - * - * @author lidongbo - */ -public final class NativeZookeeperRegistryCenter implements RegistryCenter { - - private final Map caches = new HashMap<>(); - - private IClient client; - - @Override - public void init(final RegistryCenterConfiguration config) { - client = initClient(buildClientFactory(config), config); - } - - private ClientFactory buildClientFactory(final RegistryCenterConfiguration config) { - ClientFactory result = new ClientFactory(); - result.setClientNamespace(config.getNamespace()).newClient(config.getServerLists(), config.getTimeToLiveSeconds() * 1000) - .setRetryPolicy(new DelayRetryPolicy(config.getRetryIntervalMilliseconds(), config.getMaxRetries(), config.getRetryIntervalMilliseconds())); - if (!Strings.isNullOrEmpty(config.getDigest())) { - result.authorization("digest", config.getDigest().getBytes(Charsets.UTF_8), ZooDefs.Ids.CREATOR_ALL_ACL); - } - return result; - } - - private IClient initClient(final ClientFactory clientFactory, final RegistryCenterConfiguration config) { - IClient result = null; - try { - // TODO There is a bug when the start time is very short, and I haven't found the reason yet - // result = clientFactory.start(config.getRetryIntervalMilliseconds() * config.getMaxRetries(), TimeUnit.MILLISECONDS); - result = clientFactory.start(); - if (!result.blockUntilConnected(config.getRetryIntervalMilliseconds() * config.getMaxRetries(), TimeUnit.MILLISECONDS)) { - result.close(); - throw new KeeperException.OperationTimeoutException(); - } - result.useExecStrategy(StrategyType.SYNC_RETRY); - } catch (final KeeperException.OperationTimeoutException | IOException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - } - return result; - } - - @Override - public String get(final String key) { - Optional cache = findTreeCache(key); - if (!cache.isPresent()) { - return getDirectly(key); - } - byte[] resultInCache = cache.get().getValue(key); - if (null != resultInCache) { - return new String(resultInCache, Charsets.UTF_8); - } - return getDirectly(key); - } - - private Optional findTreeCache(final String key) { - for (Entry entry : caches.entrySet()) { - if (key.startsWith(entry.getKey())) { - return Optional.of(entry.getValue()); - } - } - return Optional.absent(); - } - - @Override - public String getDirectly(final String key) { - try { - return new String(client.getData(key), Charsets.UTF_8); - } catch (final KeeperException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - return null; - } - } - - @Override - public boolean isExisted(final String key) { - try { - return client.checkExists(key); - } catch (final KeeperException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - return false; - } - } - - @Override - public List getChildrenKeys(final String key) { - try { - final List result = client.getChildren(key); - Collections.sort(result, new Comparator() { - - @Override - public int compare(final String o1, final String o2) { - return o2.compareTo(o1); - } - }); - return result; - } catch (final KeeperException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - return Collections.emptyList(); - } - } - - @Override - public void persist(final String key, final String value) { - try { - if (!isExisted(key)) { - client.createAllNeedPath(key, value, CreateMode.PERSISTENT); - } else { - update(key, value); - } - } catch (final KeeperException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - } - } - - @Override - public void update(final String key, final String value) { - try { - client.transaction().check(key, ZookeeperConstants.VERSION).setData(key, value.getBytes(ZookeeperConstants.UTF_8), ZookeeperConstants.VERSION).commit(); - } catch (final KeeperException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - } - } - - @Override - public void persistEphemeral(final String key, final String value) { - try { - if (isExisted(key)) { - client.deleteAllChildren(key); - } - client.createAllNeedPath(key, value, CreateMode.EPHEMERAL); - } catch (final KeeperException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - } - } - - @Override - public void watch(final String key, final EventListener eventListener) { - String path = key + "/"; - if (!caches.containsKey(path)) { - addCacheData(key); - } - PathTree cache = caches.get(path); - cache.watch(new ZookeeperEventListener() { - - @Override - public void process(final WatchedEvent event) { - if (!Strings.isNullOrEmpty(event.getPath())) { - eventListener.onChange(new DataChangedEvent(extractEventType(event), event.getPath(), getWithoutCache(event.getPath()))); - } - } - }); - } - - private DataChangedEvent.Type extractEventType(final WatchedEvent event) { - switch (event.getType()) { - case NodeDataChanged: - case NodeChildrenChanged: - return DataChangedEvent.Type.UPDATED; - case NodeDeleted: - return DataChangedEvent.Type.DELETED; - default: - return DataChangedEvent.Type.IGNORED; - } - } - - private synchronized String getWithoutCache(final String key) { - try { - client.useExecStrategy(StrategyType.USUAL); - byte[] data = client.getData(key); - client.useExecStrategy(StrategyType.SYNC_RETRY); - return null == data ? null : new String(data, Charsets.UTF_8); - } catch (final KeeperException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - return null; - } - } - - private void addCacheData(final String cachePath) { - PathTree cache = new PathTree(cachePath, client); - try { - cache.load(); - cache.watch(); - } catch (final KeeperException | InterruptedException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - } - caches.put(cachePath + "/", cache); - } - - @Override - public void close() { - for (Entry each : caches.entrySet()) { - each.getValue().close(); - } - client.close(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/ContentionCallback.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/ContentionCallback.java deleted file mode 100644 index 83c42baf9d1c5..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/ContentionCallback.java +++ /dev/null @@ -1,31 +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.orchestration.reg.zookeeper.natived.client.action; - -/** - * Callback on contention has not reached. - * - * @author lidongbo - */ -public interface ContentionCallback { - - /** - * Process callback result. - */ - void processResult(); -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IAction.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IAction.java deleted file mode 100644 index f0c119ab282e2..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IAction.java +++ /dev/null @@ -1,136 +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.orchestration.reg.zookeeper.natived.client.action; - -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.Watcher; - -import java.util.List; - -/** - * The basic actions of the client. - * - * @author lidongbo - */ -public interface IAction { - - /** - * Get string type data. - * - * @param key key - * @return data String - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - String getDataString(String key) throws KeeperException, InterruptedException; - - /** - * Get string type data. - * - * @param key key - * @return data - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - byte[] getData(String key) throws KeeperException, InterruptedException; - - /** - * Get string type data. - * - * @param key key - * @param callback callback - * @param ctx context - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void getData(String key, AsyncCallback.DataCallback callback, Object ctx) throws KeeperException, InterruptedException; - - /** - * Check exist. - * - * @param key key - * @return exist or not - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - boolean checkExists(String key) throws KeeperException, InterruptedException; - - /** - * Check exist. - * - * @param key key - * @param watcher watcher - * @return exist or not - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - boolean checkExists(String key, Watcher watcher) throws KeeperException, InterruptedException; - - /** - * Get children's keys. - * - * @param key key - * @return children keys - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - List getChildren(String key) throws KeeperException, InterruptedException; - - /** - * Only create target node. - * - * @param key key - * @param value value - * @param createMode createMode - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void createCurrentOnly(String key, String value, CreateMode createMode) throws KeeperException, InterruptedException; - - /** - * Update. - * - * @param key key - * @param value value - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void update(String key, String value) throws KeeperException, InterruptedException; - - /** - * Only delete target node.. - * - * @param key key - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void deleteOnlyCurrent(String key) throws KeeperException, InterruptedException; - - /** - * Only delete target node.. - * - * @param key key - * @param callback callback - * @param ctx context - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void deleteOnlyCurrent(String key, AsyncCallback.VoidCallback callback, Object ctx) throws KeeperException, InterruptedException; -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IClient.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IClient.java deleted file mode 100644 index 2be97e81032f7..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IClient.java +++ /dev/null @@ -1,103 +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.orchestration.reg.zookeeper.natived.client.action; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.StrategyType; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -/** - * Client API. - * - * @author lidongbo - */ -public interface IClient extends IAction, IGroupAction { - - /** - * Start. - * - * @throws IOException IO exception - * @throws InterruptedException interrupted exception - */ - void start() throws IOException, InterruptedException; - - /** - * Start until out. - * - * @param waitingTime waiting time - * @param timeUnit time unit - * @return connected or not - * @throws IOException IO exception - * @throws InterruptedException interrupted exception - */ - boolean start(int waitingTime, TimeUnit timeUnit) throws IOException, InterruptedException; - - /** - * Block until connected. - * - * @param waitingTime waiting time - * @param timeUnit time unit - * @return connected or not - * @throws InterruptedException interrupted exception - */ - boolean blockUntilConnected(int waitingTime, TimeUnit timeUnit) throws InterruptedException; - - /** - * Register watcher. - * - * @param key key - * @param zookeeperEventListener zookeeper event listener - */ - void registerWatch(String key, ZookeeperEventListener zookeeperEventListener); - - /** - * Unregister watcher. - * - * @param key key - */ - void unregisterWatch(String key); - - /** - * Choice exec strategy. - * - * @param strategyType strategyType - */ - void useExecStrategy(StrategyType strategyType); - - /** - * Get execution strategy. - * - * @return execution strategy - */ - IExecStrategy getExecStrategy(); - - /** - * Create zookeeper transaction. - * - * @return zookeeper transaction - */ - BaseTransaction transaction(); - - /** - * Close. - */ - void close(); -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IExecStrategy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IExecStrategy.java deleted file mode 100644 index 48337ffd384c3..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IExecStrategy.java +++ /dev/null @@ -1,42 +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.orchestration.reg.zookeeper.natived.client.action; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; - -/** - * Client 's execution strategy. - * - * @author lidongbo - */ -public interface IExecStrategy extends IAction, IGroupAction { - - /** - * Get provider. - * - * @return provider - */ - IProvider getProvider(); - - /** - * Create zookeeper transaction. - * - * @return zookeeper transaction - */ - BaseTransaction transaction(); -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IGroupAction.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IGroupAction.java deleted file mode 100644 index c8acd37e759a0..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IGroupAction.java +++ /dev/null @@ -1,58 +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.orchestration.reg.zookeeper.natived.client.action; - -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; - -/** - * One action contains a group operation. - * - * @author lidongbo - */ -public interface IGroupAction { - - /** - * Create target node and all need created. - * - * @param key key - * @param value value - * @param createMode create mode - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void createAllNeedPath(String key, String value, CreateMode createMode) throws KeeperException, InterruptedException; - - /** - * Delete target node and children nodes. - * - * @param key key - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void deleteAllChildren(String key) throws KeeperException, InterruptedException; - - /** - * Delete the current node with force and delete the super node whose only child node is current node recursively. - * - * @param key key - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void deleteCurrentBranch(String key) throws KeeperException, InterruptedException; -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IProvider.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IProvider.java deleted file mode 100644 index 161f6d78cee9b..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/IProvider.java +++ /dev/null @@ -1,185 +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.orchestration.reg.zookeeper.natived.client.action; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.election.LeaderElection; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.Watcher; - -import java.util.List; -import java.util.Stack; - -/** - * Provider API. - * - * @author lidongbo - */ -public interface IProvider { - - /** - * Get string type data. - * - * @param key key - * @return data String - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - String getDataString(String key) throws KeeperException, InterruptedException; - - /** - * Get string type data. - * - * @param key key - * @return data - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - byte[] getData(String key) throws KeeperException, InterruptedException; - - /** - * Get string type data. - * - * @param key key - * @param callback callback - * @param ctx ctx - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void getData(String key, AsyncCallback.DataCallback callback, Object ctx) throws KeeperException, InterruptedException; - - /** - * Check exist. - * - * @param key key - * @return exist - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - boolean exists(String key) throws KeeperException, InterruptedException; - - /** - * Check exist. - * - * @param key key - * @param watcher watcher - * @return exist - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - boolean exists(String key, Watcher watcher) throws KeeperException, InterruptedException; - - /** - * Get children's keys. - * - * @param key key - * @return exist - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - List getChildren(String key) throws KeeperException, InterruptedException; - - /** - * Only create target node. - * - * @param key key - * @param value value - * @param createMode create mode - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void create(String key, String value, CreateMode createMode) throws KeeperException, InterruptedException; - - /** - * Update. - * - * @param key key - * @param value value - * @return is success - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - boolean update(String key, String value) throws KeeperException, InterruptedException; - - /** - * Only delete target node.. - * - * @param key key - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void delete(String key) throws KeeperException, InterruptedException; - - /** - * Only delete target node. - * - * @param key key - * @param callback callback - * @param ctx ctx - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - void delete(String key, AsyncCallback.VoidCallback callback, Object ctx) throws KeeperException, InterruptedException; - - /** - * Get real path with root. - * - * @param path path - * @return real path - */ - String getRealPath(String path); - - /** - * Get path nodes that needed create. - * - * @param key key - * @return all path nodes - */ - List getNecessaryPaths(String key); - - /** - * Get path nodes that needed delete. - * - * @param key key - * @return all path nodes - */ - Stack getDeletingPaths(String key); - - /** - * Contention exec. - * - * @param election election - * @throws KeeperException zookeeper exception - * @throws InterruptedException InterruptedException - */ - void executeContention(LeaderElection election) throws KeeperException, InterruptedException; - - /** - * Reset connection. - */ - void resetConnection(); - - /** - * Create zookeeper transaction. - * - * @return zookeeper transaction - */ - BaseTransaction transaction(); -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/ITransactionProvider.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/ITransactionProvider.java deleted file mode 100644 index 11ad6590504b7..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/action/ITransactionProvider.java +++ /dev/null @@ -1,39 +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.orchestration.reg.zookeeper.natived.client.action; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; -import org.apache.zookeeper.CreateMode; - -/** - * Provider with transaction. - * - * @author lidongbo - */ -public interface ITransactionProvider extends IProvider { - - /** - * Only create target node in transaction. - * - * @param key key - * @param value value - * @param createMode create mode - * @param transaction zookeeper transaction - */ - void createInTransaction(String key, String value, CreateMode createMode, BaseTransaction transaction); -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/CacheStrategy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/CacheStrategy.java deleted file mode 100644 index a725bf1a7f19e..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/CacheStrategy.java +++ /dev/null @@ -1,28 +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.orchestration.reg.zookeeper.natived.client.cache; - -/** - * Cache strategy. - * - * @author lidongbo - */ -public enum CacheStrategy { - - NONE, WATCH, ALL -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathNode.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathNode.java deleted file mode 100644 index d587a7e667759..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathNode.java +++ /dev/null @@ -1,96 +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.orchestration.reg.zookeeper.natived.client.cache; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import lombok.Getter; -import lombok.Setter; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Zookeeper node cache. - * - * @author lidongbo - */ -@Getter -@Setter -public final class PathNode { - - private final Map children = new ConcurrentHashMap<>(); - - private final String nodeKey; - - private String path; - - private byte[] value; - - PathNode(final String key) { - this(key, ZookeeperConstants.RELEASE_VALUE); - } - - PathNode(final String key, final byte[] value) { - this.nodeKey = key; - this.value = value; - this.path = key; - } - - void attachChild(final PathNode node) { - children.put(node.nodeKey, node); - node.setPath(PathUtil.getRealPath(path, node.getNodeKey())); - } - - PathNode set(final PathResolve pathResolve, final String value) { - if (pathResolve.isEnd()) { - setValue(value.getBytes(ZookeeperConstants.UTF_8)); - return this; - } - pathResolve.next(); - if (children.containsKey(pathResolve.getCurrent())) { - return children.get(pathResolve.getCurrent()).set(pathResolve, value); - } - PathNode result = new PathNode(pathResolve.getCurrent(), ZookeeperConstants.NOTHING_DATA); - this.attachChild(result); - result.set(pathResolve, value); - return result; - } - - PathNode get(final PathResolve pathResolve) { - pathResolve.next(); - if (children.containsKey(pathResolve.getCurrent())) { - if (pathResolve.isEnd()) { - return children.get(pathResolve.getCurrent()); - } - return children.get(pathResolve.getCurrent()).get(pathResolve); - } - return null; - } - - void delete(final PathResolve pathResolve) { - pathResolve.next(); - if (children.containsKey(pathResolve.getCurrent())) { - if (pathResolve.isEnd()) { - children.remove(pathResolve.getCurrent()); - } else { - children.get(pathResolve.getCurrent()).delete(pathResolve); - } - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathResolve.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathResolve.java deleted file mode 100644 index 0d4d1801143b1..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathResolve.java +++ /dev/null @@ -1,78 +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.orchestration.reg.zookeeper.natived.client.cache; - -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -/** - * Path hierarchy resolve. - * - * @author lidongbo - */ -@RequiredArgsConstructor -final class PathResolve { - - @Getter - private final String path; - - @Getter - private String current; - - private int position; - - private boolean ended; - - private long length = -1; - - /** - * Read position Whether the end position or not . - * - * @return isEnd boolean - */ - public boolean isEnd() { - return ended; - } - - private void checkEnd() { - if (length == -1) { - if (path.charAt(path.length() - 1) == '/') { - length = path.length() - 1; - } else { - length = path.length(); - } - } - - ended = position >= length; - } - - /** - * Next path node. - */ - public void next() { - if (isEnd()) { - return; - } - int nodeBegin = ++position; - while (!isEnd() && path.charAt(position) != '/') { - position++; - checkEnd(); - } - current = path.substring(nodeBegin, position); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathStatus.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathStatus.java deleted file mode 100644 index 96332e691c4fb..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathStatus.java +++ /dev/null @@ -1,28 +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.orchestration.reg.zookeeper.natived.client.cache; - -/** - * Path status. - * - * @author lidongbo - */ -public enum PathStatus { - - CHANGING, RELEASE -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathTree.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathTree.java deleted file mode 100644 index 12634e85fc3a3..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathTree.java +++ /dev/null @@ -1,369 +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.orchestration.reg.zookeeper.natived.client.cache; - -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import lombok.Getter; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.locks.ReentrantLock; - -/** - * Zookeeper cache tree. - * - * @author lidongbo - */ -@Slf4j -public final class PathTree implements AutoCloseable { - - private final IClient client; - - private final IProvider provider; - - private final AtomicReference rootNode = new AtomicReference<>(); - - private final List watcherKeys = new ArrayList<>(); - - private final transient ReentrantLock lock = new ReentrantLock(); - - private boolean executorStart; - - private ScheduledExecutorService cacheService; - - @Getter - @Setter - private PathStatus status; - - private boolean closed; - - public PathTree(final String root, final IClient client) { - rootNode.set(new PathNode(root)); - status = PathStatus.RELEASE; - // TODO consider whether to use a new client alternative to the current - this.client = client; - provider = client.getExecStrategy().getProvider(); - } - - /** - * Load data. - * - * @throws KeeperException Zookeeper Exception - * @throws InterruptedException InterruptedException - */ - public void load() throws KeeperException, InterruptedException { - ReentrantLock lock = this.lock; - lock.lockInterruptibly(); - if (closed) { - return; - } - try { - if (status == PathStatus.RELEASE) { - status = PathStatus.CHANGING; - PathNode newRoot = new PathNode(rootNode.get().getNodeKey()); - List children = provider.getChildren(PathUtil.checkPath(rootNode.get().getNodeKey())); - children.remove(ZookeeperConstants.CHANGING_KEY); - attachIntoNode(children, newRoot); - rootNode.set(newRoot); - status = PathStatus.RELEASE; - } else { - try { - Thread.sleep(10L); - } catch (final InterruptedException ex) { - log.error("loading sleep error: {}", ex.getMessage(), ex); - } - load(); - } - } finally { - lock.unlock(); - } - } - - private void attachIntoNode(final List children, final PathNode pathNode) throws KeeperException, InterruptedException { - if (closed) { - return; - } - if (children.isEmpty()) { - return; - } - for (String each : children) { - String childPath = PathUtil.getRealPath(pathNode.getPath(), each); - PathNode current = new PathNode(each, provider.getData(childPath)); - pathNode.attachChild(current); - List subs = provider.getChildren(childPath); - attachIntoNode(subs, current); - } - } - - /** - * Start thread pool period load data. - * - * @param period period - */ - public void refreshPeriodic(final long period) { - ReentrantLock lock = this.lock; - lock.lock(); - if (closed) { - return; - } - try { - Preconditions.checkState(!executorStart, "period already set"); - long threadPeriod = period; - if (threadPeriod < 1) { - threadPeriod = ZookeeperConstants.THREAD_PERIOD; - } - cacheService = Executors.newSingleThreadScheduledExecutor(); - cacheService.scheduleAtFixedRate(new Runnable() { - - @Override - public void run() { - if (PathStatus.RELEASE == getStatus()) { - try { - load(); - } catch (final KeeperException | InterruptedException ex) { - log.error(ex.getMessage(), ex); - } - } - } - }, ZookeeperConstants.THREAD_INITIAL_DELAY, threadPeriod, TimeUnit.MILLISECONDS); - executorStart = true; - Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { - - @Override - public void run() { - stopRefresh(); - } - })); - } finally { - lock.unlock(); - } - } - - /** - * Stop thread pool period load data. - */ - public void stopRefresh() { - cacheService.shutdown(); - executorStart = false; - } - - /** - * Watch data change. - */ - public void watch() { - watch(new ZookeeperEventListener(rootNode.get().getNodeKey()) { - - @Override - public void process(final WatchedEvent event) { - String path = event.getPath(); - switch (event.getType()) { - case NodeCreated: - case NodeDataChanged: - case NodeChildrenChanged: - processNodeChange(path); - break; - case NodeDeleted: - delete(path); - break; - default: - break; - } - } - }); - } - - /** - * Watch data change. - * - * @param zookeeperEventListener listener - */ - public void watch(final ZookeeperEventListener zookeeperEventListener) { - if (closed) { - return; - } - String key = zookeeperEventListener.getKey(); - client.registerWatch(rootNode.get().getNodeKey(), zookeeperEventListener); - watcherKeys.add(key); - } - - private void processNodeChange(final String path) { - try { - String value = provider.getDataString(path); - put(path, value); - } catch (final KeeperException | InterruptedException ex) { - if (ex instanceof KeeperException.NoNodeException || ex instanceof KeeperException.ConnectionLossException) { - log.debug(ex.getMessage()); - return; - } - log.error("PathTree put error : " + ex.getMessage()); - } - } - - /** - * Get node value. - * - * @param path path - * @return node data - */ - public byte[] getValue(final String path) { - if (closed) { - return null; - } - PathNode node = get(path); - return null == node ? null : node.getValue(); - } - - /** - * Get children. - * - * @param path path - * @return children - */ - public List getChildren(final String path) { - if (closed) { - return null; - } - PathNode node = get(path); - List result = new ArrayList<>(); - if (node == null) { - return result; - } - if (node.getChildren().isEmpty()) { - return result; - } - for (final PathNode pathNode : node.getChildren().values()) { - result.add(new String(pathNode.getValue())); - } - return result; - } - - private PathNode get(final String path) { - if (Strings.isNullOrEmpty(path) || path.equals(ZookeeperConstants.PATH_SEPARATOR)) { - return rootNode.get(); - } - String realPath = provider.getRealPath(path); - PathResolve pathResolve = new PathResolve(realPath); - pathResolve.next(); - if (pathResolve.isEnd()) { - return rootNode.get(); - } - return rootNode.get().get(pathResolve); - } - - /** - * Put node. - * - * @param path path - * @param value value - */ - public void put(final String path, final String value) { - ReentrantLock lock = this.lock; - lock.lock(); - if (closed) { - return; - } - try { - if (status == PathStatus.RELEASE) { - setStatus(PathStatus.CHANGING); - String realPath = provider.getRealPath(path); - PathResolve pathResolve = new PathResolve(realPath); - pathResolve.next(); - rootNode.get().set(pathResolve, value); - setStatus(PathStatus.RELEASE); - } else { - try { - Thread.sleep(10L); - } catch (final InterruptedException ex) { - log.error("put sleep error:{}", ex.getMessage(), ex); - } - put(path, value); - } - } finally { - lock.unlock(); - } - } - - /** - * Delete node. - * - * @param path path - */ - public void delete(final String path) { - ReentrantLock lock = this.lock; - lock.lock(); - if (closed) { - return; - } - try { - if (rootNode.get().getChildren().containsKey(path)) { - rootNode.get().getChildren().remove(path); - return; - } - String realPath = provider.getRealPath(path); - PathResolve pathResolve = new PathResolve(realPath); - pathResolve.next(); - rootNode.get().delete(pathResolve); - } finally { - lock.unlock(); - } - } - - @Override - public void close() { - ReentrantLock lock = this.lock; - lock.lock(); - closed = true; - try { - if (executorStart) { - stopRefresh(); - } - deleteAllChildren(rootNode.get()); - if (!watcherKeys.isEmpty()) { - for (String each : watcherKeys) { - client.unregisterWatch(each); - } - } - } finally { - lock.unlock(); - } - } - - private void deleteAllChildren(final PathNode node) { - if (node.getChildren().isEmpty()) { - return; - } - for (String each : node.getChildren().keySet()) { - deleteAllChildren(node.getChildren().get(each)); - node.getChildren().remove(each); - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/election/LeaderElection.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/election/LeaderElection.java deleted file mode 100644 index 4ee4bdea03707..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/election/LeaderElection.java +++ /dev/null @@ -1,122 +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.orchestration.reg.zookeeper.natived.client.election; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.WatcherCreator; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; - -/** - * Competition of node write permission. - * It is not recommended to be used as a global variable. - * - * @author lidongbo - */ -@Slf4j -public abstract class LeaderElection { - - private int retryCount = ZookeeperConstants.NODE_ELECTION_RETRY; - - private boolean done; - - /** - * Listener will be register when the contention of the path is unsuccessful. - * - * @param nodeBeContend node be contend - * @param provider provider - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - public void executeContention(final String nodeBeContend, final IProvider provider) throws KeeperException, InterruptedException { - boolean canBegin; - final String realNode = provider.getRealPath(nodeBeContend); - String contendNode = PathUtil.getRealPath(realNode, ZookeeperConstants.CHANGING_KEY); - canBegin = contend(contendNode, provider, new ZookeeperEventListener(contendNode) { - - @Override - public void process(final WatchedEvent event) { - try { - retryCount--; - if (retryCount < 0) { - return; - } - executeContention(realNode, provider); - } catch (final KeeperException | InterruptedException ex) { - log.error("Listener Exception executeContention:{}", ex.getMessage(), ex); - } - } - }); - if (canBegin) { - try { - action(); - done = true; - callback(); - } catch (final KeeperException | InterruptedException ex) { - log.error("action Exception executeContention:{}", ex.getMessage(), ex); - } - provider.delete(contendNode); - } - } - - private boolean contend(final String node, final IProvider provider, final ZookeeperEventListener zookeeperEventListener) throws KeeperException, InterruptedException { - boolean result = false; - try { - // TODO EPHEMERAL_SEQUENTIAL check index value - provider.create(node, ZookeeperConstants.CLIENT_ID, CreateMode.EPHEMERAL); - result = true; - } catch (final KeeperException.NodeExistsException ex) { - log.info("contend not result"); - // TODO or changing_key node value == current client id - provider.exists(node, WatcherCreator.deleteWatcher(zookeeperEventListener)); - } - return result; - } - - /** - * Wait done. - */ - public void waitDone() { - while (!done) { - try { - Thread.sleep(10L); - } catch (final InterruptedException ex) { - log.error("waitDone:{}", ex.getMessage(), ex); - } - } - } - - /** - * Contend execute. - * - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - public abstract void action() throws KeeperException, InterruptedException; - - /** - * Callback. - */ - public void callback() { - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/AsyncRetryCenter.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/AsyncRetryCenter.java deleted file mode 100644 index a2b21f2f70238..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/AsyncRetryCenter.java +++ /dev/null @@ -1,74 +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.orchestration.reg.zookeeper.natived.client.retry; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseOperation; - -import java.util.concurrent.DelayQueue; - -/** - * Async retry center. - * - * @author lidongbo - */ -public enum AsyncRetryCenter { - - INSTANCE; - - private final DelayQueue queue = new DelayQueue<>(); - - private final RetryThread retryThread = new RetryThread(queue); - - private boolean started; - - private DelayRetryPolicy delayRetryPolicy; - - /** - * Initialize. - * - * @param delayRetryPolicy delay retry policy - */ - public void init(final DelayRetryPolicy delayRetryPolicy) { - this.delayRetryPolicy = null == delayRetryPolicy ? DelayRetryPolicy.defaultDelayPolicy() : delayRetryPolicy; - } - - /** - * start. - */ - public synchronized void start() { - if (started) { - return; - } - retryThread.setName("retry-thread"); - retryThread.start(); - started = true; - } - - /** - * add async operation. - * - * @param operation operation - */ - public void add(final BaseOperation operation) { - if (null == delayRetryPolicy) { - delayRetryPolicy = DelayRetryPolicy.defaultDelayPolicy(); - } - operation.setDelayPolicyExecutor(new DelayPolicyExecutor(delayRetryPolicy)); - queue.offer(operation); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/DelayPolicyExecutor.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/DelayPolicyExecutor.java deleted file mode 100644 index ade08f607f959..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/DelayPolicyExecutor.java +++ /dev/null @@ -1,70 +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.orchestration.reg.zookeeper.natived.client.retry; - -import lombok.RequiredArgsConstructor; - -import java.util.Random; - -/** - * Delay policy executor. - * - * @author lidongbo - */ -@RequiredArgsConstructor -public final class DelayPolicyExecutor { - - private final DelayRetryPolicy delayRetryPolicy; - - private final Random random = new Random(); - - private int executeCount; - - private long executeTick = System.currentTimeMillis(); - - /** - * Has next. - * - * @return has next - */ - public boolean hasNext() { - return executeCount < delayRetryPolicy.getRetryCount(); - } - - /** - * Next execute tick. - * - * @return next execute tick - */ - public long getNextTick() { - return executeTick; - } - - /** - * Next. - */ - public void next() { - executeCount++; - long sleep = delayRetryPolicy.getBaseDelay() * Math.max(1, this.random.nextInt(1 << delayRetryPolicy.getRetryCount() + 1)); - if (sleep < delayRetryPolicy.getDelayUpperBound()) { - executeTick += sleep; - } else { - executeTick += delayRetryPolicy.getDelayUpperBound(); - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/DelayRetryPolicy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/DelayRetryPolicy.java deleted file mode 100644 index 0187fc21b0d8c..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/DelayRetryPolicy.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.orchestration.reg.zookeeper.natived.client.retry; - -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -/** - * Delay policy. - * - * @author lidongbo - */ -@RequiredArgsConstructor -@Getter -public class DelayRetryPolicy { - - private static final long BASE_DELAY = 10; - - private static final int BASE_COUNT = 3; - - private static final int RETRY_COUNT_BOUND = 29; - - private final int retryCount; - - private final long baseDelay; - - private final long delayUpperBound; - - public DelayRetryPolicy(final long baseDelay) { - this(RETRY_COUNT_BOUND, baseDelay, Integer.MAX_VALUE); - } - - /** - * Default delay policy. - * - * @return delay policy - */ - public static DelayRetryPolicy defaultDelayPolicy() { - return new DelayRetryPolicy(BASE_COUNT, BASE_DELAY, Integer.MAX_VALUE); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryCallable.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryCallable.java deleted file mode 100644 index ded980ce40c8a..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryCallable.java +++ /dev/null @@ -1,82 +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.orchestration.reg.zookeeper.natived.client.retry; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.Connection; -import lombok.AccessLevel; -import lombok.Getter; -import org.apache.zookeeper.KeeperException; - -/** - * Sync retry call. - * - * @author lidongbo - */ -@Getter(value = AccessLevel.PROTECTED) -public abstract class RetryCallable { - - private final IProvider provider; - - private final DelayPolicyExecutor delayPolicyExecutor; - - public RetryCallable(final IProvider provider, final DelayRetryPolicy delayRetryPolicy) { - this.provider = provider; - delayPolicyExecutor = new DelayPolicyExecutor(delayRetryPolicy); - } - - /** - * Call the action. - * - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - public abstract void call() throws KeeperException, InterruptedException; - - /** - * Call without result. - * - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - public void exec() throws KeeperException, InterruptedException { - try { - call(); - } catch (final KeeperException ex) { - delayPolicyExecutor.next(); - if (Connection.needReset(ex)) { - provider.resetConnection(); - } - execDelay(); - } - } - - private void execDelay() throws KeeperException, InterruptedException { - for (;;) { - long delay = delayPolicyExecutor.getNextTick() - System.currentTimeMillis(); - if (delay > 0) { - Thread.sleep(delay); - } else { - if (delayPolicyExecutor.hasNext()) { - exec(); - } - break; - } - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryResultCallable.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryResultCallable.java deleted file mode 100644 index 5f0570e86b28f..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryResultCallable.java +++ /dev/null @@ -1,51 +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.orchestration.reg.zookeeper.natived.client.retry; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import lombok.Setter; -import org.apache.zookeeper.KeeperException; - -/** - * Sync retry call with result. - * - * @author lidongbo - */ -public abstract class RetryResultCallable extends RetryCallable { - - @Setter - private T result; - - public RetryResultCallable(final IProvider provider, final DelayRetryPolicy delayRetryPolicy) { - super(provider, delayRetryPolicy); - } - - /** - * Get result. - * - * @return result - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - public T getResult() throws KeeperException, InterruptedException { - if (null == result) { - exec(); - } - return result; - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryThread.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryThread.java deleted file mode 100644 index 3b1ffba5fa7d0..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/RetryThread.java +++ /dev/null @@ -1,114 +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.orchestration.reg.zookeeper.natived.client.retry; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseOperation; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.KeeperException; - -import java.util.concurrent.DelayQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Async retry. - * - * @author lidongbo - */ -@Slf4j -public final class RetryThread extends Thread { - - private final int corePoolSize = Runtime.getRuntime().availableProcessors(); - - private final int maximumPoolSize = corePoolSize; - - private final long keepAliveTime = 0; - - private final int closeDelay = 60; - - private final DelayQueue queue; - - private final ThreadPoolExecutor retryExecutor; - - public RetryThread(final DelayQueue queue) { - this.queue = queue; - retryExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(10), new ThreadFactory() { - - private final AtomicInteger threadIndex = new AtomicInteger(0); - - @Override - public Thread newThread(final Runnable runnable) { - Thread thread = new Thread(runnable); - thread.setDaemon(true); - thread.setName("zk-retry-" + threadIndex.incrementAndGet()); - return thread; - } - }); - addDelayedShutdownHook(retryExecutor, closeDelay, TimeUnit.SECONDS); - } - - @Override - public void run() { - for (;;) { - final BaseOperation operation; - try { - operation = queue.take(); - } catch (final InterruptedException ex) { - log.error("retry interrupt ex: {}", ex.getMessage()); - continue; - } - retryExecutor.submit(new Runnable() { - - @Override - public void run() { - boolean result; - try { - result = operation.executeOperation(); - } catch (final KeeperException | InterruptedException ex) { - result = false; - log.error("retry disrupt operation: {}, ex: {}", operation.toString(), ex.getMessage()); - } - if (result) { - queue.offer(operation); - } - } - }); - } - } - - private void addDelayedShutdownHook(final ExecutorService service, final long terminationTimeout, final TimeUnit timeUnit) { - Thread thread = new Thread(new Runnable() { - - @Override - public void run() { - try { - queue.clear(); - service.shutdown(); - service.awaitTermination(terminationTimeout, timeUnit); - } catch (final InterruptedException ignored) { - } - } - }); - thread.setName("retry shutdown hook"); - Runtime.getRuntime().addShutdownHook(thread); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/utility/PathUtil.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/utility/PathUtil.java deleted file mode 100644 index 8aa5baaa04bbe..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/utility/PathUtil.java +++ /dev/null @@ -1,192 +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.orchestration.reg.zookeeper.natived.client.utility; - -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; - -import java.util.ArrayList; -import java.util.List; -import java.util.Stack; - -/** - * Path util. - * - * @author lidongbo - */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class PathUtil { - - /** - * Get real path. - * - * @param root root - * @param path path - * @return real path - */ - public static String getRealPath(final String root, final String path) { - return adjustPath(root, path); - } - - private static String adjustPath(final String root, final String path) { - if (Strings.isNullOrEmpty(path)) { - throw new IllegalArgumentException("path should have content!"); - } - String rootPath = root; - if (!root.startsWith(ZookeeperConstants.PATH_SEPARATOR)) { - rootPath = ZookeeperConstants.PATH_SEPARATOR + root; - } - String realPath = path; - if (!path.startsWith(ZookeeperConstants.PATH_SEPARATOR)) { - realPath = ZookeeperConstants.PATH_SEPARATOR + path; - } - if (!realPath.startsWith(rootPath)) { - return rootPath + realPath; - } - return realPath; - } - - /** - * Get path nodes, child to root. - * - * @param root root - * @param path path - * @return all path nodes - */ - public static Stack getPathReverseNodes(final String root, final String path) { - String realPath = adjustPath(root, path); - Stack pathStack = new Stack<>(); - int index = 1; - int position = realPath.indexOf(ZookeeperConstants.PATH_SEPARATOR, index); - do { - pathStack.push(realPath.substring(0, position)); - index = position + 1; - position = realPath.indexOf(ZookeeperConstants.PATH_SEPARATOR, index); - } - while (position > -1); - pathStack.push(realPath); - return pathStack; - } - - /** - * Get path nodes. - * - * @param root root - * @param path path - * @return all path nodes - */ - public static List getPathOrderNodes(final String root, final String path) { - String realPath = adjustPath(root, path); - List paths = new ArrayList<>(); - int index = 1; - int position = realPath.indexOf(ZookeeperConstants.PATH_SEPARATOR, index); - - do { - paths.add(realPath.substring(0, position)); - index = position + 1; - position = realPath.indexOf(ZookeeperConstants.PATH_SEPARATOR, index); - } - while (position > -1); - paths.add(realPath); - return paths; - } - - /** - * Get path nodes. - * - * @param path path - * @return all path nodes - */ - public static List getShortPathNodes(final String path) { - String realPath = checkPath(path); - List paths = new ArrayList<>(); - char[] chars = realPath.toCharArray(); - StringBuilder builder = new StringBuilder(ZookeeperConstants.PATH_SEPARATOR); - for (int i = 1; i < chars.length; i++) { - if (chars[i] == ZookeeperConstants.PATH_SEPARATOR.charAt(0)) { - paths.add(builder.toString()); - builder = new StringBuilder(ZookeeperConstants.PATH_SEPARATOR); - continue; - } - builder.append(chars[i]); - if (i == chars.length - 1) { - paths.add(builder.toString()); - } - } - return paths; - } - - /** - * Ignore invalid char and // /./ /../. - * code consult zookeeper - * - * @param key key - * @return real path - * @throws IllegalArgumentException IllegalArgumentException - */ - // CHECKSTYLE:OFF - public static String checkPath(final String key) { - // CHECKSTYLE:ON - Preconditions.checkNotNull(key, "path should not be null"); - - String path = key; - if (path.charAt(0) != 47 || path.charAt(path.length() - 1) == 47) { - path = ZookeeperConstants.PATH_SEPARATOR + path; - } - - if (path.charAt(path.length() - 1) == 47) { - path = ZookeeperConstants.PATH_SEPARATOR + path; - } - - char previous = 47; - char[] chars = path.toCharArray(); - StringBuilder builder = new StringBuilder(); - builder.append(previous); - - for (int i = 1; i < chars.length; ++i) { - char c = chars[i]; - if (c == 0 || (c == 47 && previous == 47)) { - continue; - } - if (c == 46) { - // ignore /./ /../ - boolean preWarn = previous == 47 || (previous == 46 && chars[i - 2] == 47); - if (previous == 47 && (i + 1 == chars.length || chars[i + 1] == 47)) { - // CHECKSTYLE:OFF - i++; - continue; - } - if ((previous == 46 && chars[i - 2] == 47) && (i + 1 == chars.length || chars[i + 1] == 47)) { - i += 2; - continue; - } - } - - if (c > 0 && c < 31 || c > 127 && c < 159 || c > '\ud800' && c < '\uf8ff' || c > '\ufff0' && c < '\uffff') { - // CHECKSTYLE:ON - continue; - } - - builder.append(c); - previous = c; - } - return builder.toString(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/utility/ZookeeperConstants.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/utility/ZookeeperConstants.java deleted file mode 100644 index 84de60548c1fb..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/utility/ZookeeperConstants.java +++ /dev/null @@ -1,64 +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.orchestration.reg.zookeeper.natived.client.utility; - -import lombok.AccessLevel; -import lombok.NoArgsConstructor; - -import java.nio.charset.Charset; - -/** - * Zookeeper client constants. - * - * @author lidongbo - */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class ZookeeperConstants { - - public static final int VERSION = -1; - - public static final int WAIT = 60 * 1000; - - public static final byte[] NOTHING_DATA = new byte[0]; - - public static final String NOTHING_VALUE = ""; - - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - public static final String PATH_SEPARATOR = "/"; - - public static final String GLOBAL_LISTENER_KEY = "globalListener"; - - public static final String ROOT_INIT_PATH = "/InitValue"; - - public static final byte[] CHANGING_VALUE = new byte[]{'c'}; - - public static final byte[] RELEASE_VALUE = new byte[]{'r'}; - - public static final String CHANGING_KEY = "CHANGING_KEY"; - - public static final long THREAD_PERIOD = 3000L; - - public static final long THREAD_INITIAL_DELAY = 1000L; - - public static final int NODE_ELECTION_RETRY = 3; - - public static final String CLIENT_ID = "1"; - - public static final boolean WATCHED = true; -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/CacheClient.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/CacheClient.java deleted file mode 100644 index 37e2a9a7ced12..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/CacheClient.java +++ /dev/null @@ -1,125 +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.orchestration.reg.zookeeper.natived.client.zookeeper; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.cache.CacheStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.cache.PathTree; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseContext; -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; - -import java.io.IOException; -import java.util.List; - -/** - * Cache Client. - * - * @author lidongbo - */ -// TODO Partially prepared product -public final class CacheClient extends UsualClient { - - private PathTree pathTree; - - CacheClient(final BaseContext context) { - super(context); - } - - @Override - public void start() throws IOException, InterruptedException { - super.start(); - try { - useCacheStrategy(CacheStrategy.WATCH); - } catch (final KeeperException ignored) { - } - } - - @Override - public void close() { - super.close(); - pathTree.close(); - } - - //todo put it here? - private void useCacheStrategy(final CacheStrategy cacheStrategy) throws KeeperException, InterruptedException { - switch (cacheStrategy) { - case WATCH: - pathTree = new PathTree(getRootNode(), this); - pathTree.watch(); - break; - case ALL: - pathTree = loadPathTree(); - pathTree.refreshPeriodic(ZookeeperConstants.THREAD_PERIOD); - break; - case NONE: - default: - } - } - - private PathTree loadPathTree() throws KeeperException, InterruptedException { - return loadPathTree(getRootNode()); - } - - private PathTree loadPathTree(final String treeRoot) throws KeeperException, InterruptedException { - PathTree result = new PathTree(treeRoot, this); - result.load(); - result.watch(); - return result; - } - - @Override - public void createCurrentOnly(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - super.createCurrentOnly(key, value, createMode); - pathTree.put(PathUtil.getRealPath(getRootNode(), key), value); - } - - @Override - public void deleteOnlyCurrent(final String key) throws KeeperException, InterruptedException { - super.deleteOnlyCurrent(key); - pathTree.delete(PathUtil.getRealPath(getRootNode(), key)); - } - - @Override - public void deleteOnlyCurrent(final String key, final AsyncCallback.VoidCallback callback, final Object ctx) throws KeeperException, InterruptedException { - super.deleteOnlyCurrent(key, callback, ctx); - pathTree.delete(PathUtil.getRealPath(getRootNode(), key)); - } - - @Override - public byte[] getData(final String key) throws KeeperException, InterruptedException { - String path = PathUtil.getRealPath(getRootNode(), key); - byte[] data = pathTree.getValue(path); - if (null != data) { - return data; - } - return getExecStrategy().getData(key); - } - - @Override - public List getChildren(final String key) throws KeeperException, InterruptedException { - String path = PathUtil.getRealPath(getRootNode(), key); - List keys = pathTree.getChildren(path); - if (keys != null && !keys.isEmpty()) { - return keys; - } - return getExecStrategy().getChildren(PathUtil.getRealPath(getRootNode(), key)); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/ClientFactory.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/ClientFactory.java deleted file mode 100644 index b4e208e2346c2..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/ClientFactory.java +++ /dev/null @@ -1,131 +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.orchestration.reg.zookeeper.natived.client.zookeeper; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.DelayRetryPolicy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseClientFactory; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ClientContext; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import org.apache.zookeeper.data.ACL; - -import java.io.IOException; -import java.util.List; - -/** - * Client factory. - * - * @author lidongbo - */ -public final class ClientFactory extends BaseClientFactory { - - private DelayRetryPolicy delayRetryPolicy; - - /** - * Create a new client. - * - * @param servers servers - * @param sessionTimeoutMilliseconds session timeout milliseconds - * @return ClientFactory this - */ - public ClientFactory newClient(final String servers, final int sessionTimeoutMilliseconds) { - int wait = sessionTimeoutMilliseconds; - if (sessionTimeoutMilliseconds == 0) { - wait = ZookeeperConstants.WAIT; - } - setContext(new ClientContext(servers, wait)); - setClient(new UsualClient(getContext())); - return this; - } - - /* - * Used for create new clients through a existing client. - * This client is not perhaps the client. - */ - synchronized BaseClientFactory newClientByOriginal(final boolean closeOriginal) { - IClient oldClient = getClient(); - setClient(new UsualClient(getContext())); - if (closeOriginal) { - oldClient.close(); - } - return this; - } - - ClientFactory newCacheClient(final String servers, final int sessionTimeoutMilliseconds) { - setContext(new ClientContext(servers, sessionTimeoutMilliseconds)); - setClient(new CacheClient(getContext())); - return this; - } - - /** - * Wait to register global listener. - * - * @param globalZookeeperEventListener global listener - * @return client factory - */ - public ClientFactory watch(final ZookeeperEventListener globalZookeeperEventListener) { - setGlobalZookeeperEventListener(globalZookeeperEventListener); - return this; - } - - /** - * Set client namespace. - * - * @param namespace namespace - * @return client factory - */ - public ClientFactory setClientNamespace(final String namespace) { - setNamespace(PathUtil.checkPath(namespace)); - return this; - } - - /** - * Authorization. - * - * @param scheme scheme - * @param auth auth - * @param authorities authorities - * @return client factory - */ - public ClientFactory authorization(final String scheme, final byte[] auth, final List authorities) { - setScheme(scheme); - setAuth(auth); - setAuthorities(authorities); - return this; - } - - /** - * Set delay retry policy. - * - * @param delayRetryPolicy delay retry policy - * @return client factory - */ - public ClientFactory setRetryPolicy(final DelayRetryPolicy delayRetryPolicy) { - this.delayRetryPolicy = delayRetryPolicy; - return this; - } - - @Override - public IClient start() throws IOException, InterruptedException { - ((ClientContext) getContext()).setDelayRetryPolicy(delayRetryPolicy); - ((ClientContext) getContext()).setClientFactory(this); - return super.start(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/UsualClient.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/UsualClient.java deleted file mode 100644 index f6bd9593dbc7c..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/UsualClient.java +++ /dev/null @@ -1,189 +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.orchestration.reg.zookeeper.natived.client.zookeeper; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IExecStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.ITransactionProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseContext; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.provider.TransactionProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ClientContext; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.StrategyType; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.AsyncRetryStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.ContentionStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.SyncRetryStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.TransactionContendStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.UsualStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; -import lombok.Getter; -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.Watcher; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Usually use client. - * - * @author lidongbo - */ -public class UsualClient extends BaseClient { - - private final Map strategies = new ConcurrentHashMap<>(); - - @Getter - private IExecStrategy execStrategy; - - protected UsualClient(final BaseContext context) { - super(context); - } - - @Override - public void close() { - strategies.clear(); - super.close(); - } - - @Override - public synchronized void useExecStrategy(final StrategyType strategyType) { - if (strategies.containsKey(strategyType)) { - execStrategy = strategies.get(strategyType); - return; - } - - ITransactionProvider provider = new TransactionProvider(getRootNode(), getHolder(), ZookeeperConstants.WATCHED, getAuthorities()); - switch (strategyType) { - case USUAL: - execStrategy = new UsualStrategy(provider); - break; - case CONTEND: - execStrategy = new ContentionStrategy(provider); - break; - case TRANSACTION_CONTEND: - execStrategy = new TransactionContendStrategy(provider); - break; - case SYNC_RETRY: - execStrategy = new SyncRetryStrategy(provider, ((ClientContext) getContext()).getDelayRetryPolicy()); - break; - case ASYNC_RETRY: - execStrategy = new AsyncRetryStrategy(provider, ((ClientContext) getContext()).getDelayRetryPolicy()); - break; - default: - execStrategy = new UsualStrategy(provider); - break; - } - - strategies.put(strategyType, execStrategy); - } - - @Override - public String getDataString(final String key) throws KeeperException, InterruptedException { - return execStrategy.getDataString(key); - } - - @Override - public byte[] getData(final String key) throws KeeperException, InterruptedException { - return execStrategy.getData(key); - } - - @Override - public void getData(final String key, final AsyncCallback.DataCallback callback, final Object ctx) throws KeeperException, InterruptedException { - execStrategy.getData(key, callback, ctx); - } - - @Override - public boolean checkExists(final String key) throws KeeperException, InterruptedException { - return execStrategy.checkExists(key); - } - - @Override - public boolean checkExists(final String key, final Watcher watcher) throws KeeperException, InterruptedException { - return execStrategy.checkExists(key, watcher); - } - - @Override - public List getChildren(final String key) throws KeeperException, InterruptedException { - return execStrategy.getChildren(key); - } - - @Override - public void createCurrentOnly(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - createNamespace(); - if (getRootNode().equals(key)) { - return; - } - execStrategy.createCurrentOnly(key, value, createMode); - } - - @Override - public void createAllNeedPath(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - createNamespace(); - if (getRootNode().equals(key)) { - return; - } - execStrategy.createAllNeedPath(key, value, createMode); - } - - @Override - public void update(final String key, final String value) throws KeeperException, InterruptedException { - execStrategy.update(key, value); - } - - @Override - public void deleteOnlyCurrent(final String key) throws KeeperException, InterruptedException { - if (getRootNode().equals(key)) { - deleteNamespace(); - return; - } - execStrategy.deleteOnlyCurrent(key); - } - - @Override - public void deleteOnlyCurrent(final String key, final AsyncCallback.VoidCallback callback, final Object ctx) throws KeeperException, InterruptedException { - if (getRootNode().equals(key)) { - deleteNamespace(); - return; - } - execStrategy.deleteOnlyCurrent(key, callback, ctx); - } - - @Override - public void deleteAllChildren(final String key) throws KeeperException, InterruptedException { - execStrategy.deleteAllChildren(key); - if (getRootNode().equals(key)) { - setRootExist(false); - } - } - - @Override - public void deleteCurrentBranch(final String key) throws KeeperException, InterruptedException { - execStrategy.deleteCurrentBranch(key); - if (!execStrategy.checkExists(getRootNode())) { - setRootExist(false); - } - } - - @Override - public BaseTransaction transaction() { - return execStrategy.transaction(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClient.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClient.java deleted file mode 100644 index ad672a6b07b6e..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClient.java +++ /dev/null @@ -1,181 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import com.google.common.base.Strings; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.StrategyType; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.WatcherCreator; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.data.ACL; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** - * Base client. - * - * @author lidongbo - */ -@Slf4j -public abstract class BaseClient implements IClient { - - private static final int CIRCLE_WAIT = 30; - - @Getter(value = AccessLevel.PROTECTED) - private List authorities; - - // false - @Setter(value = AccessLevel.PROTECTED) - private boolean rootExist; - - @Getter(value = AccessLevel.PROTECTED) - @Setter(value = AccessLevel.PROTECTED) - private Holder holder; - - @Setter(value = AccessLevel.PROTECTED) - @Getter(value = AccessLevel.PROTECTED) - private String rootNode = ZookeeperConstants.ROOT_INIT_PATH; - - @Getter(value = AccessLevel.PROTECTED) - private BaseContext context; - - protected BaseClient(final BaseContext context) { - this.context = context; - } - - @Override - public void start() throws IOException, InterruptedException { - prepareStart(); - holder.start(); - } - - @Override - public synchronized boolean start(final int waitingTime, final TimeUnit timeUnit) throws InterruptedException, IOException { - prepareStart(); - holder.start(waitingTime, timeUnit); - return holder.isConnected(); - } - - private void prepareStart() { - holder = new Holder(getContext()); - useExecStrategy(StrategyType.USUAL); - } - - @Override - public synchronized boolean blockUntilConnected(final int waitingTime, final TimeUnit timeUnit) throws InterruptedException { - long maxWait = timeUnit != null ? TimeUnit.MILLISECONDS.convert(waitingTime, timeUnit) : 0; - while (!holder.isConnected()) { - long waitTime = maxWait - CIRCLE_WAIT; - if (waitTime <= 0) { - return holder.isConnected(); - } - wait(CIRCLE_WAIT); - } - return true; - } - - @Override - public void close() { - context.close(); - try { - if (rootExist) { - this.deleteNamespace(); - } - } catch (final KeeperException | InterruptedException ex) { - log.error("zk client close delete root error:{}", ex.getMessage(), ex); - } - holder.close(); - } - - void registerWatch(final ZookeeperEventListener globalZookeeperEventListener) { - if (context.getGlobalZookeeperEventListener() != null) { - log.warn("global listener can only register one"); - return; - } - context.setGlobalZookeeperEventListener(globalZookeeperEventListener); - } - - @Override - public final void registerWatch(final String key, final ZookeeperEventListener zookeeperEventListener) { - final String path = PathUtil.getRealPath(rootNode, key); - zookeeperEventListener.setPath(path); - context.getWatchers().put(zookeeperEventListener.getKey(), zookeeperEventListener); - } - - @Override - public final void unregisterWatch(final String key) { - if (Strings.isNullOrEmpty(key)) { - throw new IllegalArgumentException("key should not be blank"); - } - if (context.getWatchers().containsKey(key)) { - context.getWatchers().remove(key); - } - } - - protected void createNamespace() throws KeeperException, InterruptedException { - createNamespace(ZookeeperConstants.NOTHING_DATA); - } - - private void createNamespace(final byte[] date) throws KeeperException, InterruptedException { - if (rootExist) { - return; - } - try { - if (null == holder.getZooKeeper().exists(rootNode, false)) { - holder.getZooKeeper().create(rootNode, date, authorities, CreateMode.PERSISTENT); - } - rootExist = true; - } catch (final KeeperException.NodeExistsException ex) { - rootExist = true; - return; - } - holder.getZooKeeper().exists(rootNode, WatcherCreator.deleteWatcher(new ZookeeperEventListener(rootNode) { - - @Override - public void process(final WatchedEvent event) { - rootExist = false; - } - })); - } - - protected final void deleteNamespace() throws KeeperException, InterruptedException { - try { - holder.getZooKeeper().delete(rootNode, ZookeeperConstants.VERSION); - } catch (final KeeperException.NodeExistsException | KeeperException.NotEmptyException ex) { - log.info("delete root :{}", ex.getMessage()); - } - rootExist = false; - } - - final void setAuthorities(final String scheme, final byte[] auth, final List authorities) { - context.setScheme(scheme); - context.setAuth(auth); - this.authorities = authorities; - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClientFactory.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClientFactory.java deleted file mode 100644 index c828f56da3d70..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClientFactory.java +++ /dev/null @@ -1,98 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.Setter; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.ZooDefs; -import org.apache.zookeeper.data.ACL; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** - * Base client factory. - * - * @author lidongbo - */ -@Setter(value = AccessLevel.PROTECTED) -@Getter(value = AccessLevel.PROTECTED) -public abstract class BaseClientFactory { - - private BaseClient client; - - private ZookeeperEventListener globalZookeeperEventListener; - - private String namespace; - - private String scheme; - - private byte[] auth; - - private List authorities; - - private BaseContext context; - - /** - * Start. - * - * @return client - * @throws IOException IO Exception - * @throws InterruptedException InterruptedException - */ - public IClient start() throws IOException, InterruptedException { - prepareClient(); - client.start(); - return client; - } - - /** - * Start until Timeout. - * - * @param waitingTime waiting time - * @param timeUnit time unit - * @return connected or not - * @throws IOException IO Exception - * @throws InterruptedException interrupted exception - * @throws KeeperException operation timeout exception - */ - public IClient start(final int waitingTime, final TimeUnit timeUnit) throws IOException, InterruptedException, KeeperException { - prepareClient(); - if (!client.start(waitingTime, timeUnit)) { - client.close(); - throw new KeeperException.OperationTimeoutException(); - } - return client; - } - - private void prepareClient() { - client.setRootNode(namespace); - if (null == scheme) { - authorities = ZooDefs.Ids.OPEN_ACL_UNSAFE; - } - client.setAuthorities(scheme, auth, authorities); - if (null != globalZookeeperEventListener) { - client.registerWatch(globalZookeeperEventListener); - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseContext.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseContext.java deleted file mode 100644 index 33a428305e03b..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseContext.java +++ /dev/null @@ -1,55 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.Setter; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Base context. - * - * @author lidongbo - */ -@Getter -@Setter(value = AccessLevel.PROTECTED) -public abstract class BaseContext { - - private String servers; - - private int sessionTimeOut; - - private String scheme; - - private byte[] auth; - - private ZookeeperEventListener globalZookeeperEventListener; - - private final Map watchers = new ConcurrentHashMap<>(); - - /** - * Close. - */ - public void close() { - watchers.clear(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseOperation.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseOperation.java deleted file mode 100644 index 350eec4f91211..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseOperation.java +++ /dev/null @@ -1,82 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.DelayPolicyExecutor; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.Connection; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.Setter; -import org.apache.zookeeper.KeeperException; - -import java.util.concurrent.Delayed; -import java.util.concurrent.TimeUnit; - -/** - * Base async retry operation. - * - * @author lidongbo - */ -@RequiredArgsConstructor -public abstract class BaseOperation implements Delayed { - - @Getter - private final IProvider provider; - - @Setter - private DelayPolicyExecutor delayPolicyExecutor; - - @Override - public final long getDelay(final TimeUnit timeUnit) { - long absoluteBlock = this.delayPolicyExecutor.getNextTick() - System.currentTimeMillis(); - return timeUnit.convert(absoluteBlock, TimeUnit.MILLISECONDS); - } - - @Override - public final int compareTo(final Delayed delayed) { - return (int) (this.getDelay(TimeUnit.MILLISECONDS) - delayed.getDelay(TimeUnit.MILLISECONDS)); - } - - protected abstract void execute() throws KeeperException, InterruptedException; - - /** - * Queue precedence. - * - * @return whether or not continue enqueue - * @throws KeeperException keeper exception - * @throws InterruptedException interrupted exception - */ - public boolean executeOperation() throws KeeperException, InterruptedException { - boolean result; - try { - execute(); - result = true; - } catch (final KeeperException ex) { - if (Connection.needReset(ex)) { - provider.resetConnection(); - } - result = false; - } - if (!result && delayPolicyExecutor.hasNext()) { - delayPolicyExecutor.next(); - return true; - } - return false; - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/Holder.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/Holder.java deleted file mode 100644 index 5ee67a3d16af2..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/Holder.java +++ /dev/null @@ -1,172 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import com.google.common.base.Strings; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.ZooKeeper; - -import java.io.IOException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Zookeeper connection holder. - * - * @author lidongbo - */ -@RequiredArgsConstructor -@Getter -@Slf4j -public class Holder { - - private final CountDownLatch connectLatch = new CountDownLatch(1); - - @Getter(value = AccessLevel.PROTECTED) - private final BaseContext context; - - private ZooKeeper zooKeeper; - - @Setter(value = AccessLevel.PROTECTED) - private boolean connected; - - /** - * Start. - * - * @throws IOException IO exception - * @throws InterruptedException interrupted exception - */ - public void start() throws IOException, InterruptedException { - initZookeeper(); - connectLatch.await(); - } - - protected void start(final int wait, final TimeUnit units) throws IOException, InterruptedException { - initZookeeper(); - connectLatch.await(wait, units); - } - - protected void initZookeeper() throws IOException { - zooKeeper = new ZooKeeper(context.getServers(), context.getSessionTimeOut(), startWatcher()); - if (!Strings.isNullOrEmpty(context.getScheme())) { - zooKeeper.addAuthInfo(context.getScheme(), context.getAuth()); - } - } - - private Watcher startWatcher() { - return new Watcher() { - - @Override - public void process(final WatchedEvent event) { - processConnection(event); - if (!isConnected()) { - return; - } - processGlobalListener(event); - // TODO filter event type or path - if (event.getType() == Event.EventType.None) { - return; - } - if (Event.EventType.NodeDeleted == event.getType() || checkPath(event.getPath())) { - processUsualListener(event); - } - } - }; - } - - protected void processConnection(final WatchedEvent event) { - if (Watcher.Event.EventType.None == event.getType()) { - if (Watcher.Event.KeeperState.SyncConnected == event.getState()) { - connectLatch.countDown(); - connected = true; - } else if (Watcher.Event.KeeperState.Expired == event.getState()) { - connected = false; - try { - reset(); - } catch (final IOException | InterruptedException ex) { - log.error("event state Expired: {}", ex.getMessage(), ex); - } - } else if (Watcher.Event.KeeperState.Disconnected == event.getState()) { - connected = false; - } - } - } - - private void processGlobalListener(final WatchedEvent event) { - if (null != context.getGlobalZookeeperEventListener()) { - context.getGlobalZookeeperEventListener().process(event); - } - } - - private void processUsualListener(final WatchedEvent event) { - if (!context.getWatchers().isEmpty()) { - for (ZookeeperEventListener zookeeperEventListener : context.getWatchers().values()) { - if (null == zookeeperEventListener.getPath() || event.getPath().startsWith(zookeeperEventListener.getPath())) { - zookeeperEventListener.process(event); - } - } - } - } - - private boolean checkPath(final String path) { - try { - return null != zooKeeper.exists(path, true); - } catch (final KeeperException | InterruptedException ignore) { - return false; - } - } - - /** - * Reset connection. - * - * @throws IOException IO exception - * @throws InterruptedException interrupted exception - */ - public void reset() throws IOException, InterruptedException { - close(); - start(); - } - - /** - * Close. - */ - public void close() { - try { - zooKeeper.register(new Watcher() { - - @Override - public void process(final WatchedEvent watchedEvent) { - - } - }); - zooKeeper.close(); - connected = false; - context.close(); - } catch (final InterruptedException ex) { - log.warn("Holder close:{}", ex.getMessage()); - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/CreateAllNeedOperation.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/CreateAllNeedOperation.java deleted file mode 100644 index 862362b9686f5..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/CreateAllNeedOperation.java +++ /dev/null @@ -1,55 +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.orchestration.reg.zookeeper.natived.client.zookeeper.operation; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.UsualStrategy; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; - -/** - * Async retry operation which create all need action. - * - * @author lidongbo - */ -public final class CreateAllNeedOperation extends BaseOperation { - - private final String key; - - private final String value; - - private final CreateMode createMode; - - public CreateAllNeedOperation(final IProvider provider, final String key, final String value, final CreateMode createMode) { - super(provider); - this.key = key; - this.value = value; - this.createMode = createMode; - } - - @Override - protected void execute() throws KeeperException, InterruptedException { - new UsualStrategy(getProvider()).createAllNeedPath(key, value, createMode); - } - - @Override - public String toString() { - return String.format("CreateAllNeedOperation key: %s,value: %s, createMode: %s", key, value, createMode.name()); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/CreateCurrentOperation.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/CreateCurrentOperation.java deleted file mode 100644 index a7932cf96be12..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/CreateCurrentOperation.java +++ /dev/null @@ -1,54 +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.orchestration.reg.zookeeper.natived.client.zookeeper.operation; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseOperation; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; - -/** - * Async retry operation which create current action. - * - * @author lidongbo - */ -public final class CreateCurrentOperation extends BaseOperation { - - private final String key; - - private final String value; - - private final CreateMode createMode; - - public CreateCurrentOperation(final IProvider provider, final String key, final String value, final CreateMode createMode) { - super(provider); - this.key = key; - this.value = value; - this.createMode = createMode; - } - - @Override - public void execute() throws KeeperException, InterruptedException { - getProvider().create(getProvider().getRealPath(key), value, createMode); - } - - @Override - public String toString() { - return String.format("CreateCurrentOperation key: %s, value: %s, createMode: %s", key, value, createMode.name()); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteAllChildrenOperation.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteAllChildrenOperation.java deleted file mode 100644 index 89cc17f964a19..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteAllChildrenOperation.java +++ /dev/null @@ -1,48 +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.orchestration.reg.zookeeper.natived.client.zookeeper.operation; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.UsualStrategy; -import org.apache.zookeeper.KeeperException; - -/** - * Async retry operation which delete all children action. - * - * @author lidongbo - */ -public final class DeleteAllChildrenOperation extends BaseOperation { - - private final String key; - - public DeleteAllChildrenOperation(final IProvider provider, final String key) { - super(provider); - this.key = key; - } - - @Override - protected void execute() throws KeeperException, InterruptedException { - new UsualStrategy(getProvider()).deleteAllChildren(key); - } - - @Override - public String toString() { - return String.format("DeleteAllChildrenOperation key: %s", key); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteCurrentBranchOperation.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteCurrentBranchOperation.java deleted file mode 100644 index 7c2fc30fe223c..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteCurrentBranchOperation.java +++ /dev/null @@ -1,48 +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.orchestration.reg.zookeeper.natived.client.zookeeper.operation; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.UsualStrategy; -import org.apache.zookeeper.KeeperException; - -/** - * Async retry operation which delete current branch action. - * - * @author lidongbo - */ -public final class DeleteCurrentBranchOperation extends BaseOperation { - - private final String key; - - public DeleteCurrentBranchOperation(final IProvider provider, final String key) { - super(provider); - this.key = key; - } - - @Override - protected void execute() throws KeeperException, InterruptedException { - new UsualStrategy(getProvider()).deleteCurrentBranch(key); - } - - @Override - public String toString() { - return String.format("DeleteCurrentBranchOperation key: %s", key); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteCurrentOperation.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteCurrentOperation.java deleted file mode 100644 index d5eaf639ebf45..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/DeleteCurrentOperation.java +++ /dev/null @@ -1,47 +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.orchestration.reg.zookeeper.natived.client.zookeeper.operation; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseOperation; -import org.apache.zookeeper.KeeperException; - -/** - * Async retry operation which delete current action. - * - * @author lidongbo - */ -public final class DeleteCurrentOperation extends BaseOperation { - - private final String key; - - public DeleteCurrentOperation(final IProvider provider, final String key) { - super(provider); - this.key = key; - } - - @Override - protected void execute() throws KeeperException, InterruptedException { - getProvider().delete(getProvider().getRealPath(key)); - } - - @Override - public String toString() { - return String.format("DeleteCurrentOperation key: %s", key); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/UpdateOperation.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/UpdateOperation.java deleted file mode 100644 index c2d6aa9f357c2..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/operation/UpdateOperation.java +++ /dev/null @@ -1,50 +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.orchestration.reg.zookeeper.natived.client.zookeeper.operation; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseOperation; -import org.apache.zookeeper.KeeperException; - -/** - * Async retry operation which update action. - * - * @author lidongbo - */ -public final class UpdateOperation extends BaseOperation { - - private final String key; - - private final String value; - - public UpdateOperation(final IProvider provider, final String key, final String value) { - super(provider); - this.key = key; - this.value = value; - } - - @Override - protected void execute() throws KeeperException, InterruptedException { - getProvider().update(getProvider().getRealPath(key), value); - } - - @Override - public String toString() { - return String.format("UpdateOperation key: %s, value: %s", key, value); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/provider/BaseProvider.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/provider/BaseProvider.java deleted file mode 100644 index 529f93e613fc0..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/provider/BaseProvider.java +++ /dev/null @@ -1,157 +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.orchestration.reg.zookeeper.natived.client.zookeeper.provider; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.election.LeaderElection; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.Holder; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.data.ACL; - -import java.io.IOException; -import java.util.List; -import java.util.Stack; - -/** - * Base provider. - * - * @author lidongbo - */ -@RequiredArgsConstructor -@Slf4j -public class BaseProvider implements IProvider { - - @Getter - private final String rootNode; - - @Getter - private final Holder holder; - - @Getter(value = AccessLevel.PROTECTED) - private final boolean watched; - - @Getter(value = AccessLevel.PROTECTED) - private final List authorities; - - @Override - public final String getDataString(final String key) throws KeeperException, InterruptedException { - return new String(getData(key)); - } - - @Override - public final byte[] getData(final String key) throws KeeperException, InterruptedException { - return holder.getZooKeeper().getData(key, watched, null); - } - - @Override - public final void getData(final String key, final AsyncCallback.DataCallback callback, final Object ctx) { - holder.getZooKeeper().getData(key, watched, callback, ctx); - } - - @Override - public final boolean exists(final String key) throws KeeperException, InterruptedException { - return null != holder.getZooKeeper().exists(key, watched); - } - - @Override - public final boolean exists(final String key, final Watcher watcher) throws KeeperException, InterruptedException { - return null != holder.getZooKeeper().exists(key, watcher); - } - - @Override - public final List getChildren(final String key) throws KeeperException, InterruptedException { - return holder.getZooKeeper().getChildren(key, watched); - } - - @Override - public final void create(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - if (exists(key)) { - return; - } - holder.getZooKeeper().create(key, value.getBytes(ZookeeperConstants.UTF_8), authorities, createMode); - } - - @Override - public final boolean update(final String key, final String value) throws KeeperException, InterruptedException { - if (exists(key)) { - holder.getZooKeeper().setData(key, value.getBytes(ZookeeperConstants.UTF_8), ZookeeperConstants.VERSION); - return true; - } - return false; - } - - @Override - public final void delete(final String key) throws KeeperException, InterruptedException { - holder.getZooKeeper().delete(key, ZookeeperConstants.VERSION); - } - - @Override - public final void delete(final String key, final AsyncCallback.VoidCallback callback, final Object ctx) { - holder.getZooKeeper().delete(key, ZookeeperConstants.VERSION, callback, ctx); - } - - @Override - public final String getRealPath(final String path) { - return PathUtil.getRealPath(rootNode, path); - } - - @Override - public final List getNecessaryPaths(final String key) { - List nodes = PathUtil.getPathOrderNodes(rootNode, key); - nodes.remove(rootNode); - return nodes; - } - - @Override - public final Stack getDeletingPaths(final String key) { - return PathUtil.getPathReverseNodes(rootNode, key); - } - - @Override - public final void executeContention(final LeaderElection election) throws KeeperException, InterruptedException { - this.executeContention(rootNode, election); - } - - private void executeContention(final String nodeBeCompete, final LeaderElection election) throws KeeperException, InterruptedException { - election.executeContention(nodeBeCompete, this); - } - - @Override - public final void resetConnection() { - try { - holder.reset(); - } catch (final InterruptedException | IOException ex) { - log.error("resetConnection Exception: {}", ex.getMessage(), ex); - } - } - - @Override - public BaseTransaction transaction() { - return new BaseTransaction(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/provider/TransactionProvider.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/provider/TransactionProvider.java deleted file mode 100644 index 93f003f7fa966..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/provider/TransactionProvider.java +++ /dev/null @@ -1,50 +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.orchestration.reg.zookeeper.natived.client.zookeeper.provider; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.ITransactionProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.Holder; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.ZooKeeperTransaction; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.data.ACL; - -import java.util.List; - -/** - * Provider with transaction. - * - * @author lidongbo - */ -public final class TransactionProvider extends BaseProvider implements ITransactionProvider { - - public TransactionProvider(final String rootNode, final Holder holder, final boolean watched, final List authorities) { - super(rootNode, holder, watched, authorities); - } - - @Override - public void createInTransaction(final String key, final String value, final CreateMode createMode, final BaseTransaction transaction) { - transaction.create(key, value.getBytes(ZookeeperConstants.UTF_8), getAuthorities(), createMode); - } - - @Override - public BaseTransaction transaction() { - return new ZooKeeperTransaction(getRootNode(), getHolder()); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ClientContext.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ClientContext.java deleted file mode 100644 index dccc3093c4162..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ClientContext.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.orchestration.reg.zookeeper.natived.client.zookeeper.section; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.DelayRetryPolicy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseClientFactory; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseContext; -import lombok.Getter; -import lombok.Setter; - -/** - * Client context. - * - * @author lidongbo - */ -@Setter -@Getter -public final class ClientContext extends BaseContext { - - private DelayRetryPolicy delayRetryPolicy; - - private BaseClientFactory clientFactory; - - public ClientContext(final String servers, final int sessionTimeoutMilliseconds) { - setServers(servers); - setSessionTimeOut(sessionTimeoutMilliseconds); - } - - /** - * Update context. - * - * @param context context - */ - public void updateContext(final ClientContext context) { - delayRetryPolicy = context.getDelayRetryPolicy(); - clientFactory = context.clientFactory; - getWatchers().clear(); - getWatchers().putAll(context.getWatchers()); - } - - @Override - public void close() { - super.close(); - delayRetryPolicy = null; - clientFactory = null; - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ClientTask.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ClientTask.java deleted file mode 100644 index 75415123dc229..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ClientTask.java +++ /dev/null @@ -1,53 +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.orchestration.reg.zookeeper.natived.client.zookeeper.section; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.KeeperException; - -/** - * Client task. - * - * @author lidongbo - */ -@RequiredArgsConstructor -@Slf4j -public abstract class ClientTask implements Runnable { - - private final IProvider provider; - - /** - * Run. - * - * @param provider provider - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - public abstract void run(IProvider provider) throws KeeperException, InterruptedException; - - @Override - public final void run() { - try { - run(provider); - } catch (final KeeperException | InterruptedException ex) { - log.error(ex.getMessage(), ex); - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/Connection.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/Connection.java deleted file mode 100644 index 20cd367eea463..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/Connection.java +++ /dev/null @@ -1,69 +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.orchestration.reg.zookeeper.natived.client.zookeeper.section; - -import lombok.AccessLevel; -import lombok.NoArgsConstructor; -import org.apache.zookeeper.KeeperException; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Zookeeper connection check. - * - * @author lidongbo - */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class Connection { - - //is need reset - private static final Map EXCEPTION_RESETS = new ConcurrentHashMap<>(); - - static { - EXCEPTION_RESETS.put(KeeperException.Code.SESSIONEXPIRED.intValue(), true); - EXCEPTION_RESETS.put(KeeperException.Code.SESSIONMOVED.intValue(), true); - EXCEPTION_RESETS.put(KeeperException.Code.CONNECTIONLOSS.intValue(), false); - EXCEPTION_RESETS.put(KeeperException.Code.OPERATIONTIMEOUT.intValue(), false); - } - - /** - * Need retry. - * - * @param keeperException keeper exception - * @return need retry - */ - public static boolean needRetry(final KeeperException keeperException) { - return EXCEPTION_RESETS.containsKey(keeperException.code().intValue()); - } - - /** - * Need reset. - * - * @param keeperException keeper exception - * @return need reset - * @throws KeeperException zookeeper exception - */ - public static boolean needReset(final KeeperException keeperException) throws KeeperException { - int code = keeperException.code().intValue(); - if (!EXCEPTION_RESETS.containsKey(code)) { - throw keeperException; - } - return EXCEPTION_RESETS.get(code); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/StrategyType.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/StrategyType.java deleted file mode 100644 index 0195de83c68fd..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/StrategyType.java +++ /dev/null @@ -1,33 +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.orchestration.reg.zookeeper.natived.client.zookeeper.section; - -/** - * Exec strategy type. - * - * @author lidongbo - */ -public enum StrategyType { - - USUAL, - CONTEND, - TRANSACTION_CONTEND, - SYNC_RETRY, - ASYNC_RETRY, - ALL_ASYNC_RETRY -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/WatcherCreator.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/WatcherCreator.java deleted file mode 100644 index 2dcea7832ca55..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/WatcherCreator.java +++ /dev/null @@ -1,50 +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.orchestration.reg.zookeeper.natived.client.zookeeper.section; - -import lombok.AccessLevel; -import lombok.NoArgsConstructor; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; - -/** - * Build public watcher. - * - * @author lidongbo - */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class WatcherCreator { - - /** - * Get string type data. - * - * @param zookeeperEventListener listener - * @return watcher - */ - public static Watcher deleteWatcher(final ZookeeperEventListener zookeeperEventListener) { - return new Watcher() { - - @Override - public void process(final WatchedEvent event) { - if (zookeeperEventListener.getPath().equals(event.getPath()) && Event.EventType.NodeDeleted.equals(event.getType())) { - zookeeperEventListener.process(event); - } - } - }; - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ZookeeperEventListener.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ZookeeperEventListener.java deleted file mode 100644 index f6b44f012add9..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/section/ZookeeperEventListener.java +++ /dev/null @@ -1,52 +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.orchestration.reg.zookeeper.natived.client.zookeeper.section; - -import lombok.Getter; -import lombok.Setter; -import org.apache.zookeeper.WatchedEvent; - -/** - * Watch event listener. - * - * @author lidongbo - */ -@Getter -public abstract class ZookeeperEventListener { - - private final String key; - - @Setter - private String path; - - public ZookeeperEventListener() { - this(null); - } - - public ZookeeperEventListener(final String path) { - this.key = path + System.currentTimeMillis(); - this.path = path; - } - - /** - * Process. - * - * @param event event - */ - public abstract void process(WatchedEvent event); -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/AsyncRetryStrategy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/AsyncRetryStrategy.java deleted file mode 100644 index 13b5e6fce9b42..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/AsyncRetryStrategy.java +++ /dev/null @@ -1,134 +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.orchestration.reg.zookeeper.natived.client.zookeeper.strategy; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.AsyncRetryCenter; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.DelayRetryPolicy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.operation.CreateAllNeedOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.operation.CreateCurrentOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.operation.DeleteAllChildrenOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.operation.DeleteCurrentBranchOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.operation.DeleteCurrentOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.operation.UpdateOperation; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.Connection; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; - -/** - * Async retry strategy. - * - * @author lidongbo - */ -@Slf4j -public final class AsyncRetryStrategy extends SyncRetryStrategy { - - public AsyncRetryStrategy(final IProvider provider, final DelayRetryPolicy delayRetryPolicy) { - super(provider, delayRetryPolicy); - AsyncRetryCenter.INSTANCE.init(getDelayRetryPolicy()); - AsyncRetryCenter.INSTANCE.start(); - } - - @Override - public void createCurrentOnly(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - String path = getProvider().getRealPath(key); - try { - getProvider().create(path, value, createMode); - } catch (KeeperException ex) { - if (Connection.needRetry(ex)) { - log.warn(String.format("AsyncRetryStrategy SessionExpiredException createCurrentOnly: %s", path), ex); - AsyncRetryCenter.INSTANCE.add(new CreateCurrentOperation(getProvider(), path, value, createMode)); - } else { - throw ex; - } - } - } - - @Override - public void update(final String key, final String value) throws KeeperException, InterruptedException { - String path = getProvider().getRealPath(key); - try { - getProvider().update(path, value); - } catch (KeeperException ex) { - if (Connection.needRetry(ex)) { - log.warn(String.format("AsyncRetryStrategy SessionExpiredException update: %s", path), ex); - AsyncRetryCenter.INSTANCE.add(new UpdateOperation(getProvider(), path, value)); - } else { - throw ex; - } - } - } - - @Override - public void deleteOnlyCurrent(final String key) throws KeeperException, InterruptedException { - String path = getProvider().getRealPath(key); - try { - getProvider().delete(path); - } catch (KeeperException ex) { - if (Connection.needRetry(ex)) { - log.warn(String.format("AsyncRetryStrategy SessionExpiredException deleteOnlyCurrent: %s", path), ex); - AsyncRetryCenter.INSTANCE.add(new DeleteCurrentOperation(getProvider(), path)); - } else { - throw ex; - } - } - } - - @Override - public void createAllNeedPath(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - try { - super.createAllNeedPath(key, value, createMode); - } catch (KeeperException ex) { - if (Connection.needRetry(ex)) { - log.warn(String.format("AllAsyncRetryStrategy SessionExpiredException CreateAllNeedOperation: %s", key), ex); - AsyncRetryCenter.INSTANCE.add(new CreateAllNeedOperation(getProvider(), key, value, createMode)); - } else { - throw ex; - } - } - } - - @Override - public void deleteAllChildren(final String key) throws KeeperException, InterruptedException { - try { - super.deleteAllChildren(key); - } catch (KeeperException ex) { - if (Connection.needRetry(ex)) { - log.warn(String.format("AllAsyncRetryStrategy SessionExpiredException deleteAllChildren: %s", key), ex); - AsyncRetryCenter.INSTANCE.add(new DeleteAllChildrenOperation(getProvider(), key)); - } else { - throw ex; - } - } - } - - @Override - public void deleteCurrentBranch(final String key) throws KeeperException, InterruptedException { - try { - super.deleteCurrentBranch(key); - } catch (KeeperException ex) { - if (Connection.needRetry(ex)) { - log.warn(String.format("AllAsyncRetryStrategy SessionExpiredException deleteCurrentBranch: %s", key), ex); - AsyncRetryCenter.INSTANCE.add(new DeleteCurrentBranchOperation(getProvider(), key)); - } else { - throw ex; - } - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/BaseStrategy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/BaseStrategy.java deleted file mode 100644 index 527b68ed12216..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/BaseStrategy.java +++ /dev/null @@ -1,47 +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.orchestration.reg.zookeeper.natived.client.zookeeper.strategy; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IExecStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import org.apache.zookeeper.KeeperException; - -/** - * Base execute strategy. - * - * @author lidongbo - */ -@RequiredArgsConstructor -public abstract class BaseStrategy implements IExecStrategy { - - @Getter - private final IProvider provider; - - @Override - public final String getDataString(final String key) throws KeeperException, InterruptedException { - return new String(getData(key)); - } - - @Override - public final BaseTransaction transaction() { - return provider.transaction(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/ContentionStrategy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/ContentionStrategy.java deleted file mode 100644 index 8e26a1f736994..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/ContentionStrategy.java +++ /dev/null @@ -1,252 +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.orchestration.reg.zookeeper.natived.client.zookeeper.strategy; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.ContentionCallback; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.election.LeaderElection; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; - -import java.util.List; -import java.util.Stack; - -/** - * The contention strategy is effective only when all the clients of the node which be competitive are using contention strategy. - * - * @author lidongbo - */ -@Slf4j -public class ContentionStrategy extends UsualStrategy { - - public ContentionStrategy(final IProvider provider) { - super(provider); - } - - /* - * Don't use this if you don't have to use it. - */ - @Override - public final void getData(final String key, final AsyncCallback.DataCallback callback, final Object ctx) throws KeeperException, InterruptedException { - getProvider().executeContention(new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - getProvider().getData(getProvider().getRealPath(key), callback, ctx); - } - }); - } - - @Override - public final void createCurrentOnly(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - LeaderElection election = buildCreateElection(key, value, createMode, null); - getProvider().executeContention(election); - election.waitDone(); - } - - private LeaderElection buildCreateElection(final String key, final String value, final CreateMode createMode, final ContentionCallback contentionCallback) { - return new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - getProvider().create(getProvider().getRealPath(key), value, createMode); - } - - @Override - public void callback() { - if (null != contentionCallback) { - contentionCallback.processResult(); - } - } - }; - } - - @Override - public final void update(final String key, final String value) throws KeeperException, InterruptedException { - LeaderElection election = buildUpdateElection(key, value, null); - getProvider().executeContention(election); - election.waitDone(); - } - - private LeaderElection buildUpdateElection(final String key, final String value, final ContentionCallback contentionCallback) { - return new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - getProvider().update(getProvider().getRealPath(key), value); - } - - @Override - public void callback() { - if (null != contentionCallback) { - contentionCallback.processResult(); - } - } - }; - } - - @Override - public final void deleteOnlyCurrent(final String key) throws KeeperException, InterruptedException { - LeaderElection election = buildDeleteElection(key, null); - getProvider().executeContention(election); - election.waitDone(); - } - - @Override - public final void deleteOnlyCurrent(final String key, final AsyncCallback.VoidCallback callback, final Object ctx) throws KeeperException, InterruptedException { - getProvider().executeContention(new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - getProvider().delete(getProvider().getRealPath(key), callback, ctx); - } - }); - } - - private LeaderElection buildDeleteElection(final String key, final ContentionCallback contentionCallback) { - return new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - getProvider().delete(getProvider().getRealPath(key)); - } - - @Override - public void callback() { - if (null != contentionCallback) { - contentionCallback.processResult(); - } - } - }; - } - - @Override - public void createAllNeedPath(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - LeaderElection election = buildCreateAllNeedElection(key, value, createMode, null); - getProvider().executeContention(election); - election.waitDone(); - } - - private LeaderElection buildCreateAllNeedElection(final String key, final String value, final CreateMode createMode, final ContentionCallback contentionCallback) { - return new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - createBegin(getProvider().getRealPath(key), value, createMode); - } - - @Override - public void callback() { - if (null != contentionCallback) { - contentionCallback.processResult(); - } - } - }; - } - - private void createBegin(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - // TODO start with / - if (!key.contains(ZookeeperConstants.PATH_SEPARATOR)) { - getProvider().create(key, value, createMode); - return; - } - List nodes = getProvider().getNecessaryPaths(key); - for (int i = 0; i < nodes.size(); i++) { - if (getProvider().exists(nodes.get(i))) { - continue; - } - if (i == nodes.size() - 1) { - getProvider().create(nodes.get(i), value, createMode); - } else { - getProvider().create(nodes.get(i), ZookeeperConstants.NOTHING_VALUE, createMode); - } - } - } - - @Override - public void deleteAllChildren(final String key) throws KeeperException, InterruptedException { - getProvider().executeContention(new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - deleteChildren(getProvider().getRealPath(key), true); - } - }); - } - - private void deleteChildren(final String key, final boolean deleteCurrentNode) throws KeeperException, InterruptedException { - List children = getProvider().getChildren(key); - for (String aChildren : children) { - String child = PathUtil.getRealPath(key, aChildren); - if (!getProvider().exists(child)) { - continue; - } - deleteChildren(child, true); - } - if (deleteCurrentNode) { - getProvider().delete(key); - } - } - - @Override - public void deleteCurrentBranch(final String key) throws KeeperException, InterruptedException { - getProvider().executeContention(new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - deleteBranch(getProvider().getRealPath(key)); - } - }); - } - - private void deleteBranch(final String key) throws KeeperException, InterruptedException { - deleteChildren(key, false); - Stack pathStack = getProvider().getDeletingPaths(key); - while (!pathStack.empty()) { - String node = pathStack.pop(); - // contrast cache - if (getProvider().exists(node)) { - try { - getProvider().delete(node); - } catch (KeeperException.NotEmptyException e) { - log.warn("deleteBranch {} exist other children: {}", node, this.getChildren(node)); - return; - } - } - log.info("deleteBranch node not exist: {}", node); - } - } - - //TODO Use arbitrary competitive nodes - //IExecStrategy convert to ContentionStrategy - /*public void createCurrentOnly(final String key, final String value, final CreateMode createMode, final ContentionCallback callback) throws KeeperException, InterruptedException { - getProvider().executeContention(buildCreateElection(key, value, createMode, callback)); - } - - public void update(final String key, final String value, final ContentionCallback callback) throws KeeperException, InterruptedException { - getProvider().executeContention(buildUpdateElection(key, value, null)); - } - - public void deleteOnlyCurrent(final String key, final ContentionCallback callback) throws KeeperException, InterruptedException { - getProvider().executeContention(buildDeleteElection(key, null)); - }*/ -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/SyncRetryStrategy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/SyncRetryStrategy.java deleted file mode 100644 index 8f8f5f9ee6ab9..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/SyncRetryStrategy.java +++ /dev/null @@ -1,166 +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.orchestration.reg.zookeeper.natived.client.zookeeper.strategy; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.DelayRetryPolicy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.RetryCallable; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.RetryResultCallable; -import lombok.AccessLevel; -import lombok.Getter; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.Watcher; - -import java.util.List; - -/** - * Sync retry strategy. - * - * @author lidongbo - */ -@Getter(value = AccessLevel.PROTECTED) -public class SyncRetryStrategy extends UsualStrategy { - - private final DelayRetryPolicy delayRetryPolicy; - - public SyncRetryStrategy(final IProvider provider, final DelayRetryPolicy delayRetryPolicy) { - super(provider); - this.delayRetryPolicy = null == delayRetryPolicy ? DelayRetryPolicy.defaultDelayPolicy() : delayRetryPolicy; - } - - @Override - public byte[] getData(final String key) throws KeeperException, InterruptedException { - RetryResultCallable retryCallable = new RetryResultCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - setResult(getProvider().getData(getProvider().getRealPath(key))); - } - }; - return retryCallable.getResult(); - } - - @Override - public boolean checkExists(final String key) throws KeeperException, InterruptedException { - RetryResultCallable retryCallable = new RetryResultCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - setResult(getProvider().exists(getProvider().getRealPath(key))); - } - }; - return retryCallable.getResult(); - } - - @Override - public boolean checkExists(final String key, final Watcher watcher) throws KeeperException, InterruptedException { - RetryResultCallable retryCallable = new RetryResultCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - setResult(getProvider().exists(getProvider().getRealPath(key), watcher)); - } - }; - return retryCallable.getResult(); - } - - @Override - public List getChildren(final String key) throws KeeperException, InterruptedException { - RetryResultCallable> retryCallable = new RetryResultCallable>(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - setResult(getProvider().getChildren(getProvider().getRealPath(key))); - } - }; - return retryCallable.getResult(); - } - - @Override - public void createCurrentOnly(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - RetryCallable retryCallable = new RetryCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - getProvider().create(getProvider().getRealPath(key), value, createMode); - } - }; - retryCallable.exec(); - } - - @Override - public void update(final String key, final String value) throws KeeperException, InterruptedException { - RetryCallable retryCallable = new RetryCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - getProvider().update(getProvider().getRealPath(key), value); - } - }; - retryCallable.exec(); - } - - @Override - public void deleteOnlyCurrent(final String key) throws KeeperException, InterruptedException { - RetryCallable retryCallable = new RetryCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - getProvider().delete(getProvider().getRealPath(key)); - } - }; - retryCallable.exec(); - } - - @Override - public void createAllNeedPath(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - RetryCallable retryCallable = new RetryCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - new UsualStrategy(getProvider()).createAllNeedPath(key, value, createMode); - } - }; - retryCallable.exec(); - } - - @Override - public void deleteAllChildren(final String key) throws KeeperException, InterruptedException { - RetryCallable retryCallable = new RetryCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - new UsualStrategy(getProvider()).deleteAllChildren(key); - } - }; - retryCallable.exec(); - } - - @Override - public void deleteCurrentBranch(final String key) throws KeeperException, InterruptedException { - RetryCallable retryCallable = new RetryCallable(getProvider(), delayRetryPolicy) { - - @Override - public void call() throws KeeperException, InterruptedException { - new UsualStrategy(getProvider()).deleteCurrentBranch(key); - } - }; - retryCallable.exec(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/TransactionContendStrategy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/TransactionContendStrategy.java deleted file mode 100644 index edc64ac92196b..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/TransactionContendStrategy.java +++ /dev/null @@ -1,150 +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.orchestration.reg.zookeeper.natived.client.zookeeper.strategy; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.ContentionCallback; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.ITransactionProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.election.LeaderElection; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.provider.BaseProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.ZooKeeperTransaction; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; - -import java.util.List; -import java.util.Stack; - -/** - * ContentionStrategy with transaction. - * - * @author lidongbo - * @since zookeeper 3.4.0 - */ -public final class TransactionContendStrategy extends ContentionStrategy { - - public TransactionContendStrategy(final ITransactionProvider provider) { - super(provider); - } - - @Override - public void createAllNeedPath(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - LeaderElection election = buildCreateAllNeedElection(key, value, createMode, null); - getProvider().executeContention(election); - election.waitDone(); - } - - private LeaderElection buildCreateAllNeedElection(final String key, final String value, final CreateMode createMode, final ContentionCallback contentionCallback) { - return new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - ZooKeeperTransaction transaction = new ZooKeeperTransaction(((BaseProvider) getProvider()).getRootNode(), ((BaseProvider) getProvider()).getHolder()); - createBegin(key, value, createMode, transaction); - transaction.commit(); - } - - @Override - public void callback() { - if (contentionCallback != null) { - contentionCallback.processResult(); - } - } - }; - } - - private void createBegin(final String key, final String value, final CreateMode createMode, final ZooKeeperTransaction transaction) throws KeeperException, InterruptedException { - if (!key.contains(ZookeeperConstants.PATH_SEPARATOR)) { - ((ITransactionProvider) getProvider()).createInTransaction(key, value, createMode, transaction); - return; - } - List nodes = getProvider().getNecessaryPaths(key); - for (int i = 0; i < nodes.size(); i++) { - if (getProvider().exists(nodes.get(i))) { - continue; - } - if (i == nodes.size() - 1) { - ((ITransactionProvider) getProvider()).createInTransaction(nodes.get(i), value, createMode, transaction); - } else { - ((ITransactionProvider) getProvider()).createInTransaction(nodes.get(i), ZookeeperConstants.NOTHING_VALUE, createMode, transaction); - } - } - } - - @Override - public void deleteAllChildren(final String key) throws KeeperException, InterruptedException { - getProvider().executeContention(new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - ZooKeeperTransaction transaction = new ZooKeeperTransaction(((BaseProvider) getProvider()).getRootNode(), ((BaseProvider) getProvider()).getHolder()); - deleteChildren(getProvider().getRealPath(key), true, transaction); - transaction.commit(); - } - }); - } - - private void deleteChildren(final String key, final boolean deleteCurrentNode, final ZooKeeperTransaction transaction) throws KeeperException, InterruptedException { - List children = getProvider().getChildren(key); - for (String each : children) { - String child = PathUtil.getRealPath(key, each); - if (!getProvider().exists(child)) { - continue; - } - deleteChildren(child, true, transaction); - } - if (deleteCurrentNode) { - transaction.delete(key, ZookeeperConstants.VERSION); - } - } - - @Override - public void deleteCurrentBranch(final String key) throws KeeperException, InterruptedException { - getProvider().executeContention(new LeaderElection() { - - @Override - public void action() throws KeeperException, InterruptedException { - ZooKeeperTransaction transaction = new ZooKeeperTransaction(((BaseProvider) getProvider()).getRootNode(), ((BaseProvider) getProvider()).getHolder()); - deleteBranch(getProvider().getRealPath(key), transaction); - transaction.commit(); - } - }); - } - - private void deleteBranch(final String key, final ZooKeeperTransaction transaction) throws KeeperException, InterruptedException { - deleteChildren(key, false, transaction); - Stack pathStack = getProvider().getDeletingPaths(key); - String prePath = key; - while (!pathStack.empty()) { - String node = pathStack.pop(); - // contrast cache - // Performance needs testing - List children = getProvider().getChildren(node); - boolean canDelete = children.isEmpty() || 1 == children.size(); - if (1 == children.size()) { - if (!PathUtil.getRealPath(node, children.get(0)).equals(prePath)) { - canDelete = false; - } - } - if (getProvider().exists(node) && canDelete) { - transaction.delete(node, ZookeeperConstants.VERSION); - } - prePath = node; - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/UsualStrategy.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/UsualStrategy.java deleted file mode 100644 index 697842cedbf10..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/strategy/UsualStrategy.java +++ /dev/null @@ -1,170 +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.orchestration.reg.zookeeper.natived.client.zookeeper.strategy; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.Watcher; - -import java.util.List; - -/** - * Usual strategy. - * - * @author lidongbo - */ -@Slf4j -public class UsualStrategy extends BaseStrategy { - - public UsualStrategy(final IProvider provider) { - super(provider); - } - - @Override - public byte[] getData(final String key) throws KeeperException, InterruptedException { - return getProvider().getData(getProvider().getRealPath(key)); - } - - @Override - public void getData(final String key, final AsyncCallback.DataCallback callback, final Object ctx) throws KeeperException, InterruptedException { - getProvider().getData(getProvider().getRealPath(key), callback, ctx); - } - - @Override - public boolean checkExists(final String key) throws KeeperException, InterruptedException { - return getProvider().exists(getProvider().getRealPath(key)); - } - - @Override - public boolean checkExists(final String key, final Watcher watcher) throws KeeperException, InterruptedException { - return getProvider().exists(getProvider().getRealPath(key), watcher); - } - - @Override - public List getChildren(final String key) throws KeeperException, InterruptedException { - return getProvider().getChildren(getProvider().getRealPath(key)); - } - - @Override - public void createCurrentOnly(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - getProvider().create(getProvider().getRealPath(key), value, createMode); - } - - @Override - public void update(final String key, final String value) throws KeeperException, InterruptedException { - getProvider().update(getProvider().getRealPath(key), value); - } - - @Override - public void deleteOnlyCurrent(final String key) throws KeeperException, InterruptedException { - getProvider().delete(getProvider().getRealPath(key)); - } - - @Override - public void deleteOnlyCurrent(final String key, final AsyncCallback.VoidCallback callback, final Object ctx) throws KeeperException, InterruptedException { - getProvider().delete(getProvider().getRealPath(key), callback, ctx); - } - - @Override - public void createAllNeedPath(final String key, final String value, final CreateMode createMode) throws KeeperException, InterruptedException { - if (!key.contains(ZookeeperConstants.PATH_SEPARATOR)) { - createCurrentOnly(key, value, createMode); - return; - } - List nodes = getProvider().getNecessaryPaths(key); - for (int i = 0; i < nodes.size(); i++) { - try { - if (i == nodes.size() - 1) { - createCurrentOnly(nodes.get(i), value, createMode); - } else { - createCurrentOnly(nodes.get(i), ZookeeperConstants.NOTHING_VALUE, CreateMode.PERSISTENT); - } - } catch (final KeeperException.NodeExistsException ignored) { - } - } - } - - @Override - public void deleteAllChildren(final String key) throws KeeperException, InterruptedException { - deleteChildren(getProvider().getRealPath(key), true); - } - - private void deleteChildren(final String path, final boolean deleteCurrentNode) throws KeeperException, InterruptedException { - List children; - try { - children = getProvider().getChildren(path); - } catch (final KeeperException.NoNodeException ignored) { - return; - } - for (String each : children) { - this.deleteAllChildren(PathUtil.getRealPath(path, each)); - } - if (deleteCurrentNode) { - try { - deleteOnlyCurrent(path); - } catch (final KeeperException.NotEmptyException ex) { - log.warn("deleteCurrentNode exist children: {}, ex: {}", path, ex.getMessage()); - deleteChildren(path, true); - } catch (final KeeperException.NoNodeException ex) { - log.warn("deleteCurrentNode node not exist: {}, ex: {}", path, ex.getMessage()); - } - } - } - - /* - * delete the current node with force and delete the super node whose only child node is current node recursively - */ - @Override - public void deleteCurrentBranch(final String key) throws KeeperException, InterruptedException { - String path = getProvider().getRealPath(key); - try { - deleteOnlyCurrent(path); - } catch (final KeeperException.NotEmptyException ex) { - deleteChildren(path, true); - } catch (final KeeperException.NoNodeException ignored) { - } - - String superPath = path.substring(0, path.lastIndexOf(ZookeeperConstants.PATH_SEPARATOR)); - try { - deleteRecursively(superPath); - } catch (final KeeperException.NotEmptyException ex) { - log.warn("deleteCurrentBranch exist children: {}, ex: {}", path, ex.getMessage()); - } catch (final KeeperException.NoNodeException ignored) { - } - } - - private void deleteRecursively(final String path) throws KeeperException, InterruptedException { - int index = path.lastIndexOf(ZookeeperConstants.PATH_SEPARATOR); - if (index == 0) { - deleteOnlyCurrent(path); - return; - } - String superPath = path.substring(0, index); - try { - deleteOnlyCurrent(path); - deleteRecursively(superPath); - } catch (final KeeperException.NotEmptyException ex) { - log.info("deleteRecursively exist children: {}, ex: {}", path, ex.getMessage()); - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/transaction/BaseTransaction.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/transaction/BaseTransaction.java deleted file mode 100644 index 390cc30819c6a..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/transaction/BaseTransaction.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.orchestration.reg.zookeeper.natived.client.zookeeper.transaction; - -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.OpResult; -import org.apache.zookeeper.data.ACL; - -import java.util.List; - -/** - * Base transaction. - * - * @author lidongbo - */ -public class BaseTransaction { - - /** - * Create target node. - * - * @param path key - * @param data value - * @param acl acl - * @param createMode create mode - * @return zookeeper transaction - */ - public ZooKeeperTransaction create(final String path, final byte[] data, final List acl, final CreateMode createMode) { - throw new UnsupportedOperationException("check zk version!"); - } - - /** - * Delete target node. - * - * @param path key - * @return zookeeper transaction - */ - public ZooKeeperTransaction delete(final String path) { - throw new UnsupportedOperationException("check zk version!"); - } - - /** - * Delete target node. - * - * @param path key - * @param version version - * @return zookeeper transaction - */ - public ZooKeeperTransaction delete(final String path, final int version) { - throw new UnsupportedOperationException("check zk version!"); - } - - /** - * Check target node. - * - * @param path key - * @return zookeeper transaction - */ - public ZooKeeperTransaction check(final String path) { - throw new UnsupportedOperationException("check zk version!"); - } - - - /** - * Check target node. - * - * @param path key - * @param version version - * @return zookeeper transaction - */ - public ZooKeeperTransaction check(final String path, final int version) { - throw new UnsupportedOperationException("check zk version!"); - } - - /** - * Update target node. - * - * @param path key - * @param data data - * @return zookeeper transaction - */ - public ZooKeeperTransaction setData(final String path, final byte[] data) { - throw new UnsupportedOperationException("check zk version!"); - } - - /** - * Update target node. - * - * @param path key - * @param data data - * @param version version - * @return zookeeper transaction - */ - public ZooKeeperTransaction setData(final String path, final byte[] data, final int version) { - throw new UnsupportedOperationException("check zk version!"); - } - - /** - * Commit. - * - * @return operation result - * @throws KeeperException zookeeper exception - * @throws InterruptedException interrupted exception - */ - public List commit() throws InterruptedException, KeeperException { - throw new UnsupportedOperationException("check zk version!"); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/transaction/ZooKeeperTransaction.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/transaction/ZooKeeperTransaction.java deleted file mode 100644 index 2d99e7b2c512d..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/transaction/ZooKeeperTransaction.java +++ /dev/null @@ -1,91 +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.orchestration.reg.zookeeper.natived.client.zookeeper.transaction; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.Holder; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.OpResult; -import org.apache.zookeeper.Transaction; -import org.apache.zookeeper.data.ACL; - -import java.util.List; - -/** - * Zookeeper transaction support. - * - * @author lidongbo - * @since zookeeper 3.4.0 - */ -public final class ZooKeeperTransaction extends BaseTransaction { - - private final String rootNode; - - private final Transaction transaction; - - public ZooKeeperTransaction(final String root, final Holder holder) { - rootNode = root; - transaction = holder.getZooKeeper().transaction(); - } - - @Override - public ZooKeeperTransaction create(final String path, final byte[] data, final List acl, final CreateMode createMode) { - transaction.create(PathUtil.getRealPath(rootNode, path), data, acl, createMode); - return this; - } - - @Override - public ZooKeeperTransaction delete(final String path) { - return delete(path, ZookeeperConstants.VERSION); - } - - @Override - public ZooKeeperTransaction delete(final String path, final int version) { - transaction.delete(PathUtil.getRealPath(rootNode, path), version); - return this; - } - - @Override - public ZooKeeperTransaction check(final String path) { - return check(path, ZookeeperConstants.VERSION); - } - - @Override - public ZooKeeperTransaction check(final String path, final int version) { - transaction.check(PathUtil.getRealPath(rootNode, path), version); - return this; - } - - @Override - public ZooKeeperTransaction setData(final String path, final byte[] data) { - return setData(path, data, ZookeeperConstants.VERSION); - } - - @Override - public ZooKeeperTransaction setData(final String path, final byte[] data, final int version) { - transaction.setData(PathUtil.getRealPath(rootNode, path), data, version); - return this; - } - - @Override - public List commit() throws InterruptedException, KeeperException { - return transaction.commit(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/resources/META-INF/services/io.shardingsphere.orchestration.reg.api.RegistryCenter b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/resources/META-INF/services/io.shardingsphere.orchestration.reg.api.RegistryCenter deleted file mode 100644 index 9db828e8a6738..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/main/resources/META-INF/services/io.shardingsphere.orchestration.reg.api.RegistryCenter +++ /dev/null @@ -1 +0,0 @@ -io.shardingsphere.orchestration.reg.zookeeper.natived.NativeZookeeperRegistryCenter diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/AllNativeZookeeperTests.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/AllNativeZookeeperTests.java deleted file mode 100644 index d2c9866739e60..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/AllNativeZookeeperTests.java +++ /dev/null @@ -1,38 +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.orchestration.reg.zookeeper.natived; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.cache.PathResolveTest; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.cache.PathTreeTest; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.AllBaseTests; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.SyncRetryStrategyTest; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.UsualClientTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ - PathResolveTest.class, - PathTreeTest.class, - SyncRetryStrategyTest.class, - AllBaseTests.class, - UsualClientTest.class - }) -public final class AllNativeZookeeperTests { -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathResolveTest.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathResolveTest.java deleted file mode 100644 index 8cba2e815f46c..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathResolveTest.java +++ /dev/null @@ -1,60 +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.orchestration.reg.zookeeper.natived.client.cache; - -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -public class PathResolveTest { - - @Test - public void assertNext() { - final String path = "/test/a/bb/ccc/ddd"; - PathResolve pathResolve = new PathResolve(path); - pathResolve.next(); - assertThat(pathResolve.getCurrent(), is("test")); - pathResolve.next(); - assertThat(pathResolve.getCurrent(), is("a")); - pathResolve.next(); - assertThat(pathResolve.getCurrent(), is("bb")); - pathResolve.next(); - assertThat(pathResolve.getCurrent(), is("ccc")); - pathResolve.next(); - assertThat(pathResolve.getCurrent(), is("ddd")); - } - - @Test - public void assertTrickEnd() { - final String path = "/test/"; - PathResolve pathResolve = new PathResolve(path); - pathResolve.next(); - assertThat(pathResolve.isEnd(), is(true)); - } - - @Test - public void assertEnd() { - final String path = "/test/a/bb"; - PathResolve pathResolve = new PathResolve(path); - pathResolve.next(); - pathResolve.next(); - pathResolve.next(); - assertThat(pathResolve.isEnd(), is(true)); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathTreeTest.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathTreeTest.java deleted file mode 100644 index 1813d1e40e9ab..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/cache/PathTreeTest.java +++ /dev/null @@ -1,202 +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.orchestration.reg.zookeeper.natived.client.cache; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.util.EmbedTestingServer; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.ClientFactory; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseTest; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.TestSupport; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.ZooDefs; -import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -public class PathTreeTest extends BaseTest { - - private PathTree pathTree; - - private IClient testClient; - - @Before - public void start() throws IOException, InterruptedException { - EmbedTestingServer.start(); - ClientFactory creator = new ClientFactory(); - testClient = creator.setClientNamespace(TestSupport.ROOT).authorization(TestSupport.AUTH, TestSupport.AUTH.getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL) - .newClient(TestSupport.SERVERS, TestSupport.SESSION_TIMEOUT).start(); - - pathTree = new PathTree(TestSupport.ROOT, testClient); - } - - @After - public void stop() { - pathTree.close(); - testClient.close(); - } - - @Test - public void assertLoad() throws KeeperException, InterruptedException { - final String keyB = "a/b/bb"; - final String valueB = "bbb11"; - testClient.createAllNeedPath(keyB, valueB, CreateMode.PERSISTENT); - assertTrue(testClient.checkExists(keyB)); - final String keyC = "a/c/cc"; - final String valueC = "ccc11"; - testClient.createAllNeedPath(keyC, valueC, CreateMode.PERSISTENT); - assertTrue(testClient.checkExists(keyC)); - - try { - pathTree.load(); - - assertThat(new String(pathTree.getValue(keyB)), is(valueB)); - assertThat(new String(pathTree.getValue(keyC)), is(valueC)); - } finally { - testClient.deleteCurrentBranch(keyC); - testClient.deleteCurrentBranch(keyB); - } - } - - @Test - public void assertGetChildren() throws KeeperException, InterruptedException { - final String keyB = "a/b"; - final String valueB = "bbb11"; - - final String keyC = "a/c"; - final String valueC = "ccc11"; - - try { - pathTree.watch(); - testClient.createAllNeedPath(keyB, valueB, CreateMode.PERSISTENT); - Thread.sleep(200); - testClient.createAllNeedPath(keyC, valueC, CreateMode.PERSISTENT); - Thread.sleep(200); - - assertThat(pathTree.getChildren("a"), hasItems(valueB, valueC)); - } finally { - testClient.deleteCurrentBranch(keyC); - testClient.deleteCurrentBranch(keyB); - } - } - - @Test - public void assertPut() { - final String key = "a/b/bb"; - final String value = "bbb11"; - pathTree.put(key, value); - assertThat(pathTree.getValue("a"), CoreMatchers.is(ZookeeperConstants.NOTHING_DATA)); - assertThat(pathTree.getValue("a/b"), is(ZookeeperConstants.NOTHING_DATA)); - assertThat(pathTree.getValue(key), is(value.getBytes(ZookeeperConstants.UTF_8))); - } - - @Test - public void assertGetValue() throws KeeperException, InterruptedException { - final String key = "a/b/bb"; - final String value = "bbb11"; - try { - pathTree.watch(); - testClient.createAllNeedPath(key, value, CreateMode.PERSISTENT); - Thread.sleep(200); - assertThat(pathTree.getValue(key), is(value.getBytes(ZookeeperConstants.UTF_8))); - } finally { - testClient.deleteCurrentBranch(key); - } - } - - @Test - public void assertDelete() throws KeeperException, InterruptedException { - final String key = "a/b/bb"; - final String value = "bbb11"; - try { - pathTree.watch(); - testClient.createAllNeedPath(key, value, CreateMode.PERSISTENT); - Thread.sleep(200); - pathTree.delete(key); - assertNull(pathTree.getValue(key)); - } finally { - testClient.deleteCurrentBranch(key); - } - } - - @Test - public void assertWatch() throws KeeperException, InterruptedException { - final String key = "a/b/bb"; - final String value = "bbb11"; - final String valueNew = "111"; - try { - createRootOnly(testClient); - pathTree.watch(); - - testClient.createAllNeedPath(key, value, CreateMode.PERSISTENT); - Thread.sleep(200); - testClient.update(key, valueNew); - - Thread.sleep(1000); - assertThat(pathTree.getValue(key), is(valueNew.getBytes(ZookeeperConstants.UTF_8))); - } finally { - testClient.deleteCurrentBranch(key); - } - } - - @Test - public void assertRefreshPeriodic() throws KeeperException, InterruptedException { - final String key = "a/b/bb"; - final String value = "bbb11"; - final String valueNew = "111"; - try { - testClient.createAllNeedPath(key, value, CreateMode.PERSISTENT); - pathTree.refreshPeriodic(100); - sleep(2000); - assertThat(pathTree.getValue(key), is(value.getBytes(ZookeeperConstants.UTF_8))); - testClient.update(key, valueNew); - sleep(2000); - assertThat(pathTree.getValue(key), is(valueNew.getBytes(ZookeeperConstants.UTF_8))); - - pathTree.refreshPeriodic(10); - } catch (final IllegalStateException ex) { - assertThat(ex.getMessage(), is("period already set")); - } finally { - pathTree.stopRefresh(); - testClient.deleteCurrentBranch(key); - } - } - - @Test - public void assertStopRefresh() { - try { - pathTree.refreshPeriodic(1); - sleep(100); - pathTree.refreshPeriodic(1); - } catch (final IllegalStateException ex) { - assertThat(ex.getMessage(), is("period already set")); - pathTree.stopRefresh(); - pathTree.refreshPeriodic(1); - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/TestCallable.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/TestCallable.java deleted file mode 100644 index d58431b2c7612..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/TestCallable.java +++ /dev/null @@ -1,51 +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.orchestration.reg.zookeeper.natived.client.retry; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.provider.BaseProvider; -import org.apache.zookeeper.KeeperException; - -public abstract class TestCallable extends RetryCallable { - - private int count; - - public TestCallable(final IProvider provider, final DelayRetryPolicy delayRetryPolicy) { - super(provider, delayRetryPolicy); - } - - @Override - public final void call() throws KeeperException, InterruptedException { - if (count < 2) { - count++; - - // need dependent zk beat version - //((BaseProvider)getProvider()).getHolder().getZooKeeper().getTestable().injectSessionExpiration(); - ((BaseProvider) getProvider()).getHolder().close(); - } - test(); - } - - /** - * Test exec. - * - * @throws KeeperException Zookeeper Exception - * @throws InterruptedException InterruptedException - */ - public abstract void test() throws KeeperException, InterruptedException; -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/TestResultCallable.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/TestResultCallable.java deleted file mode 100644 index 15bf4af5f832e..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/retry/TestResultCallable.java +++ /dev/null @@ -1,51 +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.orchestration.reg.zookeeper.natived.client.retry; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.provider.BaseProvider; -import org.apache.zookeeper.KeeperException; - -public abstract class TestResultCallable extends RetryResultCallable { - - private int count; - - public TestResultCallable(final IProvider provider, final DelayRetryPolicy delayRetryPolicy) { - super(provider, delayRetryPolicy); - } - - @Override - public final void call() throws KeeperException, InterruptedException { - if (count < 2) { - count++; - - // need dependent zk beat version - //((BaseProvider)getProvider()).getHolder().getZooKeeper().getTestable().injectSessionExpiration(); - ((BaseProvider) getProvider()).getHolder().close(); - } - test(); - } - - /** - * Test exec. - * - * @throws KeeperException Zookeeper Exception - * @throws InterruptedException InterruptedException - */ - public abstract void test() throws KeeperException, InterruptedException; -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/util/EmbedTestingServer.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/util/EmbedTestingServer.java deleted file mode 100644 index f3713472fdf67..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/util/EmbedTestingServer.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.orchestration.reg.zookeeper.natived.client.util; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.NativeZookeeperExceptionHandler; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; -import org.apache.curator.test.TestingServer; - -import java.io.File; -import java.io.IOException; - -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class EmbedTestingServer { - - private static final int PORT = 3181; - - private static volatile TestingServer testingServer; - - /** - * Start embed zookeeper server. - */ - public static void start() { - if (null != testingServer) { - return; - } - try { - testingServer = new TestingServer(PORT, new File(String.format("target/test_zk_data/%s/", System.nanoTime()))); - // CHECKSTYLE:OFF - } catch (final Exception ex) { - // CHECKSTYLE:ON - NativeZookeeperExceptionHandler.handleException(ex); - } finally { - Runtime.getRuntime().addShutdownHook(new Thread() { - - @Override - public void run() { - try { - testingServer.close(); - } catch (final IOException ex) { - NativeZookeeperExceptionHandler.handleException(ex); - } - } - }); - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/AllBaseTests.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/AllBaseTests.java deleted file mode 100644 index f7a6a1c50c16f..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/AllBaseTests.java +++ /dev/null @@ -1,28 +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.orchestration.reg.zookeeper.natived.client.zookeeper; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.StartWaitTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses(StartWaitTest.class) -public final class AllBaseTests { -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/SyncRetryStrategyTest.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/SyncRetryStrategyTest.java deleted file mode 100644 index c68e6a78edb91..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/SyncRetryStrategyTest.java +++ /dev/null @@ -1,237 +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.orchestration.reg.zookeeper.natived.client.zookeeper; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IProvider; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.DelayRetryPolicy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.TestCallable; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.retry.TestResultCallable; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.TestSupport; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.StrategyType; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.UsualStrategy; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.ZooDefs; -import org.junit.Test; - -import java.io.IOException; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -public final class SyncRetryStrategyTest extends UsualClientTest { - - private IProvider provider; - - @Override - protected IClient createClient(final ClientFactory creator) throws IOException, InterruptedException { - final IClient client = creator.setClientNamespace(TestSupport.ROOT).authorization(TestSupport.AUTH, TestSupport.AUTH.getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL) - .newClient(TestSupport.SERVERS, TestSupport.SESSION_TIMEOUT).start(); - client.useExecStrategy(StrategyType.SYNC_RETRY); - provider = client.getExecStrategy().getProvider(); - return client; - } - - @Test - public void createChild() throws KeeperException, InterruptedException { - final String key = "a/b/bb"; - new UsualStrategy(provider).deleteCurrentBranch(key); - TestCallable callable = new TestCallable(provider, DelayRetryPolicy.defaultDelayPolicy()) { - - @Override - public void test() throws KeeperException, InterruptedException { - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().createAllNeedPath(key, "bbb11", CreateMode.PERSISTENT); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - } - }; - callable.exec(); - assertTrue(getTestClient().checkExists(key)); - new UsualStrategy(provider).deleteCurrentBranch(key); - assertFalse(getTestClient().checkExists(key)); - } - - @Test - public void deleteBranch() throws KeeperException, InterruptedException { - final String keyB = "a/b/bb"; - final String value = "bbb11"; - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().createAllNeedPath(keyB, value, CreateMode.PERSISTENT); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - - assertTrue(getTestClient().checkExists(keyB)); - final String keyC = "a/c/cc"; - new UsualStrategy(provider).createAllNeedPath(keyC, "ccc11", CreateMode.PERSISTENT); - assertTrue(getTestClient().checkExists(keyC)); - - TestCallable callable = getDeleteBranch(keyC); - callable.exec(); - assertFalse(getTestClient().checkExists(keyC)); - assertTrue(getTestClient().checkExists("a")); - - callable = getDeleteBranch(keyB); - callable.exec(); - assertFalse(getTestClient().checkExists(PathUtil.checkPath(TestSupport.ROOT))); - getTestClient().createAllNeedPath(keyB, "bbb11", CreateMode.PERSISTENT); - assertTrue(getTestClient().checkExists(keyB)); - - callable.exec(); - assertFalse(getTestClient().checkExists(PathUtil.checkPath(TestSupport.ROOT))); - } - - private TestCallable getDeleteBranch(final String key) { - return new TestCallable(provider, DelayRetryPolicy.defaultDelayPolicy()) { - - @Override - public void test() throws KeeperException, InterruptedException { - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().deleteCurrentBranch(key); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - } - }; - } - - @Test - public void isExisted() throws KeeperException, InterruptedException { - final String key = "a/b/bb"; - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().createAllNeedPath(key, "", CreateMode.PERSISTENT); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - - TestResultCallable callable = new TestResultCallable(provider, DelayRetryPolicy.defaultDelayPolicy()) { - - @Override - public void test() throws KeeperException, InterruptedException { - setResult(provider.exists(provider.getRealPath(key))); - } - }; - assertTrue(callable.getResult()); - - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().deleteCurrentBranch(key); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - } - - @Test - public void get() throws KeeperException, InterruptedException { - final String key = "a/b"; - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().createAllNeedPath(key, "bbb11", CreateMode.PERSISTENT); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - - TestResultCallable callable = getData("a"); - assertThat(callable.getResult(), is("")); - callable = getData(key); - assertThat(callable.getResult(), is("bbb11")); - - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().deleteCurrentBranch(key); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - } - - private TestResultCallable getData(final String key) { - return new TestResultCallable(provider, DelayRetryPolicy.defaultDelayPolicy()) { - - @Override - public void test() throws KeeperException, InterruptedException { - setResult(new String(provider.getData(provider.getRealPath(key)))); - } - }; - } - - @Test - public void getChildrenKeys() throws KeeperException, InterruptedException { - final String key = "a/b"; - final String current = "a"; - - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().createAllNeedPath(key, "", CreateMode.PERSISTENT); - getTestClient().createAllNeedPath("a/c", "", CreateMode.PERSISTENT); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - - final TestResultCallable> callable = new TestResultCallable>(provider, DelayRetryPolicy.defaultDelayPolicy()) { - - @Override - public void test() throws KeeperException, InterruptedException { - setResult(provider.getChildren(provider.getRealPath(current))); - } - }; - final List result = callable.getResult(); - Collections.sort(result, new Comparator() { - public int compare(final String o1, final String o2) { - return o2.compareTo(o1); - } - }); - assertThat(result.get(0), is("c")); - assertThat(result.get(1), is("b")); - - getTestClient().useExecStrategy(StrategyType.USUAL); - getTestClient().deleteAllChildren(PathUtil.checkPath(TestSupport.ROOT)); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - } - - @Test - public void update() throws KeeperException, InterruptedException { - final String key = "a"; - final String value = "aa"; - final String newValue = "aaa"; - getTestClient().deleteCurrentBranch(key); - getTestClient().createAllNeedPath(key, value, CreateMode.PERSISTENT); - assertThat(getTestClient().getDataString(key), is(value)); - - final TestCallable callable = new TestCallable(provider, DelayRetryPolicy.defaultDelayPolicy()) { - - @Override - public void test() throws KeeperException, InterruptedException { - provider.update(provider.getRealPath(key), newValue); - } - }; - callable.exec(); - assertThat(getTestClient().getDataString(key), is(newValue)); - getTestClient().deleteCurrentBranch(key); - } - - @Test - public void delAllChildren() throws KeeperException, InterruptedException { - String key = "a/b/bb"; - getTestClient().createAllNeedPath(key, "bb", CreateMode.PERSISTENT); - key = "a/c/cc"; - getTestClient().createAllNeedPath(key, "cc", CreateMode.PERSISTENT); - assertNotNull(getZooKeeper(getTestClient()).exists(PathUtil.getRealPath(TestSupport.ROOT, key), false)); - - TestCallable callable = new TestCallable(provider, DelayRetryPolicy.defaultDelayPolicy()) { - @Override - public void test() throws KeeperException, InterruptedException { - new UsualStrategy(provider).deleteAllChildren("a"); - } - }; - callable.exec(); - assertNull(getZooKeeper(getTestClient()).exists(PathUtil.getRealPath(TestSupport.ROOT, key), false)); - assertNotNull(getZooKeeper(getTestClient()).exists(PathUtil.checkPath(TestSupport.ROOT), false)); - super.deleteRoot(getTestClient()); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/UsualClientTest.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/UsualClientTest.java deleted file mode 100644 index d1a30154c65eb..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/UsualClientTest.java +++ /dev/null @@ -1,163 +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.orchestration.reg.zookeeper.natived.client.zookeeper; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.BaseClientTest; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.base.TestSupport; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.StrategyType; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.AsyncRetryStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.ContentionStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.SyncRetryStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.TransactionContendStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.strategy.UsualStrategy; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.transaction.BaseTransaction; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.ZooDefs; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -public class UsualClientTest extends BaseClientTest { - - @Override - protected IClient createClient(final ClientFactory creator) throws IOException, InterruptedException { - return creator.setClientNamespace(TestSupport.ROOT).authorization(TestSupport.AUTH, TestSupport.AUTH.getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL) - .newClient(TestSupport.SERVERS, TestSupport.SESSION_TIMEOUT).start(); - } - - @Test - public void assertUseExecStrategy() { - getTestClient().useExecStrategy(StrategyType.CONTEND); - assertThat(getTestClient().getExecStrategy().getClass().getName(), is(ContentionStrategy.class.getName())); - getTestClient().useExecStrategy(StrategyType.TRANSACTION_CONTEND); - assertThat(getTestClient().getExecStrategy().getClass().getName(), is(TransactionContendStrategy.class.getName())); - getTestClient().useExecStrategy(StrategyType.SYNC_RETRY); - assertThat(getTestClient().getExecStrategy().getClass().getName(), is(SyncRetryStrategy.class.getName())); - getTestClient().useExecStrategy(StrategyType.ASYNC_RETRY); - assertThat(getTestClient().getExecStrategy().getClass().getName(), is(AsyncRetryStrategy.class.getName())); - getTestClient().useExecStrategy(StrategyType.USUAL); - assertThat(getTestClient().getExecStrategy().getClass().getName(), is(UsualStrategy.class.getName())); - } - - @Test - public void assertGetData() throws KeeperException, InterruptedException { - String key = "a/b/bb"; - String value = "bbb11"; - getTestClient().createAllNeedPath(key, value, CreateMode.PERSISTENT); - assertThat(getTestClient().getDataString(key), is(value)); - getTestClient().deleteCurrentBranch(key); - } - - @Test - public void assertCreateRoot() throws KeeperException, InterruptedException { - super.createRoot(getTestClient()); - } - - @Test - public void assertCreateChild() throws KeeperException, InterruptedException { - super.createChild(getTestClient()); - } - - @Test - public void assertDeleteBranch() throws KeeperException, InterruptedException { - super.deleteBranch(getTestClient()); - } - - @Test - public void assertExisted() throws KeeperException, InterruptedException { - super.isExisted(getTestClient()); - } - - @Test - public void assertGet() throws KeeperException, InterruptedException { - super.get(getTestClient()); - } - - @Test - public void assertAsyncGet() throws KeeperException, InterruptedException { - super.asyncGet(getTestClient()); - } - - @Test - public void assertGetChildrenKeys() throws KeeperException, InterruptedException { - super.getChildrenKeys(getTestClient()); - } - - @Test - public void assertPersist() throws KeeperException, InterruptedException { - super.persist(getTestClient()); - } - - @Test - public void assertPersistEphemeral() throws KeeperException, InterruptedException { - super.persistEphemeral(getTestClient()); - } - - @Test - public void assertDelAllChildren() throws KeeperException, InterruptedException { - super.delAllChildren(getTestClient()); - } - - @Test - public void assertWatch() throws KeeperException, InterruptedException { - super.watch(getTestClient()); - } - - @Test - public void assertWatchRegister() throws KeeperException, InterruptedException { - super.watchRegister(getTestClient()); - } - - @Test - public void assertClose() { - super.close(getTestClient()); - } - - @Test - public void assertDeleteOnlyCurrent() throws KeeperException, InterruptedException { - String key = "key"; - String value = "value"; - getTestClient().createCurrentOnly(key, value, CreateMode.PERSISTENT); - assertThat(getTestClient().getDataString(key), is(value)); - assertTrue(getTestClient().checkExists(key)); - getTestClient().deleteOnlyCurrent(key); - assertFalse(getTestClient().checkExists(key)); - deleteRoot(getTestClient()); - } - - @Test - public void assertTransaction() throws KeeperException, InterruptedException { - String key = "key"; - String value = "value"; - BaseTransaction transaction = getTestClient().transaction(); - getTestClient().createCurrentOnly(key, value, CreateMode.PERSISTENT); - transaction.setData(key, value.getBytes(ZookeeperConstants.UTF_8)); - transaction.commit(); - assertThat(getTestClient().getDataString(key), is(value)); - getTestClient().deleteOnlyCurrent(key); - deleteRoot(getTestClient()); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClientTest.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClientTest.java deleted file mode 100644 index 18f725adf0766..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseClientTest.java +++ /dev/null @@ -1,321 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.util.EmbedTestingServer; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.PathUtil; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.utility.ZookeeperConstants; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.ClientFactory; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import lombok.Getter; -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.ZooKeeper; -import org.apache.zookeeper.data.Stat; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.CountDownLatch; - -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -@Getter -public abstract class BaseClientTest extends BaseTest { - - private IClient testClient; - - @Before - public void start() throws IOException, InterruptedException { - EmbedTestingServer.start(); - ClientFactory creator = new ClientFactory(); - testClient = createClient(creator); - getZooKeeper(testClient); - } - - protected final ZooKeeper getZooKeeper(final IClient client) { - return ((BaseClient) client).getHolder().getZooKeeper(); - } - - protected abstract IClient createClient(ClientFactory creator) throws IOException, InterruptedException; - - @After - public void stop() { - testClient.close(); - testClient = null; - } - - @Test - public void assertDeleteRoot() throws KeeperException, InterruptedException { - ((BaseClient) testClient).createNamespace(); - deleteRoot(testClient); - assertNull(getZooKeeper(testClient).exists(ZookeeperConstants.PATH_SEPARATOR + TestSupport.ROOT, false)); - } - - protected final void createRoot(final IClient client) throws KeeperException, InterruptedException { - ((BaseClient) client).createNamespace(); - assertNotNull(getZooKeeper(client).exists(ZookeeperConstants.PATH_SEPARATOR + TestSupport.ROOT, false)); - ((BaseClient) client).deleteNamespace(); - assertNull(getZooKeeper(client).exists(ZookeeperConstants.PATH_SEPARATOR + TestSupport.ROOT, false)); - } - - protected final void createChild(final IClient client) throws KeeperException, InterruptedException { - String key = "a/b/bb"; - client.createAllNeedPath(key, "bbb11", CreateMode.PERSISTENT); - assertNotNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, key), false)); - client.deleteCurrentBranch(key); - assertNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, key), false)); - } - - protected final void deleteBranch(final IClient client) throws KeeperException, InterruptedException { - String keyB = "a/b/bb"; - String valueB = "bbb11"; - client.createAllNeedPath(keyB, valueB, CreateMode.PERSISTENT); - assertNotNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, keyB), false)); - String keyC = "a/c/cc"; - client.createAllNeedPath(keyC, "ccc11", CreateMode.PERSISTENT); - assertNotNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, keyC), false)); - client.deleteCurrentBranch(keyC); - assertNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, keyC), false)); - assertNotNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, "a"), false)); - client.deleteCurrentBranch(keyB); - assertNull(getZooKeeper(client).exists(PathUtil.checkPath(TestSupport.ROOT), false)); - client.createAllNeedPath(keyB, valueB, CreateMode.PERSISTENT); - assertNotNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, keyB), false)); - assertThat(client.getDataString(keyB), is(valueB)); - client.deleteCurrentBranch(keyB); - assertNull(getZooKeeper(client).exists(PathUtil.checkPath(TestSupport.ROOT), false)); - } - - protected final void isExisted(final IClient client) throws KeeperException, InterruptedException { - String key = "a/b/bb"; - client.createAllNeedPath(key, "", CreateMode.PERSISTENT); - assertTrue(isExisted(key, client)); - client.deleteCurrentBranch(key); - } - - private boolean isExisted(final String key, final IClient client) throws KeeperException, InterruptedException { - return client.checkExists(key); - } - - protected final void get(final IClient client) throws KeeperException, InterruptedException { - String value = "bbb11"; - client.createAllNeedPath("a/b", value, CreateMode.PERSISTENT); - String key = "a"; - assertThat(getDirectly(key, client), is("")); - key = "a/b"; - assertThat(getDirectly(key, client), is(value)); - client.deleteCurrentBranch("a/b"); - } - - protected final void asyncGet(final IClient client) throws KeeperException, InterruptedException { - final CountDownLatch ready = new CountDownLatch(1); - String key = "a/b"; - String value = "bbb11"; - client.createAllNeedPath(key, value, CreateMode.PERSISTENT); - AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() { - @Override - public void processResult(final int rc, final String path, final Object ctx, final byte[] data, final Stat stat) { - assertThat(new String(data), is(ctx)); - ready.countDown(); - } - }; - client.getData(key, callback, value); - ready.await(); - client.deleteCurrentBranch("a/b"); - } - - private String getDirectly(final String key, final IClient client) throws KeeperException, InterruptedException { - return new String(client.getData(key)); - } - - protected final void getChildrenKeys(final IClient client) throws KeeperException, InterruptedException { - String key = "a/b"; - String current = "a"; - client.createAllNeedPath(key, "", CreateMode.PERSISTENT); - List result = client.getChildren(current); - Collections.sort(result, new Comparator() { - - public int compare(final String o1, final String o2) { - return o2.compareTo(o1); - } - }); - assertThat(result.get(0), is("b")); - client.deleteCurrentBranch(key); - } - - protected final void persist(final IClient client) throws KeeperException, InterruptedException { - String key = "a"; - String value = "aa"; - String newValue = "aaa"; - if (!isExisted(key, client)) { - client.createAllNeedPath(key, value, CreateMode.PERSISTENT); - } else { - updateWithCheck(key, value, client); - } - - assertThat(getDirectly(key, client), is(value)); - - updateWithCheck(key, newValue, client); - assertThat(getDirectly(key, client), is(newValue)); - client.deleteCurrentBranch(key); - } - - private void updateWithCheck(final String key, final String value, final IClient client) throws KeeperException, InterruptedException { - client.update(key, value); - } - - protected final void persistEphemeral(final IClient client) throws KeeperException, InterruptedException { - String key = "a/b/bb"; - String value = "b1b"; - client.createAllNeedPath(key, value, CreateMode.PERSISTENT); - Stat stat = new Stat(); - getZooKeeper(client).getData(PathUtil.getRealPath(TestSupport.ROOT, key), false, stat); - assertThat(stat.getEphemeralOwner(), is(0L)); - - client.deleteAllChildren(key); - assertFalse(isExisted(key, client)); - client.createAllNeedPath(key, value, CreateMode.EPHEMERAL); - - assertThat(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, key), null).getEphemeralOwner(), is(getZooKeeper(client).getSessionId())); - client.deleteCurrentBranch(key); - } - - protected final void delAllChildren(final IClient client) throws KeeperException, InterruptedException { - String key = "a/b/bb"; - client.createAllNeedPath(key, "bb", CreateMode.PERSISTENT); - key = "a/c/cc"; - client.createAllNeedPath(key, "cc", CreateMode.PERSISTENT); - assertNotNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, key), false)); - client.deleteAllChildren("a"); - assertNull(getZooKeeper(client).exists(PathUtil.getRealPath(TestSupport.ROOT, key), false)); - assertNotNull(getZooKeeper(client).exists("/" + TestSupport.ROOT, false)); - ((BaseClient) client).deleteNamespace(); - } - - protected final void watch(final IClient client) throws KeeperException, InterruptedException { - List actual = new ArrayList<>(); - final ZookeeperEventListener zookeeperEventListener = buildListener(client, actual); - - String key = "a"; - client.registerWatch(key, zookeeperEventListener); - client.createCurrentOnly(key, "aaa", CreateMode.EPHEMERAL); - client.checkExists(key, new Watcher() { - - @Override - public void process(final WatchedEvent event) { - zookeeperEventListener.process(event); - } - }); - String value = "value0"; - client.update(key, value); - assertThat(client.getDataString(key), is(value)); - sleep(200); - - String value1 = "value1"; - client.update(key, value1); - assertThat(client.getDataString(key), is(value1)); - sleep(200); - - String value2 = "value2"; - client.update(key, value2); - assertThat(client.getDataString(key), is(value2)); - sleep(200); - - client.deleteCurrentBranch(key); - sleep(200); - - //The acquisition value is after the reception of the event, - //so the value may be not equal. - assertThat(actual, hasItems("update_/test/a_value0", "update_/test/a_value1", "update_/test/a_value2", "delete_/test/a_")); - client.unregisterWatch(zookeeperEventListener.getKey()); - } - - protected final void watchRegister(final IClient client) throws KeeperException, InterruptedException { - List actual = new ArrayList<>(); - - final ZookeeperEventListener zookeeperEventListener = buildListener(client, actual); - - String key = "a"; - client.registerWatch(key, zookeeperEventListener); - client.createCurrentOnly(key, "aaa", CreateMode.EPHEMERAL); - sleep(100); - - String value = "value0"; - client.update(key, value); - sleep(100); - - String value1 = "value1"; - client.update(key, value1); - sleep(100); - - String value2 = "value2"; - client.update(key, value2); - sleep(100); - - client.deleteCurrentBranch(key); - sleep(100); - - //The acquisition value is after the reception of the event, - //so the value may be not equal. - assertThat(actual, hasItems("update_/test/a_value0", "update_/test/a_value1", "update_/test/a_value2", "delete_/test/a_")); - client.unregisterWatch(zookeeperEventListener.getKey()); - } - - private ZookeeperEventListener buildListener(final IClient client, final List actual) { - return new ZookeeperEventListener(null) { - - @Override - public void process(final WatchedEvent event) { - switch (event.getType()) { - case NodeDataChanged: - case NodeChildrenChanged: - try { - actual.add("update_" + event.getPath() + "_" + client.getDataString(event.getPath())); - } catch (final KeeperException | InterruptedException ignored) { - } - break; - case NodeDeleted: - actual.add("delete_" + event.getPath() + "_"); - break; - default: - } - } - }; - } - - protected final void close(final IClient client) { - client.close(); - assertThat(getZooKeeper(client).getState(), is(ZooKeeper.States.CLOSED)); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseTest.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseTest.java deleted file mode 100644 index 4ef59decefb1a..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/BaseTest.java +++ /dev/null @@ -1,39 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import org.apache.zookeeper.KeeperException; - -public class BaseTest { - - protected final void createRootOnly(final IClient client) throws KeeperException, InterruptedException { - ((BaseClient) client).createNamespace(); - } - - protected final void deleteRoot(final IClient client) throws KeeperException, InterruptedException { - ((BaseClient) client).deleteNamespace(); - } - - protected final void sleep(final long tick) { - try { - Thread.sleep(tick); - } catch (final InterruptedException ignore) { - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/StartWaitTest.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/StartWaitTest.java deleted file mode 100644 index 5f213fba77cbd..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/StartWaitTest.java +++ /dev/null @@ -1,50 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.action.IClient; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.util.EmbedTestingServer; -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ClientContext; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -public class StartWaitTest { - - @Before - public void start() { - EmbedTestingServer.start(); - } - - @Test - public void assertStart() throws IOException, InterruptedException { - IClient testClient = new TestClient(new ClientContext(TestSupport.SERVERS, TestSupport.SESSION_TIMEOUT)); - Assert.assertTrue(testClient.start(10000, TimeUnit.MILLISECONDS)); - testClient.close(); - } - - @Test - public void assertNotStart() throws IOException, InterruptedException { - TestClient testClient = new TestClient(new ClientContext(TestSupport.SERVERS, TestSupport.SESSION_TIMEOUT)); - Assert.assertFalse(testClient.start(100, TimeUnit.MILLISECONDS)); - testClient.close(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestClient.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestClient.java deleted file mode 100644 index 04b44851895db..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestClient.java +++ /dev/null @@ -1,47 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.UsualClient; -import org.apache.zookeeper.ZooKeeper; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -public final class TestClient extends UsualClient { - - TestClient(final BaseContext context) { - super(context); - } - - @Override - public synchronized boolean start(final int waitingTime, final TimeUnit timeUnit) throws InterruptedException, IOException { - setHolder(new TestHolder(getContext())); - getHolder().start(waitingTime, timeUnit); - return getHolder().isConnected(); - } - - /** - * Get zookeeper. - * - * @return zookeeper - */ - public ZooKeeper getZookeeper() { - return getHolder().getZooKeeper(); - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestHolder.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestHolder.java deleted file mode 100644 index 1c5c760457f09..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestHolder.java +++ /dev/null @@ -1,54 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; - -import java.io.IOException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public final class TestHolder extends Holder { - - private final CountDownLatch connecting = new CountDownLatch(1); - - public TestHolder(final BaseContext context) { - super(context); - } - - @Override - protected void start(final int wait, final TimeUnit units) throws IOException, InterruptedException { - initZookeeper(); - connecting.await(wait, units); - } - - @Override - protected void processConnection(final WatchedEvent event) { - if (Watcher.Event.EventType.None == event.getType()) { - if (Watcher.Event.KeeperState.SyncConnected == event.getState()) { - try { - Thread.sleep(1000); - } catch (final InterruptedException ignored) { - } - this.setConnected(true); - connecting.countDown(); - } - } - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestSupport.java b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestSupport.java deleted file mode 100644 index e75fdc9ac38d4..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/java/io/shardingsphere/orchestration/reg/zookeeper/natived/client/zookeeper/base/TestSupport.java +++ /dev/null @@ -1,52 +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.orchestration.reg.zookeeper.natived.client.zookeeper.base; - -import io.shardingsphere.orchestration.reg.zookeeper.natived.client.zookeeper.section.ZookeeperEventListener; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.zookeeper.WatchedEvent; - -@NoArgsConstructor(access = AccessLevel.PRIVATE) -@Slf4j -public final class TestSupport { - - public static final String AUTH = "digest"; - - public static final String SERVERS = "localhost:3181"; - - public static final int SESSION_TIMEOUT = 200000; - - public static final String ROOT = "test"; - - /** - * Test exec. - * - * @return listener ZookeeperEventListener - */ - public static ZookeeperEventListener buildListener() { - return new ZookeeperEventListener() { - - @Override - public void process(final WatchedEvent event) { - log.debug(event.toString()); - } - }; - } -} diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/resources/logback-test.xml b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/resources/logback-test.xml deleted file mode 100644 index 0ac5601568948..0000000000000 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-native-zookeeper/src/test/resources/logback-test.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - [%-5level] %d{HH:mm:ss.SSS} [%thread] %logger{36} - %msg%n - - - - - - - - - - - - - - diff --git a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-zookeeper-curator/pom.xml b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-zookeeper-curator/pom.xml index c1b0d55d6c893..11f7fcb4f0273 100644 --- a/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-zookeeper-curator/pom.xml +++ b/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-zookeeper-curator/pom.xml @@ -29,5 +29,10 @@ org.apache.curator curator-recipes
+ + + org.apache.curator + curator-test + From 768b740cacc29e75213762fa45a56dadc03ad719 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 18 Oct 2018 22:29:07 +0800 Subject: [PATCH 03/10] use initShardingMetaData --- .../shardingsphere/shardingproxy/runtime/GlobalRegistry.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java index a104c077b42d1..19648c9365a9f 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java @@ -35,6 +35,7 @@ import io.shardingsphere.orchestration.internal.event.state.ProxyDisabledStateEventBusEvent; import io.shardingsphere.orchestration.internal.rule.OrchestrationMasterSlaveRule; import io.shardingsphere.orchestration.internal.rule.OrchestrationShardingRule; +import io.shardingsphere.shardingproxy.backend.BackendExecutorContext; import io.shardingsphere.shardingproxy.runtime.nio.BackendNIOConfiguration; import lombok.AccessLevel; import lombok.Getter; @@ -125,6 +126,7 @@ public void init(final YamlServerConfiguration serverConfig, final Map Date: Thu, 18 Oct 2018 22:29:20 +0800 Subject: [PATCH 04/10] delete ShardingProxy() --- .../shardingsphere/shardingproxy/frontend/ShardingProxy.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java index 7edc83a17f262..65158e970b4fc 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java @@ -54,10 +54,6 @@ public final class ShardingProxy { private EventLoopGroup userGroup; - public ShardingProxy() { - GLOBAL_REGISTRY.initShardingMetaData(backendExecutorContext.getExecuteEngine()); - } - /** * Start Sharding-Proxy. * From da5558ca9a086e667ab698bd176287de8ec57ad1 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 18 Oct 2018 22:29:53 +0800 Subject: [PATCH 05/10] use private --- .../shardingproxy/runtime/GlobalRegistry.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java index 19648c9365a9f..763fc0dc9e225 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java @@ -148,12 +148,7 @@ private void initServerConfiguration(final YamlServerConfiguration serverConfig) authentication = serverConfig.getAuthentication(); } - /** - * Initialize sharding meta data. - * - * @param executeEngine sharding execute engine - */ - public void initShardingMetaData(final ShardingExecuteEngine executeEngine) { + private void initShardingMetaData(final ShardingExecuteEngine executeEngine) { for (ShardingSchema each : shardingSchemas.values()) { each.initShardingMetaData(executeEngine); } From cde48bcf57b3ed616e39fd63563cd464289f3965 Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 18 Oct 2018 22:39:23 +0800 Subject: [PATCH 06/10] add author --- .../io/shardingsphere/shardingproxy/frontend/ShardingProxy.java | 1 + 1 file changed, 1 insertion(+) diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java index 65158e970b4fc..b1b50a53c7593 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java @@ -41,6 +41,7 @@ * @author zhangliang * @author xiaoyu * @author wangkai + * @author panjuan */ public final class ShardingProxy { From 29d02669a8870b96fa83a3926f0ac811b20439ee Mon Sep 17 00:00:00 2001 From: tristaZero Date: Thu, 18 Oct 2018 22:39:59 +0800 Subject: [PATCH 07/10] java doc --- .../io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java | 1 + 1 file changed, 1 insertion(+) diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java index 763fc0dc9e225..549cae2bfeaa7 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java @@ -53,6 +53,7 @@ * Global registry. * * @author chenqingyang + * @author panjuan */ @NoArgsConstructor(access = AccessLevel.PRIVATE) @Getter From 400324fd80fe70f8a032eab03b1e3a0a7308053b Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 18 Oct 2018 23:24:52 +0800 Subject: [PATCH 08/10] add comparable for SQLToken --- .../core/parsing/SQLJudgeEngine.java | 10 +- .../clause/InsertColumnsClauseParser.java | 6 +- .../parser/clause/InsertSetClauseParser.java | 4 +- .../clause/InsertValuesClauseParser.java | 2 +- .../parser/clause/SelectListClauseParser.java | 2 +- .../clause/TableReferencesClauseParser.java | 6 +- .../clause/UpdateSetItemsClauseParser.java | 2 +- .../parser/clause/WhereClauseParser.java | 4 +- .../expression/AliasExpressionParser.java | 2 +- .../expression/BasicExpressionParser.java | 2 +- .../mysql/clause/MySQLLimitClauseParser.java | 10 +- .../dialect/mysql/sql/MySQLShowParser.java | 10 +- .../clause/PostgreSQLLimitClauseParser.java | 4 +- .../clause/SQLServerTopClauseParser.java | 2 +- .../parser/sql/AbstractSQLStatement.java | 13 +- .../core/parsing/parser/sql/SQLStatement.java | 13 +- .../index/AbstractCreateIndexParser.java | 2 +- .../drop/index/AbstractDropIndexParser.java | 4 +- .../sql/dml/insert/AbstractInsertParser.java | 2 +- .../sql/dml/insert/InsertStatement.java | 8 +- .../sql/dql/select/AbstractSelectParser.java | 4 +- .../sql/dql/select/SelectStatement.java | 9 +- .../parser/token/GeneratedKeyToken.java | 11 +- .../core/parsing/parser/token/IndexToken.java | 13 +- .../parser/token/InsertColumnToken.java | 11 +- .../parser/token/InsertValuesToken.java | 11 +- .../core/parsing/parser/token/ItemsToken.java | 10 +- .../parsing/parser/token/OffsetToken.java | 11 +- .../parsing/parser/token/OrderByToken.java | 11 +- .../parsing/parser/token/RemoveToken.java | 11 +- .../parsing/parser/token/RowCountToken.java | 11 +- .../core/parsing/parser/token/SQLToken.java | 19 +- .../parsing/parser/token/SchemaToken.java | 13 +- .../core/parsing/parser/token/TableToken.java | 12 +- .../core/rewrite/SQLRewriteEngine.java | 22 +-- .../TableBroadcastRoutingEngine.java | 7 +- .../optimizer/InsertOptimizeEngineTest.java | 4 +- .../integrate/asserts/SQLStatementAssert.java | 2 +- .../token/GeneratedKeyTokenAssert.java | 6 +- .../asserts/token/IndexTokenAssert.java | 6 +- .../token/InsertValuesTokenAssert.java | 6 +- .../asserts/token/ItemsTokenAssert.java | 6 +- .../asserts/token/OffsetTokenAssert.java | 6 +- .../asserts/token/OrderByTokenAssert.java | 6 +- .../asserts/token/RowCountTokenAssert.java | 6 +- .../asserts/token/SchemaTokenAssert.java | 5 +- .../asserts/token/TableTokenAssert.java | 5 +- .../integrate/asserts/token/TokenAssert.java | 4 +- .../core/rewrite/SQLRewriteEngineTest.java | 166 +++++++++--------- .../TableBroadcastRoutingEngineTest.java | 2 +- .../backend/BackendHandlerFactory.java | 7 +- .../rewrite/MasterSlaveSQLRewriteEngine.java | 27 +-- 52 files changed, 279 insertions(+), 279 deletions(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/SQLJudgeEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/SQLJudgeEngine.java index 4dad01a143ae6..5db73834f07db 100755 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/SQLJudgeEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/SQLJudgeEngine.java @@ -161,7 +161,7 @@ private DALStatement parseShowTables(final LexerEngine lexerEngine) { DALStatement result = new ShowTablesStatement(); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.getSqlTokens().add(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), null)); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), null)); } return result; } @@ -172,7 +172,7 @@ private DALStatement parseShowColumnsFields(final LexerEngine lexerEngine) { parseSingleTableWithSchema(lexerEngine, result); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.getSqlTokens().add(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), null)); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), null)); } return result; } @@ -182,7 +182,7 @@ private void parseSingleTableWithSchema(final LexerEngine lexerEngine, final SQL String literals = lexerEngine.getCurrentToken().getLiterals(); lexerEngine.nextToken(); if (lexerEngine.skipIfEqual(Symbol.DOT)) { - sqlStatement.getSqlTokens().add(new SchemaToken(beginPosition, literals, null)); + sqlStatement.addSQLToken(new SchemaToken(beginPosition, literals, null)); lexerEngine.nextToken(); } } @@ -193,7 +193,7 @@ private DALStatement parseShowIndex(final LexerEngine lexerEngine) { parseSingleTableWithSchema(lexerEngine, result); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.getSqlTokens().add(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), null)); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), null)); } return result; } @@ -203,7 +203,7 @@ private DALStatement parseShowTableStatus(final LexerEngine lexerEngine) { lexerEngine.nextToken(); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.getSqlTokens().add(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), null)); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), null)); } return result; } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java index f02b00333de2e..616329150527f 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java @@ -105,7 +105,7 @@ private Collection parseWithoutColumn( final InsertStatement insertStatement, final ShardingTableMetaData shardingTableMetaData, final String tableName, final Optional generateKeyColumn) { int count = 0; int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length() - 1; - insertStatement.getSqlTokens().add(new InsertColumnToken(beginPosition, "(")); + insertStatement.addSQLToken(new InsertColumnToken(beginPosition, "(")); ItemsToken columnsToken = new ItemsToken(beginPosition); columnsToken.setFirstOfItemsSpecial(true); Collection result = new LinkedList<>(); @@ -119,8 +119,8 @@ private Collection parseWithoutColumn( count++; } } - insertStatement.getSqlTokens().add(columnsToken); - insertStatement.getSqlTokens().add(new InsertColumnToken(beginPosition, ")")); + insertStatement.addSQLToken(columnsToken); + insertStatement.addSQLToken(new InsertColumnToken(beginPosition, ")")); insertStatement.setColumnsListLastPosition(beginPosition); return result; } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertSetClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertSetClauseParser.java index dd21f9186c637..3cf0315e19d94 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertSetClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertSetClauseParser.java @@ -77,7 +77,7 @@ public void parse(final InsertStatement insertStatement) { removeUnnecessaryToken(insertStatement); insertStatement.setGenerateKeyColumnIndex(-1); int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - insertStatement.getSqlTokens().add(new InsertValuesToken(beginPosition, insertStatement.getTables().getSingleTableName())); + insertStatement.addSQLToken(new InsertValuesToken(beginPosition, insertStatement.getTables().getSingleTableName())); String tableName = insertStatement.getTables().getSingleTableName(); Optional generateKeyColumn = shardingRule.getGenerateKeyColumn(tableName); int count = 0; @@ -111,7 +111,7 @@ public void parse(final InsertStatement insertStatement) { } private void removeUnnecessaryToken(final InsertStatement insertStatement) { - Iterator sqlTokens = insertStatement.getSqlTokens().iterator(); + Iterator sqlTokens = insertStatement.getSQLTokens().iterator(); while (sqlTokens.hasNext()) { SQLToken sqlToken = sqlTokens.next(); if (sqlToken instanceof InsertColumnToken || sqlToken instanceof ItemsToken) { diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertValuesClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertValuesClauseParser.java index 806e444bd4324..06d9dff104209 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertValuesClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertValuesClauseParser.java @@ -91,7 +91,7 @@ private void parseValues(final InsertStatement insertStatement) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); int endPosition; int startParametersIndex; - insertStatement.getSqlTokens().add(new InsertValuesToken(beginPosition, insertStatement.getTables().getSingleTableName())); + insertStatement.addSQLToken(new InsertValuesToken(beginPosition, insertStatement.getTables().getSingleTableName())); do { beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); startParametersIndex = insertStatement.getParametersIndex(); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/SelectListClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/SelectListClauseParser.java index a94a31cf3c90d..bd5a29bde1923 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/SelectListClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/SelectListClauseParser.java @@ -121,7 +121,7 @@ private SelectItem parseCommonOrStarSelectItem(final SelectStatement selectState } else if (lexerEngine.equalAny(Symbol.DOT)) { String tableName = SQLUtil.getExactlyValue(literals); if (shardingRule.tryFindTableRuleByLogicTable(tableName).isPresent() || shardingRule.findBindingTableRule(tableName).isPresent()) { - selectStatement.getSqlTokens().add(new TableToken(position, 0, literals)); + selectStatement.addSQLToken(new TableToken(position, 0, literals)); } result.append(lexerEngine.getCurrentToken().getLiterals()); lexerEngine.nextToken(); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/TableReferencesClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/TableReferencesClauseParser.java index 39b7bf459c415..8a1a1638ba1e0 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/TableReferencesClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/TableReferencesClauseParser.java @@ -103,7 +103,7 @@ protected final void parseTableFactor(final SQLStatement sqlStatement, final boo } if (isSingleTableOnly || shardingRule.tryFindTableRuleByLogicTable(tableName).isPresent() || shardingRule.findBindingTableRule(tableName).isPresent() || shardingRule.getShardingDataSourceNames().getDataSourceNames().contains(shardingRule.getShardingDataSourceNames().getDefaultDataSourceName())) { - sqlStatement.getSqlTokens().add(new TableToken(beginPosition, skippedSchemaNameLength, literals)); + sqlStatement.addSQLToken(new TableToken(beginPosition, skippedSchemaNameLength, literals)); sqlStatement.getTables().add(new Table(tableName, aliasExpressionParser.parseTableAlias(sqlStatement, true, tableName))); } else { aliasExpressionParser.parseTableAlias(); @@ -125,7 +125,7 @@ private void parseForceIndex(final String tableName, final SQLStatement sqlState Preconditions.checkState(!Symbol.RIGHT_PAREN.getLiterals().equals(literals), "There is an error in the vicinity of the force index syntax."); if (shardingRule.isLogicIndex(literals, tableName)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - literals.length(); - sqlStatement.getSqlTokens().add(new IndexToken(beginPosition, literals, tableName)); + sqlStatement.addSQLToken(new IndexToken(beginPosition, literals, tableName)); } lexerEngine.nextToken(); } while (lexerEngine.skipIfEqual(Symbol.COMMA)); @@ -192,7 +192,7 @@ public final void parseSingleTableWithoutAlias(final SQLStatement sqlStatement) literals = lexerEngine.getCurrentToken().getLiterals(); lexerEngine.nextToken(); } - sqlStatement.getSqlTokens().add(new TableToken(beginPosition, skippedSchemaNameLength, literals)); + sqlStatement.addSQLToken(new TableToken(beginPosition, skippedSchemaNameLength, literals)); sqlStatement.getTables().add(new Table(SQLUtil.getExactlyValue(literals), Optional.absent())); } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/UpdateSetItemsClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/UpdateSetItemsClauseParser.java index b8bc1b419896f..f68172c241b25 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/UpdateSetItemsClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/UpdateSetItemsClauseParser.java @@ -71,7 +71,7 @@ private void parseSetColumn(final DMLStatement updateStatement) { lexerEngine.nextToken(); if (lexerEngine.skipIfEqual(Symbol.DOT)) { if (updateStatement.getTables().getSingleTableName().equalsIgnoreCase(SQLUtil.getExactlyValue(literals))) { - updateStatement.getSqlTokens().add(new TableToken(beginPosition - literals.length(), 0, literals)); + updateStatement.addSQLToken(new TableToken(beginPosition - literals.length(), 0, literals)); } lexerEngine.nextToken(); } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/WhereClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/WhereClauseParser.java index f45cbd7f8a1f0..d38398136de57 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/WhereClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/WhereClauseParser.java @@ -294,7 +294,7 @@ private void parseRowCountCondition(final SelectStatement selectStatement, final if (sqlExpression instanceof SQLNumberExpression) { int rowCount = ((SQLNumberExpression) sqlExpression).getNumber().intValue(); selectStatement.getLimit().setRowCount(new LimitValue(rowCount, -1, includeRowCount)); - selectStatement.getSqlTokens().add(new RowCountToken(endPosition - String.valueOf(rowCount).length(), rowCount)); + selectStatement.addSQLToken(new RowCountToken(endPosition - String.valueOf(rowCount).length(), rowCount)); } else if (sqlExpression instanceof SQLPlaceholderExpression) { selectStatement.getLimit().setRowCount(new LimitValue(-1, ((SQLPlaceholderExpression) sqlExpression).getIndex(), includeRowCount)); } @@ -308,7 +308,7 @@ private void parseOffsetCondition(final SelectStatement selectStatement, final b if (sqlExpression instanceof SQLNumberExpression) { int offset = ((SQLNumberExpression) sqlExpression).getNumber().intValue(); selectStatement.getLimit().setOffset(new LimitValue(offset, -1, includeOffset)); - selectStatement.getSqlTokens().add(new OffsetToken( + selectStatement.addSQLToken(new OffsetToken( lexerEngine.getCurrentToken().getEndPosition() - String.valueOf(offset).length() - lexerEngine.getCurrentToken().getLiterals().length(), offset)); } else if (sqlExpression instanceof SQLPlaceholderExpression) { selectStatement.getLimit().setOffset(new LimitValue(-1, ((SQLPlaceholderExpression) sqlExpression).getIndex(), includeOffset)); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/AliasExpressionParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/AliasExpressionParser.java index 3c7e0b54213c2..2503f937e5fcb 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/AliasExpressionParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/AliasExpressionParser.java @@ -66,7 +66,7 @@ private Optional parseAlias(final SQLStatement sqlStatement, final boole String literals = lexerEngine.getCurrentToken().getLiterals(); String alias = SQLUtil.getExactlyValue(literals); if (setTableToken && alias.equals(tableName)) { - sqlStatement.getSqlTokens().add(new TableToken(beginPosition, 0, literals)); + sqlStatement.addSQLToken(new TableToken(beginPosition, 0, literals)); } lexerEngine.nextToken(); return Optional.of(SQLUtil.getExactlyValue(literals)); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/BasicExpressionParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/BasicExpressionParser.java index eb6a52a86b211..1ab4917cbcb17 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/BasicExpressionParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/BasicExpressionParser.java @@ -131,7 +131,7 @@ private void skipRestCompositeExpression(final SQLStatement sqlStatement) { private void setTableToken(final SQLStatement sqlStatement, final int beginPosition, final SQLPropertyExpression propertyExpr) { String owner = propertyExpr.getOwner().getName(); if (sqlStatement.getTables().getTableNames().contains(SQLUtil.getExactlyValue(propertyExpr.getOwner().getName()))) { - sqlStatement.getSqlTokens().add(new TableToken(beginPosition - owner.length(), 0, owner)); + sqlStatement.addSQLToken(new TableToken(beginPosition - owner.length(), 0, owner)); } } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/clause/MySQLLimitClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/clause/MySQLLimitClauseParser.java index 89bacb7d8c51b..ef702435aedb0 100755 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/clause/MySQLLimitClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/clause/MySQLLimitClauseParser.java @@ -77,7 +77,7 @@ public void parse(final SelectStatement selectStatement) { if (isParameterForValue) { selectStatement.increaseParametersIndex(); } else { - selectStatement.getSqlTokens().add(new RowCountToken(valueBeginPosition, value)); + selectStatement.addSQLToken(new RowCountToken(valueBeginPosition, value)); } Limit limit = new Limit(DatabaseType.MySQL); limit.setRowCount(new LimitValue(value, valueIndex, false)); @@ -104,12 +104,12 @@ private Limit getLimitWithComma(final int index, final int valueBeginPosition, f if (isParameterForValue) { selectStatement.increaseParametersIndex(); } else { - selectStatement.getSqlTokens().add(new OffsetToken(valueBeginPosition, value)); + selectStatement.addSQLToken(new OffsetToken(valueBeginPosition, value)); } if (isParameterForRowCount) { selectStatement.increaseParametersIndex(); } else { - selectStatement.getSqlTokens().add(new RowCountToken(rowCountBeginPosition, rowCountValue)); + selectStatement.addSQLToken(new RowCountToken(rowCountBeginPosition, rowCountValue)); } Limit result = new Limit(DatabaseType.MySQL); result.setRowCount(new LimitValue(rowCountValue, rowCountIndex, false)); @@ -136,12 +136,12 @@ private Limit getLimitWithOffset(final int index, final int valueBeginPosition, if (isParameterForOffset) { selectStatement.increaseParametersIndex(); } else { - selectStatement.getSqlTokens().add(new OffsetToken(offsetBeginPosition, offsetValue)); + selectStatement.addSQLToken(new OffsetToken(offsetBeginPosition, offsetValue)); } if (isParameterForValue) { selectStatement.increaseParametersIndex(); } else { - selectStatement.getSqlTokens().add(new RowCountToken(valueBeginPosition, value)); + selectStatement.addSQLToken(new RowCountToken(valueBeginPosition, value)); } Limit result = new Limit(DatabaseType.MySQL); result.setRowCount(new LimitValue(value, index, false)); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java index cc39eedae633b..21fecd75e3840 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java @@ -91,13 +91,13 @@ private DALStatement parseShowTableStatus() { if (lexerEngine.equalAny(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); lexerEngine.nextToken(); - result.getSqlTokens().add(new RemoveToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition())); + result.addSQLToken(new RemoveToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition())); } lexerEngine.nextToken(); if (lexerEngine.skipIfEqual(DefaultKeyword.LIKE)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length() - 1; String literals = lexerEngine.getCurrentToken().getLiterals(); - result.getSqlTokens().add(new TableToken(beginPosition, 0, literals)); + result.addSQLToken(new TableToken(beginPosition, 0, literals)); result.getTables().add(new Table(SQLUtil.getExactlyValue(literals), Optional.absent())); } return result; @@ -108,7 +108,7 @@ private DALStatement parseShowTables() { if (lexerEngine.equalAny(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); lexerEngine.nextToken(); - result.getSqlTokens().add(new RemoveToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition())); + result.addSQLToken(new RemoveToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition())); } return result; } @@ -119,7 +119,7 @@ private DALStatement parseShowColumnsFields() { tableReferencesClauseParser.parseSingleTableWithoutAlias(result); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.getSqlTokens().add(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), result.getTables().getSingleTableName())); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), result.getTables().getSingleTableName())); } return result; } @@ -136,7 +136,7 @@ private DALStatement parseShowIndex() { tableReferencesClauseParser.parseSingleTableWithoutAlias(result); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.getSqlTokens().add(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), result.getTables().getSingleTableName())); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getLiterals(), result.getTables().getSingleTableName())); } return result; } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/postgresql/clause/PostgreSQLLimitClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/postgresql/clause/PostgreSQLLimitClauseParser.java index 68ce57620ae87..51a957a98dc7b 100755 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/postgresql/clause/PostgreSQLLimitClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/postgresql/clause/PostgreSQLLimitClauseParser.java @@ -77,7 +77,7 @@ private Optional buildRowCount(final SelectStatement selectStatement if (lexerEngine.equalAny(Literals.INT, Literals.FLOAT)) { rowCountValue = NumberUtil.roundHalfUp(lexerEngine.getCurrentToken().getLiterals()); valueBeginPosition = valueBeginPosition - (rowCountValue + "").length(); - selectStatement.getSqlTokens().add(new RowCountToken(valueBeginPosition, rowCountValue)); + selectStatement.addSQLToken(new RowCountToken(valueBeginPosition, rowCountValue)); } else if (lexerEngine.equalAny(Symbol.QUESTION)) { rowCountIndex = parameterIndex++; selectStatement.setParametersIndex(parameterIndex); @@ -98,7 +98,7 @@ private Optional buildOffset(final SelectStatement selectStatement) if (lexerEngine.equalAny(Literals.INT, Literals.FLOAT)) { offsetValue = NumberUtil.roundHalfUp(lexerEngine.getCurrentToken().getLiterals()); offsetBeginPosition = offsetBeginPosition - (offsetValue + "").length(); - selectStatement.getSqlTokens().add(new OffsetToken(offsetBeginPosition, offsetValue)); + selectStatement.addSQLToken(new OffsetToken(offsetBeginPosition, offsetValue)); } else if (lexerEngine.equalAny(Symbol.QUESTION)) { offsetIndex = parameterIndex++; selectStatement.setParametersIndex(parameterIndex); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/sqlserver/clause/SQLServerTopClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/sqlserver/clause/SQLServerTopClauseParser.java index 67c458ddc5901..234393361e37c 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/sqlserver/clause/SQLServerTopClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/sqlserver/clause/SQLServerTopClauseParser.java @@ -69,7 +69,7 @@ public void parse(final SelectStatement selectStatement) { if (sqlExpression instanceof SQLNumberExpression) { int rowCount = ((SQLNumberExpression) sqlExpression).getNumber().intValue(); rowCountValue = new LimitValue(rowCount, -1, false); - selectStatement.getSqlTokens().add(new RowCountToken(beginPosition, rowCount)); + selectStatement.addSQLToken(new RowCountToken(beginPosition, rowCount)); } else if (sqlExpression instanceof SQLPlaceholderExpression) { rowCountValue = new LimitValue(-1, ((SQLPlaceholderExpression) sqlExpression).getIndex(), false); } else { diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/AbstractSQLStatement.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/AbstractSQLStatement.java index 551a50b632be9..0867db540a026 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/AbstractSQLStatement.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/AbstractSQLStatement.java @@ -21,11 +21,13 @@ import io.shardingsphere.core.parsing.parser.context.condition.Conditions; import io.shardingsphere.core.parsing.parser.context.table.Tables; import io.shardingsphere.core.parsing.parser.token.SQLToken; +import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; +import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -46,13 +48,20 @@ public abstract class AbstractSQLStatement implements SQLStatement { private final Conditions conditions = new Conditions(); + @Getter(AccessLevel.NONE) private final List sqlTokens = new LinkedList<>(); private int parametersIndex; @Override - public final SQLType getType() { - return type; + public final void addSQLToken(final SQLToken sqlToken) { + sqlTokens.add(sqlToken); + } + + @Override + public final List getSQLTokens() { + Collections.sort(sqlTokens); + return sqlTokens; } @Override diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/SQLStatement.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/SQLStatement.java index 5bf1d5ea7fba7..76f44c965c8be 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/SQLStatement.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/SQLStatement.java @@ -53,11 +53,18 @@ public interface SQLStatement { Conditions getConditions(); /** - * Get SQL Tokens. + * Add SQL token. + * + * @param sqlToken SQL token + */ + void addSQLToken(SQLToken sqlToken); + + /** + * Get SQL tokens. * - * @return SQL Tokens + * @return SQL tokens */ - List getSqlTokens(); + List getSQLTokens(); /** * Get index of parameters. diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/create/index/AbstractCreateIndexParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/create/index/AbstractCreateIndexParser.java index 8282df1aa7e93..0b2cf455248d0 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/create/index/AbstractCreateIndexParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/create/index/AbstractCreateIndexParser.java @@ -79,6 +79,6 @@ private void parseIndex(final DDLStatement ddlStatement) { lexerEngine.skipUntil(DefaultKeyword.ON); lexerEngine.nextToken(); String tableName = lexerEngine.getCurrentToken().getLiterals(); - ddlStatement.getSqlTokens().add(new IndexToken(beginPosition, literals, tableName)); + ddlStatement.addSQLToken(new IndexToken(beginPosition, literals, tableName)); } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/drop/index/AbstractDropIndexParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/drop/index/AbstractDropIndexParser.java index cad59726011e8..be6c0efe6d610 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/drop/index/AbstractDropIndexParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/ddl/drop/index/AbstractDropIndexParser.java @@ -75,9 +75,9 @@ private void parseIndex(final DDLStatement ddlStatement) { lexerEngine.skipUntil(DefaultKeyword.ON); if (lexerEngine.skipIfEqual(DefaultKeyword.ON)) { tableReferencesClauseParser.parseSingleTableWithoutAlias(ddlStatement); - ddlStatement.getSqlTokens().add(new IndexToken(beginPosition, literals, ddlStatement.getTables().getSingleTableName())); + ddlStatement.addSQLToken(new IndexToken(beginPosition, literals, ddlStatement.getTables().getSingleTableName())); } else { - ddlStatement.getSqlTokens().add(new IndexToken(beginPosition, literals, "")); + ddlStatement.addSQLToken(new IndexToken(beginPosition, literals, "")); } } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dml/insert/AbstractInsertParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dml/insert/AbstractInsertParser.java index 5acf4c12f8a59..f1f18452d1b42 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dml/insert/AbstractInsertParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dml/insert/AbstractInsertParser.java @@ -87,7 +87,7 @@ private void processGeneratedKey(final InsertStatement insertStatement) { } else { ItemsToken columnsToken = new ItemsToken(insertStatement.getColumnsListLastPosition()); columnsToken.getItems().add(generateKeyColumn.get().getName()); - insertStatement.getSqlTokens().add(columnsToken); + insertStatement.addSQLToken(columnsToken); } } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dml/insert/InsertStatement.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dml/insert/InsertStatement.java index ba14455c74863..e46cdea232e0b 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dml/insert/InsertStatement.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dml/insert/InsertStatement.java @@ -61,12 +61,12 @@ public final class InsertStatement extends DMLStatement { * @return items token list. */ public List getItemsTokens() { - List itemsTokens = new ArrayList<>(); - for (SQLToken each : getSqlTokens()) { + List result = new ArrayList<>(); + for (SQLToken each : getSQLTokens()) { if (each instanceof ItemsToken) { - itemsTokens.add((ItemsToken) each); + result.add((ItemsToken) each); } } - return itemsTokens; + return result; } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dql/select/AbstractSelectParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dql/select/AbstractSelectParser.java index 4ae74504dd468..3d554c695a156 100755 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dql/select/AbstractSelectParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dql/select/AbstractSelectParser.java @@ -134,7 +134,7 @@ private void appendDerivedColumns(final SelectStatement selectStatement) { appendDerivedOrderColumns(itemsToken, selectStatement.getOrderByItems(), selectStatement); appendDerivedGroupColumns(itemsToken, selectStatement.getGroupByItems(), selectStatement); if (!itemsToken.getItems().isEmpty()) { - selectStatement.getSqlTokens().add(itemsToken); + selectStatement.addSQLToken(itemsToken); } } @@ -231,7 +231,7 @@ private boolean isSameQualifiedName(final SelectItem selectItem, final OrderItem private void appendDerivedOrderBy(final SelectStatement selectStatement) { if (!selectStatement.getGroupByItems().isEmpty() && selectStatement.getOrderByItems().isEmpty()) { selectStatement.getOrderByItems().addAll(selectStatement.getGroupByItems()); - selectStatement.getSqlTokens().add(new OrderByToken(selectStatement.getGroupByLastPosition())); + selectStatement.addSQLToken(new OrderByToken(selectStatement.getGroupByLastPosition())); } } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dql/select/SelectStatement.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dql/select/SelectStatement.java index 60996d301a269..eec53999250d1 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dql/select/SelectStatement.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/sql/dql/select/SelectStatement.java @@ -263,7 +263,7 @@ private SelectStatement processLimitForSubQuery() { private List getLimitTokens(final SelectStatement selectStatement) { List result = new LinkedList<>(); - for (SQLToken each : selectStatement.getSqlTokens()) { + for (SQLToken each : selectStatement.getSQLTokens()) { if (each instanceof RowCountToken || each instanceof OffsetToken) { result.add(each); } @@ -274,16 +274,17 @@ private List getLimitTokens(final SelectStatement selectStatement) { private void resetLimitTokens(final SelectStatement selectStatement, final List limitSQLTokens) { int count = 0; List toBeRemovedIndexes = new LinkedList<>(); - for (SQLToken each : selectStatement.getSqlTokens()) { + List sqlTokens = selectStatement.getSQLTokens(); + for (SQLToken each : sqlTokens) { if (each instanceof RowCountToken || each instanceof OffsetToken) { toBeRemovedIndexes.add(count); } count++; } for (int each : toBeRemovedIndexes) { - selectStatement.getSqlTokens().remove(each); + sqlTokens.remove(each); } - selectStatement.getSqlTokens().addAll(limitSQLTokens); + sqlTokens.addAll(limitSQLTokens); } private void processItems(final SelectStatement subQueryStatement) { diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/GeneratedKeyToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/GeneratedKeyToken.java index f3259d88595b6..6fdcde21b9657 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/GeneratedKeyToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/GeneratedKeyToken.java @@ -17,17 +17,14 @@ package io.shardingsphere.core.parsing.parser.token; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Generated key token. * * @author zhangliang */ -@RequiredArgsConstructor -@Getter -public final class GeneratedKeyToken implements SQLToken { +public final class GeneratedKeyToken extends SQLToken { - private final int beginPosition; + public GeneratedKeyToken(final int beginPosition) { + super(beginPosition); + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/IndexToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/IndexToken.java index e6d74d83eac4b..ad4fb2bb6cb3d 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/IndexToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/IndexToken.java @@ -19,7 +19,6 @@ import io.shardingsphere.core.util.SQLUtil; import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.ToString; /** @@ -27,18 +26,20 @@ * * @author caohao */ -@RequiredArgsConstructor @ToString -public final class IndexToken implements SQLToken { - - @Getter - private final int beginPosition; +public final class IndexToken extends SQLToken { @Getter private final String originalLiterals; private final String tableName; + public IndexToken(final int beginPosition, final String originalLiterals, final String tableName) { + super(beginPosition); + this.originalLiterals = originalLiterals; + this.tableName = tableName; + } + /** * Get index name. * diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/InsertColumnToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/InsertColumnToken.java index a17b1471e06b1..091236c05f9ff 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/InsertColumnToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/InsertColumnToken.java @@ -18,7 +18,6 @@ package io.shardingsphere.core.parsing.parser.token; import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.ToString; /** @@ -26,12 +25,14 @@ * * @author panjuan */ -@RequiredArgsConstructor @Getter @ToString -public final class InsertColumnToken implements SQLToken { - - private final int beginPosition; +public final class InsertColumnToken extends SQLToken { private final String columnName; + + public InsertColumnToken(final int beginPosition, final String columnName) { + super(beginPosition); + this.columnName = columnName; + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/InsertValuesToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/InsertValuesToken.java index cdbb1e6aa96c6..0a710f0f84b91 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/InsertValuesToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/InsertValuesToken.java @@ -18,18 +18,19 @@ package io.shardingsphere.core.parsing.parser.token; import lombok.Getter; -import lombok.RequiredArgsConstructor; /** * Insert values token. * * @author maxiaoguang */ -@RequiredArgsConstructor @Getter -public final class InsertValuesToken implements SQLToken { - - private final int beginPosition; +public final class InsertValuesToken extends SQLToken { private final String tableName; + + public InsertValuesToken(final int beginPosition, final String tableName) { + super(beginPosition); + this.tableName = tableName; + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/ItemsToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/ItemsToken.java index 23bd70a2a217b..6c7bd363606ed 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/ItemsToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/ItemsToken.java @@ -18,7 +18,6 @@ package io.shardingsphere.core.parsing.parser.token; import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; @@ -31,15 +30,16 @@ * @author zhangliang * @author panjuan */ -@RequiredArgsConstructor @Getter @ToString -public final class ItemsToken implements SQLToken { - - private final int beginPosition; +public final class ItemsToken extends SQLToken { @Setter private boolean isFirstOfItemsSpecial; private final List items = new LinkedList<>(); + + public ItemsToken(final int beginPosition) { + super(beginPosition); + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/OffsetToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/OffsetToken.java index 163393c367d0e..79e505a0ef7ef 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/OffsetToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/OffsetToken.java @@ -18,18 +18,19 @@ package io.shardingsphere.core.parsing.parser.token; import lombok.Getter; -import lombok.RequiredArgsConstructor; /** * Offset token for limit. * * @author zhangliang */ -@RequiredArgsConstructor @Getter -public final class OffsetToken implements SQLToken { - - private final int beginPosition; +public final class OffsetToken extends SQLToken { private final int offset; + + public OffsetToken(final int beginPosition, final int offset) { + super(beginPosition); + this.offset = offset; + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/OrderByToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/OrderByToken.java index c430323e61a6e..ad424bdcf58fa 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/OrderByToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/OrderByToken.java @@ -17,17 +17,14 @@ package io.shardingsphere.core.parsing.parser.token; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Order by token. * * @author zhangliang */ -@RequiredArgsConstructor -@Getter -public final class OrderByToken implements SQLToken { +public final class OrderByToken extends SQLToken { - private final int beginPosition; + public OrderByToken(final int beginPosition) { + super(beginPosition); + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/RemoveToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/RemoveToken.java index fbe368f99e3da..cb8eaf38d4e8d 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/RemoveToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/RemoveToken.java @@ -18,7 +18,6 @@ package io.shardingsphere.core.parsing.parser.token; import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.ToString; /** @@ -26,12 +25,14 @@ * * @author zhangliang */ -@RequiredArgsConstructor @Getter @ToString -public final class RemoveToken implements SQLToken { - - private final int beginPosition; +public final class RemoveToken extends SQLToken { private final int endPosition; + + public RemoveToken(final int beginPosition, final int endPosition) { + super(beginPosition); + this.endPosition = endPosition; + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/RowCountToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/RowCountToken.java index 286d54e21886c..272b3bcdb0013 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/RowCountToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/RowCountToken.java @@ -18,18 +18,19 @@ package io.shardingsphere.core.parsing.parser.token; import lombok.Getter; -import lombok.RequiredArgsConstructor; /** * Row count token for limit. * * @author zhangliang */ -@RequiredArgsConstructor @Getter -public final class RowCountToken implements SQLToken { - - private final int beginPosition; +public final class RowCountToken extends SQLToken { private final int rowCount; + + public RowCountToken(final int beginPosition, final int rowCount) { + super(beginPosition); + this.rowCount = rowCount; + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/SQLToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/SQLToken.java index b0af6c88d0275..2ed268a33f2ea 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/SQLToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/SQLToken.java @@ -17,17 +17,22 @@ package io.shardingsphere.core.parsing.parser.token; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + /** * SQL Token. * * @author zhangliang */ -public interface SQLToken { +@RequiredArgsConstructor +@Getter +public abstract class SQLToken implements Comparable { + + private final int beginPosition; - /** - * Get begin position. - * - * @return begin position - */ - int getBeginPosition(); + @Override + public final int compareTo(final SQLToken sqlToken) { + return beginPosition - sqlToken.getBeginPosition(); + } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/SchemaToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/SchemaToken.java index 6da840ec90db1..4dae2a6584e49 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/SchemaToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/SchemaToken.java @@ -19,7 +19,6 @@ import io.shardingsphere.core.util.SQLUtil; import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.ToString; /** @@ -27,18 +26,20 @@ * * @author zhangliang */ -@RequiredArgsConstructor @ToString -public final class SchemaToken implements SQLToken { - - @Getter - private final int beginPosition; +public final class SchemaToken extends SQLToken { @Getter private final String originalLiterals; private final String tableName; + public SchemaToken(final int beginPosition, final String originalLiterals, final String tableName) { + super(beginPosition); + this.originalLiterals = originalLiterals; + this.tableName = tableName; + } + /** * Get schema name. * diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/TableToken.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/TableToken.java index b3110c6adf770..7cda74e059c67 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/TableToken.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/token/TableToken.java @@ -19,7 +19,6 @@ import io.shardingsphere.core.util.SQLUtil; import lombok.Getter; -import lombok.RequiredArgsConstructor; import lombok.ToString; /** @@ -27,17 +26,20 @@ * * @author zhangliang */ -@RequiredArgsConstructor @Getter @ToString -public final class TableToken implements SQLToken { - - private final int beginPosition; +public final class TableToken extends SQLToken { private final int skippedSchemaNameLength; private final String originalLiterals; + public TableToken(final int beginPosition, final int skippedSchemaNameLength, final String originalLiterals) { + super(beginPosition); + this.skippedSchemaNameLength = skippedSchemaNameLength; + this.originalLiterals = originalLiterals; + } + /** * Get table name. * diff --git a/sharding-core/src/main/java/io/shardingsphere/core/rewrite/SQLRewriteEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/rewrite/SQLRewriteEngine.java index 79900f957a629..c0aefa989f752 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/rewrite/SQLRewriteEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/rewrite/SQLRewriteEngine.java @@ -20,6 +20,7 @@ import com.google.common.base.Optional; import com.google.common.base.Strings; import io.shardingsphere.core.constant.DatabaseType; +import io.shardingsphere.core.metadata.datasource.ShardingDataSourceMetaData; import io.shardingsphere.core.optimizer.condition.ShardingConditions; import io.shardingsphere.core.parsing.lexer.token.DefaultKeyword; import io.shardingsphere.core.parsing.parser.context.OrderItem; @@ -38,7 +39,6 @@ import io.shardingsphere.core.parsing.parser.token.SQLToken; import io.shardingsphere.core.parsing.parser.token.SchemaToken; import io.shardingsphere.core.parsing.parser.token.TableToken; -import io.shardingsphere.core.metadata.datasource.ShardingDataSourceMetaData; import io.shardingsphere.core.rewrite.placeholder.IndexPlaceholder; import io.shardingsphere.core.rewrite.placeholder.InsertValuesPlaceholder; import io.shardingsphere.core.rewrite.placeholder.SchemaPlaceholder; @@ -50,10 +50,7 @@ import io.shardingsphere.core.rule.ShardingRule; import io.shardingsphere.core.util.SQLUtil; -import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; -import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -74,10 +71,10 @@ public final class SQLRewriteEngine { private final DatabaseType databaseType; - private final List sqlTokens = new LinkedList<>(); - private final SQLStatement sqlStatement; + private final List sqlTokens; + private final ShardingConditions shardingConditions; private final List parameters; @@ -98,9 +95,9 @@ public SQLRewriteEngine(final ShardingRule shardingRule, final String originalSQ this.originalSQL = originalSQL; this.databaseType = databaseType; this.sqlStatement = sqlStatement; + sqlTokens = sqlStatement.getSQLTokens(); this.shardingConditions = shardingConditions; this.parameters = parameters; - sqlTokens.addAll(sqlStatement.getSqlTokens()); } /** @@ -116,7 +113,6 @@ public SQLBuilder rewrite(final boolean isRewriteLimit) { return result; } int count = 0; - sortByBeginPosition(); for (SQLToken each : sqlTokens) { if (0 == count) { result.appendLiterals(originalSQL.substring(0, each.getBeginPosition())); @@ -147,16 +143,6 @@ public SQLBuilder rewrite(final boolean isRewriteLimit) { return result; } - private void sortByBeginPosition() { - Collections.sort(sqlTokens, new Comparator() { - - @Override - public int compare(final SQLToken o1, final SQLToken o2) { - return o1.getBeginPosition() - o2.getBeginPosition(); - } - }); - } - private void appendTablePlaceholder(final SQLBuilder sqlBuilder, final TableToken tableToken, final int count, final List sqlTokens) { sqlBuilder.appendPlaceholder(new TablePlaceholder(tableToken.getTableName().toLowerCase(), tableToken.getOriginalLiterals())); int beginPosition = tableToken.getBeginPosition() + tableToken.getSkippedSchemaNameLength() + tableToken.getOriginalLiterals().length(); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/routing/type/broadcast/TableBroadcastRoutingEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/routing/type/broadcast/TableBroadcastRoutingEngine.java index 7bb878582aba6..2f87400e456e2 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/routing/type/broadcast/TableBroadcastRoutingEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/routing/type/broadcast/TableBroadcastRoutingEngine.java @@ -21,6 +21,7 @@ import io.shardingsphere.core.parsing.parser.sql.SQLStatement; import io.shardingsphere.core.parsing.parser.sql.ddl.DDLStatement; import io.shardingsphere.core.parsing.parser.token.IndexToken; +import io.shardingsphere.core.parsing.parser.token.SQLToken; import io.shardingsphere.core.routing.type.RoutingEngine; import io.shardingsphere.core.routing.type.RoutingResult; import io.shardingsphere.core.routing.type.RoutingTable; @@ -33,6 +34,7 @@ import java.util.Collection; import java.util.Collections; import java.util.LinkedList; +import java.util.List; /** * Broadcast routing engine for tables. @@ -68,8 +70,9 @@ private boolean isOperateIndexWithoutTable() { } private IndexToken getIndexToken() { - Preconditions.checkState(1 == sqlStatement.getSqlTokens().size()); - return (IndexToken) sqlStatement.getSqlTokens().get(0); + List sqlTokens = sqlStatement.getSQLTokens(); + Preconditions.checkState(1 == sqlTokens.size()); + return (IndexToken) sqlTokens.get(0); } private Collection getAllTableUnits(final String logicTableName) { diff --git a/sharding-core/src/test/java/io/shardingsphere/core/optimizer/InsertOptimizeEngineTest.java b/sharding-core/src/test/java/io/shardingsphere/core/optimizer/InsertOptimizeEngineTest.java index 46d5dcaf123e8..f5f91caf9bba9 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/optimizer/InsertOptimizeEngineTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/optimizer/InsertOptimizeEngineTest.java @@ -68,8 +68,8 @@ public void setUp() throws IOException { insertStatement.getTables().add(new Table("t_order", Optional.absent())); insertStatement.setParametersIndex(4); insertStatement.setInsertValuesListLastPosition(45); - insertStatement.getSqlTokens().add(new TableToken(12, 0, "t_order")); - insertStatement.getSqlTokens().add(new InsertValuesToken(39, "t_order")); + insertStatement.addSQLToken(new TableToken(12, 0, "t_order")); + insertStatement.addSQLToken(new InsertValuesToken(39, "t_order")); AndCondition andCondition1 = new AndCondition(); andCondition1.getConditions().add(new Condition(new Column("user_id", "t_order"), new SQLPlaceholderExpression(0))); insertStatement.getConditions().getOrCondition().getAndConditions().add(andCondition1); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/SQLStatementAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/SQLStatementAssert.java index 23d508d030d9d..ac5e9b683f914 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/SQLStatementAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/SQLStatementAssert.java @@ -83,7 +83,7 @@ public SQLStatementAssert(final SQLStatement actual, final String sqlCaseId, fin public void assertSQLStatement() { tableAssert.assertTables(actual.getTables(), expected.getTables()); conditionAssert.assertOrCondition(actual.getConditions().getOrCondition(), expected.getOrCondition()); - tokenAssert.assertTokens(actual.getSqlTokens(), expected.getTokens()); + tokenAssert.assertTokens(actual.getSQLTokens(), expected.getTokens()); indexAssert.assertParametersIndex(actual.getParametersIndex(), expected.getParameters().size()); if (actual instanceof SelectStatement) { assertSelectStatement((SelectStatement) actual); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/GeneratedKeyTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/GeneratedKeyTokenAssert.java index 7465106baa8a0..c485db59bba48 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/GeneratedKeyTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/GeneratedKeyTokenAssert.java @@ -26,7 +26,7 @@ import io.shardingsphere.test.sql.SQLCaseType; import lombok.RequiredArgsConstructor; -import java.util.List; +import java.util.Collection; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; @@ -44,7 +44,7 @@ final class GeneratedKeyTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertGeneratedKeyToken(final List actual, final ExpectedTokens expected) { + void assertGeneratedKeyToken(final Collection actual, final ExpectedTokens expected) { Optional generatedKeyToken = getGeneratedKeyToken(actual); if (generatedKeyToken.isPresent()) { assertGeneratedKeyToken(generatedKeyToken.get(), expected.getGeneratedKeyToken()); @@ -61,7 +61,7 @@ private void assertGeneratedKeyToken(final GeneratedKeyToken actual, final Expec } } - private Optional getGeneratedKeyToken(final List actual) { + private Optional getGeneratedKeyToken(final Collection actual) { for (SQLToken each : actual) { if (each instanceof GeneratedKeyToken) { return Optional.of((GeneratedKeyToken) each); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/IndexTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/IndexTokenAssert.java index 47442df914ccb..2a512d746ffdd 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/IndexTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/IndexTokenAssert.java @@ -25,7 +25,7 @@ import io.shardingsphere.core.parsing.parser.token.SQLToken; import lombok.RequiredArgsConstructor; -import java.util.List; +import java.util.Collection; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; @@ -41,7 +41,7 @@ final class IndexTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertIndexToken(final List actual, final ExpectedTokens expected) { + void assertIndexToken(final Collection actual, final ExpectedTokens expected) { Optional indexToken = getIndexToken(actual); if (indexToken.isPresent()) { assertIndexToken(indexToken.get(), expected.getIndexToken()); @@ -56,7 +56,7 @@ private void assertIndexToken(final IndexToken actual, final ExpectedIndexToken assertThat(assertMessage.getFullAssertMessage("Index token table name assertion error: "), actual.getTableName(), is(expected.getTableName())); } - private Optional getIndexToken(final List actual) { + private Optional getIndexToken(final Collection actual) { for (SQLToken each : actual) { if (each instanceof IndexToken) { return Optional.of((IndexToken) each); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/InsertValuesTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/InsertValuesTokenAssert.java index 6a5a2550c4de6..16893556dab68 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/InsertValuesTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/InsertValuesTokenAssert.java @@ -25,7 +25,7 @@ import io.shardingsphere.core.parsing.parser.token.SQLToken; import lombok.RequiredArgsConstructor; -import java.util.List; +import java.util.Collection; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; @@ -41,7 +41,7 @@ final class InsertValuesTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertInsertValuesToken(final List actual, final ExpectedTokens expected) { + void assertInsertValuesToken(final Collection actual, final ExpectedTokens expected) { Optional insertValuesToken = getInsertValuesToken(actual); if (insertValuesToken.isPresent()) { assertInsertValuesToken(insertValuesToken.get(), expected.getInsertValuesToken()); @@ -55,7 +55,7 @@ private void assertInsertValuesToken(final InsertValuesToken actual, final Expec assertThat(assertMessage.getFullAssertMessage("Insert values table name assertion error: "), actual.getTableName(), is(expected.getTableName())); } - private Optional getInsertValuesToken(final List actual) { + private Optional getInsertValuesToken(final Collection actual) { for (SQLToken each : actual) { if (each instanceof InsertValuesToken) { return Optional.of((InsertValuesToken) each); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/ItemsTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/ItemsTokenAssert.java index fe51183d95923..4b3f703b6d8e9 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/ItemsTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/ItemsTokenAssert.java @@ -25,7 +25,7 @@ import io.shardingsphere.core.parsing.parser.token.SQLToken; import lombok.RequiredArgsConstructor; -import java.util.List; +import java.util.Collection; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; @@ -41,7 +41,7 @@ final class ItemsTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertItemsToken(final List actual, final ExpectedTokens expected) { + void assertItemsToken(final Collection actual, final ExpectedTokens expected) { Optional itemsToken = getItemsToken(actual); if (itemsToken.isPresent()) { assertItemsToken(itemsToken.get(), expected.getItemsToken()); @@ -55,7 +55,7 @@ private void assertItemsToken(final ItemsToken actual, final ExpectedItemsToken assertThat(assertMessage.getFullAssertMessage("Items token items assertion error: "), actual.getItems(), is(expected.getItems())); } - private Optional getItemsToken(final List actual) { + private Optional getItemsToken(final Collection actual) { for (SQLToken each : actual) { if (each instanceof ItemsToken) { return Optional.of((ItemsToken) each); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/OffsetTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/OffsetTokenAssert.java index 30783dd1b76e4..1c24f9d49ccc5 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/OffsetTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/OffsetTokenAssert.java @@ -26,7 +26,7 @@ import io.shardingsphere.test.sql.SQLCaseType; import lombok.RequiredArgsConstructor; -import java.util.List; +import java.util.Collection; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; @@ -45,7 +45,7 @@ final class OffsetTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertOffsetToken(final List actual, final ExpectedTokens expected) { + void assertOffsetToken(final Collection actual, final ExpectedTokens expected) { Optional offsetToken = getOffsetToken(actual); if (SQLCaseType.Placeholder == sqlCaseType) { assertFalse(assertMessage.getFullAssertMessage("Offset token should not exist: "), offsetToken.isPresent()); @@ -63,7 +63,7 @@ private void assertOffsetToken(final OffsetToken actual, final ExpectedOffsetTok assertThat(assertMessage.getFullAssertMessage("Offset token offset assertion error: "), actual.getOffset(), is(expected.getOffset())); } - private Optional getOffsetToken(final List actual) { + private Optional getOffsetToken(final Collection actual) { for (SQLToken each : actual) { if (each instanceof OffsetToken) { return Optional.of((OffsetToken) each); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/OrderByTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/OrderByTokenAssert.java index f063580454986..b639904497227 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/OrderByTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/OrderByTokenAssert.java @@ -26,7 +26,7 @@ import io.shardingsphere.test.sql.SQLCaseType; import lombok.RequiredArgsConstructor; -import java.util.List; +import java.util.Collection; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; @@ -44,7 +44,7 @@ final class OrderByTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertOrderByToken(final List actual, final ExpectedTokens expected) { + void assertOrderByToken(final Collection actual, final ExpectedTokens expected) { Optional orderByToken = getOrderByToken(actual); if (orderByToken.isPresent()) { assertOrderByToken(orderByToken.get(), expected.getOrderByToken()); @@ -61,7 +61,7 @@ private void assertOrderByToken(final OrderByToken actual, final ExpectedOrderBy } } - private Optional getOrderByToken(final List actual) { + private Optional getOrderByToken(final Collection actual) { for (SQLToken each : actual) { if (each instanceof OrderByToken) { return Optional.of((OrderByToken) each); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/RowCountTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/RowCountTokenAssert.java index 2c64c94660ddc..0030da30ba4af 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/RowCountTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/RowCountTokenAssert.java @@ -26,7 +26,7 @@ import io.shardingsphere.test.sql.SQLCaseType; import lombok.RequiredArgsConstructor; -import java.util.List; +import java.util.Collection; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; @@ -45,7 +45,7 @@ final class RowCountTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertRowCountToken(final List actual, final ExpectedTokens expected) { + void assertRowCountToken(final Collection actual, final ExpectedTokens expected) { Optional rowCountToken = getRowCountToken(actual); if (SQLCaseType.Placeholder == sqlCaseType) { assertFalse(assertMessage.getFullAssertMessage("Row count token should not exist: "), rowCountToken.isPresent()); @@ -63,7 +63,7 @@ private void assertRowCountToken(final RowCountToken actual, final ExpectedRowCo assertThat(assertMessage.getFullAssertMessage("Row count token row count assertion error: "), actual.getRowCount(), is(expected.getRowCount())); } - private Optional getRowCountToken(final List actual) { + private Optional getRowCountToken(final Collection actual) { for (SQLToken each : actual) { if (each instanceof RowCountToken) { return Optional.of((RowCountToken) each); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/SchemaTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/SchemaTokenAssert.java index e8e6f52de406f..dbf3173ea08e6 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/SchemaTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/SchemaTokenAssert.java @@ -25,6 +25,7 @@ import lombok.RequiredArgsConstructor; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import static org.hamcrest.CoreMatchers.is; @@ -40,7 +41,7 @@ final class SchemaTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertSchemaTokens(final List actual, final ExpectedTokens expected) { + void assertSchemaTokens(final Collection actual, final ExpectedTokens expected) { List schemaTokens = getSchemaTokens(actual); assertThat(assertMessage.getFullAssertMessage("Schema tokens size error: "), schemaTokens.size(), is(expected.getSchemaTokens().size())); int count = 0; @@ -56,7 +57,7 @@ private void assertSchemaToken(final SchemaToken actual, final ExpectedSchemaTok assertThat(assertMessage.getFullAssertMessage("Schema tokens table name assertion error: "), actual.getTableName(), is(expected.getTableName())); } - private List getSchemaTokens(final List actual) { + private List getSchemaTokens(final Collection actual) { List result = new ArrayList<>(actual.size()); for (SQLToken each : actual) { if (each instanceof SchemaToken) { diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/TableTokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/TableTokenAssert.java index c90635f6dc0cf..7e4162ee9598b 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/TableTokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/TableTokenAssert.java @@ -25,6 +25,7 @@ import lombok.RequiredArgsConstructor; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import static org.hamcrest.CoreMatchers.is; @@ -40,7 +41,7 @@ final class TableTokenAssert { private final SQLStatementAssertMessage assertMessage; - void assertTableTokens(final List actual, final ExpectedTokens expected) { + void assertTableTokens(final Collection actual, final ExpectedTokens expected) { List tableTokens = getTableTokens(actual); assertThat(assertMessage.getFullAssertMessage("Table tokens size error: "), tableTokens.size(), is(expected.getTableTokens().size())); int count = 0; @@ -55,7 +56,7 @@ private void assertTableToken(final TableToken actual, final ExpectedTableToken assertThat(assertMessage.getFullAssertMessage("Table tokens original literals assertion error: "), actual.getOriginalLiterals(), is(expected.getOriginalLiterals())); } - private List getTableTokens(final List actual) { + private List getTableTokens(final Collection actual) { List result = new ArrayList<>(actual.size()); for (SQLToken each : actual) { if (each instanceof TableToken) { diff --git a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/TokenAssert.java b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/TokenAssert.java index 5601cefc996a0..3b9a875abc1e6 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/TokenAssert.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/parsing/integrate/asserts/token/TokenAssert.java @@ -22,7 +22,7 @@ import io.shardingsphere.core.parsing.parser.token.SQLToken; import io.shardingsphere.test.sql.SQLCaseType; -import java.util.List; +import java.util.Collection; /** * Token assert. @@ -67,7 +67,7 @@ public TokenAssert(final SQLCaseType sqlCaseType, final SQLStatementAssertMessag * @param actual actual tokens * @param expected expected tokens */ - public void assertTokens(final List actual, final ExpectedTokens expected) { + public void assertTokens(final Collection actual, final ExpectedTokens expected) { tableTokenAssert.assertTableTokens(actual, expected); schemaTokenAssert.assertSchemaTokens(actual, expected); indexTokenAssert.assertIndexToken(actual, expected); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/rewrite/SQLRewriteEngineTest.java b/sharding-core/src/test/java/io/shardingsphere/core/rewrite/SQLRewriteEngineTest.java index 85a6d7f98d558..d7c827016f317 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/rewrite/SQLRewriteEngineTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/rewrite/SQLRewriteEngineTest.java @@ -122,9 +122,9 @@ public void assertRewriteForTableName() { List parameters = new ArrayList<>(2); parameters.add(1); parameters.add("x"); - selectStatement.getSqlTokens().add(new TableToken(7, 0, "table_x")); - selectStatement.getSqlTokens().add(new TableToken(31, 0, "table_x")); - selectStatement.getSqlTokens().add(new TableToken(47, 0, "table_x")); + selectStatement.addSQLToken(new TableToken(7, 0, "table_x")); + selectStatement.addSQLToken(new TableToken(31, 0, "table_x")); + selectStatement.addSQLToken(new TableToken(47, 0, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT table_x.id, x.name FROM table_x x WHERE table_x.id=? AND x.name=?", DatabaseType.MySQL, selectStatement, null, parameters); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), is("SELECT table_1.id, x.name FROM table_1 x WHERE table_1.id=? AND x.name=?")); @@ -132,10 +132,10 @@ public void assertRewriteForTableName() { @Test public void assertRewriteForOrderByAndGroupByDerivedColumns() { - selectStatement.getSqlTokens().add(new TableToken(18, 0, "table_x")); + selectStatement.addSQLToken(new TableToken(18, 0, "table_x")); ItemsToken itemsToken = new ItemsToken(12); itemsToken.getItems().addAll(Arrays.asList("x.id as GROUP_BY_DERIVED_0", "x.name as ORDER_BY_DERIVED_0")); - selectStatement.getSqlTokens().add(itemsToken); + selectStatement.addSQLToken(itemsToken); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT x.age FROM table_x x GROUP BY x.id ORDER BY x.name", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), is( @@ -144,10 +144,10 @@ public void assertRewriteForOrderByAndGroupByDerivedColumns() { @Test public void assertRewriteForAggregationDerivedColumns() { - selectStatement.getSqlTokens().add(new TableToken(23, 0, "table_x")); + selectStatement.addSQLToken(new TableToken(23, 0, "table_x")); ItemsToken itemsToken = new ItemsToken(17); itemsToken.getItems().addAll(Arrays.asList("COUNT(x.age) as AVG_DERIVED_COUNT_0", "SUM(x.age) as AVG_DERIVED_SUM_0")); - selectStatement.getSqlTokens().add(itemsToken); + selectStatement.addSQLToken(itemsToken); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT AVG(x.age) FROM table_x x", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), is( "SELECT AVG(x.age), COUNT(x.age) as AVG_DERIVED_COUNT_0, SUM(x.age) as AVG_DERIVED_SUM_0 FROM table_1 x")); @@ -160,11 +160,11 @@ public void assertRewriteForAutoGeneratedKeyColumn() { parameters.add(1); insertStatement.setParametersIndex(2); insertStatement.setInsertValuesListLastPosition(45); - insertStatement.getSqlTokens().add(new TableToken(12, 0, "table_x")); + insertStatement.addSQLToken(new TableToken(12, 0, "table_x")); ItemsToken itemsToken = new ItemsToken(30); itemsToken.getItems().add("id"); - insertStatement.getSqlTokens().add(itemsToken); - insertStatement.getSqlTokens().add(new InsertValuesToken(39, "table_x")); + insertStatement.addSQLToken(itemsToken); + insertStatement.addSQLToken(new InsertValuesToken(39, "table_x")); InsertShardingCondition shardingCondition = new InsertShardingCondition("(?, ?, ?)", parameters); shardingCondition.getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); @@ -179,17 +179,17 @@ public void assertRewriteForAutoGeneratedKeyColumnWithoutColumnsWithParameter() List parameters = new ArrayList<>(); parameters.add("Bill"); insertStatement.setParametersIndex(1); - insertStatement.getSqlTokens().add(new TableToken(12, 0, "`table_x`")); + insertStatement.addSQLToken(new TableToken(12, 0, "`table_x`")); insertStatement.setGenerateKeyColumnIndex(0); insertStatement.setInsertValuesListLastPosition(32); - insertStatement.getSqlTokens().add(new InsertColumnToken(21, "(")); + insertStatement.addSQLToken(new InsertColumnToken(21, "(")); ItemsToken itemsToken = new ItemsToken(21); itemsToken.setFirstOfItemsSpecial(true); itemsToken.getItems().add("name"); itemsToken.getItems().add("id"); - insertStatement.getSqlTokens().add(itemsToken); - insertStatement.getSqlTokens().add(new InsertColumnToken(21, ")")); - insertStatement.getSqlTokens().add(new InsertValuesToken(29, "table_x")); + insertStatement.addSQLToken(itemsToken); + insertStatement.addSQLToken(new InsertColumnToken(21, ")")); + insertStatement.addSQLToken(new InsertValuesToken(29, "table_x")); InsertShardingCondition shardingCondition = new InsertShardingCondition("(?, ?)", parameters); shardingCondition.getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); @@ -201,17 +201,17 @@ public void assertRewriteForAutoGeneratedKeyColumnWithoutColumnsWithParameter() @Test public void assertRewriteForAutoGeneratedKeyColumnWithoutColumnsWithoutParameter() { - insertStatement.getSqlTokens().add(new TableToken(12, 0, "`table_x`")); + insertStatement.addSQLToken(new TableToken(12, 0, "`table_x`")); insertStatement.setGenerateKeyColumnIndex(0); insertStatement.setInsertValuesListLastPosition(33); - insertStatement.getSqlTokens().add(new InsertColumnToken(21, "(")); + insertStatement.addSQLToken(new InsertColumnToken(21, "(")); ItemsToken itemsToken = new ItemsToken(21); itemsToken.setFirstOfItemsSpecial(true); itemsToken.getItems().add("name"); itemsToken.getItems().add("id"); - insertStatement.getSqlTokens().add(itemsToken); - insertStatement.getSqlTokens().add(new InsertColumnToken(21, ")")); - insertStatement.getSqlTokens().add(new InsertValuesToken(29, "table_x")); + insertStatement.addSQLToken(itemsToken); + insertStatement.addSQLToken(new InsertColumnToken(21, ")")); + insertStatement.addSQLToken(new InsertValuesToken(29, "table_x")); InsertShardingCondition shardingCondition = new InsertShardingCondition("(10, 1)", Collections.emptyList()); shardingCondition.getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); @@ -226,17 +226,17 @@ public void assertRewriteColumnWithoutColumnsWithoutParameter() { List parameters = new ArrayList<>(2); parameters.add("x"); parameters.add(1); - insertStatement.getSqlTokens().add(new TableToken(12, 0, "`table_x`")); + insertStatement.addSQLToken(new TableToken(12, 0, "`table_x`")); insertStatement.setGenerateKeyColumnIndex(0); insertStatement.setInsertValuesListLastPosition(36); - insertStatement.getSqlTokens().add(new InsertColumnToken(21, "(")); + insertStatement.addSQLToken(new InsertColumnToken(21, "(")); ItemsToken itemsToken = new ItemsToken(21); itemsToken.setFirstOfItemsSpecial(true); itemsToken.getItems().add("name"); itemsToken.getItems().add("id"); - insertStatement.getSqlTokens().add(itemsToken); - insertStatement.getSqlTokens().add(new InsertColumnToken(21, ")")); - insertStatement.getSqlTokens().add(new InsertValuesToken(29, "table_x")); + insertStatement.addSQLToken(itemsToken); + insertStatement.addSQLToken(new InsertColumnToken(21, ")")); + insertStatement.addSQLToken(new InsertValuesToken(29, "table_x")); InsertShardingCondition shardingCondition = new InsertShardingCondition("(10, 1)", parameters); shardingCondition.getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); @@ -251,17 +251,17 @@ public void assertRewriteColumnWithoutColumnsWithParameter() { List parameters = new ArrayList<>(2); parameters.add("x"); parameters.add(1); - insertStatement.getSqlTokens().add(new TableToken(12, 0, "`table_x`")); + insertStatement.addSQLToken(new TableToken(12, 0, "`table_x`")); insertStatement.setGenerateKeyColumnIndex(0); insertStatement.setInsertValuesListLastPosition(35); - insertStatement.getSqlTokens().add(new InsertColumnToken(21, "(")); + insertStatement.addSQLToken(new InsertColumnToken(21, "(")); ItemsToken itemsToken = new ItemsToken(21); itemsToken.setFirstOfItemsSpecial(true); itemsToken.getItems().add("name"); itemsToken.getItems().add("id"); - insertStatement.getSqlTokens().add(itemsToken); - insertStatement.getSqlTokens().add(new InsertColumnToken(21, ")")); - insertStatement.getSqlTokens().add(new InsertValuesToken(29, "table_x")); + insertStatement.addSQLToken(itemsToken); + insertStatement.addSQLToken(new InsertColumnToken(21, ")")); + insertStatement.addSQLToken(new InsertValuesToken(29, "table_x")); InsertShardingCondition shardingCondition = new InsertShardingCondition("(?, ?)", parameters); shardingCondition.getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); @@ -276,9 +276,9 @@ public void assertRewriteForLimit() { selectStatement.setLimit(new Limit(DatabaseType.MySQL)); selectStatement.getLimit().setOffset(new LimitValue(2, -1, true)); selectStatement.getLimit().setRowCount(new LimitValue(2, -1, false)); - selectStatement.getSqlTokens().add(new TableToken(17, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(33, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(36, 2)); + selectStatement.addSQLToken(new TableToken(17, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(33, 2)); + selectStatement.addSQLToken(new RowCountToken(36, 2)); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT x.id FROM table_x x LIMIT 2, 2", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), is("SELECT x.id FROM table_1 x LIMIT 0, 4")); } @@ -288,9 +288,9 @@ public void assertRewriteForRowNum() { selectStatement.setLimit(new Limit(DatabaseType.Oracle)); selectStatement.getLimit().setOffset(new LimitValue(2, -1, true)); selectStatement.getLimit().setRowCount(new LimitValue(4, -1, false)); - selectStatement.getSqlTokens().add(new TableToken(68, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(119, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(98, 4)); + selectStatement.addSQLToken(new TableToken(68, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(119, 2)); + selectStatement.addSQLToken(new RowCountToken(98, 4)); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT * FROM (SELECT row_.*, rownum rownum_ FROM (SELECT x.id FROM table_x x) row_ WHERE rownum<=4) t WHERE t.rownum_>2", DatabaseType.Oracle, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), @@ -302,9 +302,9 @@ public void assertRewriteForTopAndRowNumber() { selectStatement.setLimit(new Limit(DatabaseType.SQLServer)); selectStatement.getLimit().setOffset(new LimitValue(2, -1, true)); selectStatement.getLimit().setRowCount(new LimitValue(4, -1, false)); - selectStatement.getSqlTokens().add(new TableToken(85, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(123, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(26, 4)); + selectStatement.addSQLToken(new TableToken(85, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(123, 2)); + selectStatement.addSQLToken(new RowCountToken(26, 4)); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT * FROM (SELECT TOP(4) row_number() OVER (ORDER BY x.id) AS rownum_, x.id FROM table_x x) AS row_ WHERE row_.rownum_>2", DatabaseType.SQLServer, selectStatement, null, Collections.emptyList()); @@ -319,9 +319,9 @@ public void assertRewriteForLimitForMemoryGroupBy() { selectStatement.getLimit().setRowCount(new LimitValue(2, -1, false)); selectStatement.getOrderByItems().add(new OrderItem("x", "id", OrderDirection.ASC, OrderDirection.ASC, Optional.absent())); selectStatement.getGroupByItems().add(new OrderItem("x", "id", OrderDirection.DESC, OrderDirection.ASC, Optional.absent())); - selectStatement.getSqlTokens().add(new TableToken(17, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(33, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(36, 2)); + selectStatement.addSQLToken(new TableToken(17, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(33, 2)); + selectStatement.addSQLToken(new RowCountToken(36, 2)); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT x.id FROM table_x x LIMIT 2, 2", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), is("SELECT x.id FROM table_1 x LIMIT 0, 2147483647")); } @@ -331,9 +331,9 @@ public void assertRewriteForRowNumForMemoryGroupBy() { selectStatement.setLimit(new Limit(DatabaseType.Oracle)); selectStatement.getLimit().setOffset(new LimitValue(2, -1, true)); selectStatement.getLimit().setRowCount(new LimitValue(4, -1, false)); - selectStatement.getSqlTokens().add(new TableToken(68, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(119, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(98, 4)); + selectStatement.addSQLToken(new TableToken(68, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(119, 2)); + selectStatement.addSQLToken(new RowCountToken(98, 4)); selectStatement.getOrderByItems().add(new OrderItem("x", "id", OrderDirection.ASC, OrderDirection.ASC, Optional.absent())); selectStatement.getGroupByItems().add(new OrderItem("x", "id", OrderDirection.DESC, OrderDirection.ASC, Optional.absent())); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT * FROM (SELECT row_.*, rownum rownum_ FROM (SELECT x.id FROM table_x x) row_ WHERE rownum<=4) t WHERE t.rownum_>2", @@ -347,9 +347,9 @@ public void assertRewriteForTopAndRowNumberForMemoryGroupBy() { selectStatement.setLimit(new Limit(DatabaseType.SQLServer)); selectStatement.getLimit().setOffset(new LimitValue(2, -1, true)); selectStatement.getLimit().setRowCount(new LimitValue(4, -1, false)); - selectStatement.getSqlTokens().add(new TableToken(85, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(123, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(26, 4)); + selectStatement.addSQLToken(new TableToken(85, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(123, 2)); + selectStatement.addSQLToken(new RowCountToken(26, 4)); selectStatement.getOrderByItems().add(new OrderItem("x", "id", OrderDirection.ASC, OrderDirection.ASC, Optional.absent())); selectStatement.getGroupByItems().add(new OrderItem("x", "id", OrderDirection.DESC, OrderDirection.ASC, Optional.absent())); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, @@ -364,9 +364,9 @@ public void assertRewriteForLimitForNotRewriteLimit() { selectStatement.setLimit(new Limit(DatabaseType.MySQL)); selectStatement.getLimit().setOffset(new LimitValue(2, -1, true)); selectStatement.getLimit().setRowCount(new LimitValue(2, -1, false)); - selectStatement.getSqlTokens().add(new TableToken(17, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(33, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(36, 2)); + selectStatement.addSQLToken(new TableToken(17, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(33, 2)); + selectStatement.addSQLToken(new RowCountToken(36, 2)); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT x.id FROM table_x x LIMIT 2, 2", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), is("SELECT x.id FROM table_1 x LIMIT 2, 2")); } @@ -376,9 +376,9 @@ public void assertRewriteForRowNumForNotRewriteLimit() { selectStatement.setLimit(new Limit(DatabaseType.Oracle)); selectStatement.getLimit().setOffset(new LimitValue(2, -1, true)); selectStatement.getLimit().setRowCount(new LimitValue(4, -1, false)); - selectStatement.getSqlTokens().add(new TableToken(68, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(119, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(98, 4)); + selectStatement.addSQLToken(new TableToken(68, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(119, 2)); + selectStatement.addSQLToken(new RowCountToken(98, 4)); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT * FROM (SELECT row_.*, rownum rownum_ FROM (SELECT x.id FROM table_x x) row_ WHERE rownum<=4) t WHERE t.rownum_>2", DatabaseType.Oracle, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), @@ -390,9 +390,9 @@ public void assertRewriteForTopAndRowNumberForNotRewriteLimit() { selectStatement.setLimit(new Limit(DatabaseType.SQLServer)); selectStatement.getLimit().setOffset(new LimitValue(2, -1, true)); selectStatement.getLimit().setRowCount(new LimitValue(4, -1, false)); - selectStatement.getSqlTokens().add(new TableToken(85, 0, "table_x")); - selectStatement.getSqlTokens().add(new OffsetToken(123, 2)); - selectStatement.getSqlTokens().add(new RowCountToken(26, 4)); + selectStatement.addSQLToken(new TableToken(85, 0, "table_x")); + selectStatement.addSQLToken(new OffsetToken(123, 2)); + selectStatement.addSQLToken(new RowCountToken(26, 4)); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT * FROM (SELECT TOP(4) row_number() OVER (ORDER BY x.id) AS rownum_, x.id FROM table_x x) AS row_ WHERE row_.rownum_>2", DatabaseType.SQLServer, selectStatement, null, Collections.emptyList()); @@ -405,8 +405,8 @@ public void assertRewriteForDerivedOrderBy() { selectStatement.setGroupByLastPosition(61); selectStatement.getOrderByItems().add(new OrderItem("x", "id", OrderDirection.ASC, OrderDirection.ASC, Optional.absent())); selectStatement.getOrderByItems().add(new OrderItem("x", "name", OrderDirection.DESC, OrderDirection.ASC, Optional.absent())); - selectStatement.getSqlTokens().add(new TableToken(25, 0, "table_x")); - selectStatement.getSqlTokens().add(new OrderByToken(61)); + selectStatement.addSQLToken(new TableToken(25, 0, "table_x")); + selectStatement.addSQLToken(new OrderByToken(61)); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT x.id, x.name FROM table_x x GROUP BY x.id, x.name DESC", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, null, shardingDataSourceMetaData).getSql(), is( @@ -418,9 +418,9 @@ public void assertGenerateSQL() { List parameters = new ArrayList<>(2); parameters.add(1); parameters.add("x"); - selectStatement.getSqlTokens().add(new TableToken(7, 0, "table_x")); - selectStatement.getSqlTokens().add(new TableToken(31, 0, "table_x")); - selectStatement.getSqlTokens().add(new TableToken(58, 0, "table_x")); + selectStatement.addSQLToken(new TableToken(7, 0, "table_x")); + selectStatement.addSQLToken(new TableToken(31, 0, "table_x")); + selectStatement.addSQLToken(new TableToken(58, 0, "table_x")); selectStatement.getTables().add(new Table("table_x", Optional.of("x"))); selectStatement.getTables().add(new Table("table_y", Optional.of("y"))); SQLRewriteEngine sqlRewriteEngine = @@ -435,39 +435,39 @@ public void assertGenerateSQL() { public void assertSchemaTokenRewriteForTableName() { tableTokens = new HashMap<>(1, 1); tableTokens.put("table_x", "table_y"); - selectStatement.getSqlTokens().add(new TableToken(18, 0, "table_x")); - selectStatement.getSqlTokens().add(new SchemaToken(29, "table_x", "table_x")); + selectStatement.addSQLToken(new TableToken(18, 0, "table_x")); + selectStatement.addSQLToken(new SchemaToken(29, "table_x", "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW CREATE TABLE table_x ON table_x", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW CREATE TABLE table_y ON db0")); } @Test public void assertIndexTokenForIndexNameTableName() { - selectStatement.getSqlTokens().add(new IndexToken(13, "index_name", "table_x")); - selectStatement.getSqlTokens().add(new TableToken(27, 0, "table_x")); + selectStatement.addSQLToken(new IndexToken(13, "index_name", "table_x")); + selectStatement.addSQLToken(new TableToken(27, 0, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "CREATE INDEX index_name ON table_x ('column')", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("CREATE INDEX index_name_table_1 ON table_1 ('column')")); } @Test public void assertIndexTokenForIndexNameTableNameWithoutLogicTableName() { - selectStatement.getSqlTokens().add(new IndexToken(13, "logic_index", "")); - selectStatement.getSqlTokens().add(new TableToken(28, 0, "table_x")); + selectStatement.addSQLToken(new IndexToken(13, "logic_index", "")); + selectStatement.addSQLToken(new TableToken(28, 0, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "CREATE INDEX index_names ON table_x ('column')", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(true).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("CREATE INDEX logic_index_table_1 ON table_1 ('column')")); } @Test public void assertTableTokenWithoutBackQuoteForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, 0, "table_x")); + showTablesStatement.addSQLToken(new TableToken(18, 0, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM table_x", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM table_1")); } @Test public void assertTableTokenWithoutBackQuoteFromSchemaForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, 0, "table_x")); - showTablesStatement.getSqlTokens().add(new SchemaToken(31, "'sharding_db'", "table_x")); + showTablesStatement.addSQLToken(new TableToken(18, 0, "table_x")); + showTablesStatement.addSQLToken(new SchemaToken(31, "'sharding_db'", "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM table_x FROM 'sharding_db'", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); Map logicAndActualTableMap = new LinkedHashMap<>(); logicAndActualTableMap.put("table_x", "table_x"); @@ -476,28 +476,28 @@ public void assertTableTokenWithoutBackQuoteFromSchemaForShow() { @Test public void assertTableTokenWithBackQuoteForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, 0, "`table_x`")); + showTablesStatement.addSQLToken(new TableToken(18, 0, "`table_x`")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM `table_x`", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM `table_1`")); } @Test public void assertTableTokenWithBackQuoteFromSchemaForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, 0, "`table_x`")); + showTablesStatement.addSQLToken(new TableToken(18, 0, "`table_x`")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM `table_x` FROM 'sharding_db'", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM `table_1` FROM 'sharding_db'")); } @Test public void assertTableTokenWithSchemaForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, "sharding_db".length() + 1, "table_x")); + showTablesStatement.addSQLToken(new TableToken(18, "sharding_db".length() + 1, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM sharding_db.table_x", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM table_1")); } @Test public void assertTableTokenWithSchemaFromSchemaForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, "sharding_db".length() + 1, "table_x")); + showTablesStatement.addSQLToken(new TableToken(18, "sharding_db".length() + 1, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM sharding_db.table_x FROM sharding_db", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM table_1 FROM sharding_db")); @@ -505,14 +505,14 @@ public void assertTableTokenWithSchemaFromSchemaForShow() { @Test public void assertTableTokenWithBackQuoteWithSchemaForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, "sharding_db".length() + 1, "`table_x`")); + showTablesStatement.addSQLToken(new TableToken(18, "sharding_db".length() + 1, "`table_x`")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM sharding_db.`table_x`", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM `table_1`")); } @Test public void assertTableTokenWithBackQuoteWithSchemaFromSchemaForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, "sharding_db".length() + 1, "`table_x`")); + showTablesStatement.addSQLToken(new TableToken(18, "sharding_db".length() + 1, "`table_x`")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM sharding_db.`table_x` FROM sharding_db", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM `table_1` FROM sharding_db")); @@ -520,14 +520,14 @@ public void assertTableTokenWithBackQuoteWithSchemaFromSchemaForShow() { @Test public void assertTableTokenWithSchemaWithBackQuoteForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, "`sharding_db`".length() + 1, "`table_x`")); + showTablesStatement.addSQLToken(new TableToken(18, "`sharding_db`".length() + 1, "`table_x`")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM `sharding_db`.`table_x`", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM `table_1`")); } @Test public void assertTableTokenWithSchemaWithBackQuoteFromSchemaForShow() { - showTablesStatement.getSqlTokens().add(new TableToken(18, "`sharding_db`".length() + 1, "`table_x`")); + showTablesStatement.addSQLToken(new TableToken(18, "`sharding_db`".length() + 1, "`table_x`")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SHOW COLUMNS FROM `sharding_db`.`table_x` FROM sharding_db", DatabaseType.MySQL, showTablesStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SHOW COLUMNS FROM `table_1` FROM sharding_db")); @@ -535,14 +535,14 @@ public void assertTableTokenWithSchemaWithBackQuoteFromSchemaForShow() { @Test public void assertTableTokenWithSchemaForSelect() { - selectStatement.getSqlTokens().add(new TableToken(14, "sharding_db".length() + 1, "table_x")); + selectStatement.addSQLToken(new TableToken(14, "sharding_db".length() + 1, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT * FROM sharding_db.table_x", DatabaseType.MySQL, selectStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("SELECT * FROM table_1")); } @Test public void assertTableTokenWithSchemaForInsert() { - insertStatement.getSqlTokens().add(new TableToken(12, "sharding_db".length() + 1, "table_x")); + insertStatement.addSQLToken(new TableToken(12, "sharding_db".length() + 1, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "INSERT INTO sharding_db.table_x (order_id, user_id, status) values (1, 1, 'OK')", DatabaseType.MySQL, insertStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL( @@ -551,7 +551,7 @@ public void assertTableTokenWithSchemaForInsert() { @Test public void assertTableTokenWithSchemaForUpdate() { - dmlStatement.getSqlTokens().add(new TableToken(7, "`sharding_db`".length() + 1, "table_x")); + dmlStatement.addSQLToken(new TableToken(7, "`sharding_db`".length() + 1, "table_x")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "UPDATE `sharding_db`.table_x SET user_id=1 WHERE order_id=1", DatabaseType.MySQL, dmlStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("UPDATE table_1 SET user_id=1 WHERE order_id=1")); @@ -559,7 +559,7 @@ public void assertTableTokenWithSchemaForUpdate() { @Test public void assertTableTokenWithSchemaForDelete() { - dmlStatement.getSqlTokens().add(new TableToken(12, "`sharding_db`".length() + 1, "`table_x`")); + dmlStatement.addSQLToken(new TableToken(12, "`sharding_db`".length() + 1, "`table_x`")); SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "DELETE FROM `sharding_db`.`table_x` WHERE user_id=1", DatabaseType.MySQL, dmlStatement, null, Collections.emptyList()); assertThat(rewriteEngine.rewrite(false).toSQL(null, tableTokens, shardingRule, shardingDataSourceMetaData).getSql(), is("DELETE FROM `table_1` WHERE user_id=1")); } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/routing/type/broadcast/TableBroadcastRoutingEngineTest.java b/sharding-core/src/test/java/io/shardingsphere/core/routing/type/broadcast/TableBroadcastRoutingEngineTest.java index a0d1dfcf28079..50620952b9861 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/routing/type/broadcast/TableBroadcastRoutingEngineTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/routing/type/broadcast/TableBroadcastRoutingEngineTest.java @@ -88,7 +88,7 @@ private RoutingResult createDQLStatementRoutingResult() { private RoutingResult createDDLStatementRoutingResult() { DDLStatement ddlStatement = new DDLStatement(); - ddlStatement.getSqlTokens().add(new IndexToken(13, "t_order_index", "t_order")); + ddlStatement.addSQLToken(new IndexToken(13, "t_order_index", "t_order")); TableBroadcastRoutingEngine tableBroadcastRoutingEngine = new TableBroadcastRoutingEngine(shardingRule, ddlStatement); return tableBroadcastRoutingEngine.route(); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendHandlerFactory.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendHandlerFactory.java index c61179671ee6f..f3c28a7fa1d02 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendHandlerFactory.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendHandlerFactory.java @@ -129,12 +129,11 @@ public static BackendHandler createBackendHandler( } private static Optional getSchema(final SQLStatement sqlStatement) { - if (!sqlStatement.getSqlTokens().isEmpty() + List sqlTokens = sqlStatement.getSQLTokens(); + if (!sqlTokens.isEmpty() && (sqlStatement instanceof ShowTablesStatement || sqlStatement instanceof ShowColumnsStatement || sqlStatement instanceof ShowIndexStatement || sqlStatement instanceof ShowTableStatusStatement)) { - LinkedList sqlTokens = new LinkedList<>(); - sqlTokens.addAll(sqlStatement.getSqlTokens()); - return Optional.of(((SchemaToken) sqlTokens.getLast()).getSchemaName()); + return Optional.of(((SchemaToken) new LinkedList<>(sqlTokens).getLast()).getSchemaName()); } return Optional.absent(); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/rewrite/MasterSlaveSQLRewriteEngine.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/rewrite/MasterSlaveSQLRewriteEngine.java index 188509ec61860..9ce02923eb350 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/rewrite/MasterSlaveSQLRewriteEngine.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/rewrite/MasterSlaveSQLRewriteEngine.java @@ -25,9 +25,6 @@ import io.shardingsphere.core.rewrite.placeholder.SchemaPlaceholder; import io.shardingsphere.core.rule.MasterSlaveRule; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; import java.util.List; /** @@ -43,10 +40,10 @@ public final class MasterSlaveSQLRewriteEngine { private final String originalSQL; - private final List sqlTokens = new LinkedList<>(); - private final SQLStatement sqlStatement; + private final List sqlTokens; + private final ShardingMetaData metaData; /** @@ -61,8 +58,8 @@ public MasterSlaveSQLRewriteEngine(final MasterSlaveRule masterSlaveRule, final this.masterSlaveRule = masterSlaveRule; this.originalSQL = originalSQL; this.sqlStatement = sqlStatement; + sqlTokens = sqlStatement.getSQLTokens(); this.metaData = metaData; - sqlTokens.addAll(sqlStatement.getSqlTokens()); } /** @@ -71,18 +68,17 @@ public MasterSlaveSQLRewriteEngine(final MasterSlaveRule masterSlaveRule, final * @return SQL */ public String rewrite() { - if (sqlStatement.getSqlTokens().isEmpty()) { + if (sqlTokens.isEmpty()) { return originalSQL; } SQLBuilder result = new SQLBuilder(null); int count = 0; - sortByBeginPosition(); - for (SQLToken each : sqlStatement.getSqlTokens()) { + for (SQLToken each : sqlTokens) { if (0 == count) { result.appendLiterals(originalSQL.substring(0, each.getBeginPosition())); } if (each instanceof SchemaToken) { - appendSchemaPlaceholder(originalSQL, result, (SchemaToken) each, count, sqlStatement.getSqlTokens()); + appendSchemaPlaceholder(originalSQL, result, (SchemaToken) each, count, sqlTokens); } count++; } @@ -95,15 +91,4 @@ private void appendSchemaPlaceholder(final String sql, final SQLBuilder sqlBuild int endPosition = sqlTokens.size() - 1 == count ? sql.length() : sqlTokens.get(count + 1).getBeginPosition(); sqlBuilder.appendLiterals(sql.substring(beginPosition, endPosition)); } - - private void sortByBeginPosition() { - Collections.sort(sqlTokens, new Comparator() { - - @Override - public int compare(final SQLToken o1, final SQLToken o2) { - return o1.getBeginPosition() - o2.getBeginPosition(); - } - }); - } - } From 028d7c8693cc2e59029144466a5acc168fb614f7 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 18 Oct 2018 23:29:50 +0800 Subject: [PATCH 09/10] move MasterSlaveSQLRewriteEngine to sharding-core --- .../core}/rewrite/MasterSlaveSQLRewriteEngine.java | 11 ++++------- .../wrapper/PreparedStatementExecutorWrapper.java | 2 +- .../jdbc/wrapper/StatementExecutorWrapper.java | 2 +- 3 files changed, 6 insertions(+), 9 deletions(-) rename {sharding-proxy/src/main/java/io/shardingsphere/shardingproxy => sharding-core/src/main/java/io/shardingsphere/core}/rewrite/MasterSlaveSQLRewriteEngine.java (91%) diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/rewrite/MasterSlaveSQLRewriteEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/rewrite/MasterSlaveSQLRewriteEngine.java similarity index 91% rename from sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/rewrite/MasterSlaveSQLRewriteEngine.java rename to sharding-core/src/main/java/io/shardingsphere/core/rewrite/MasterSlaveSQLRewriteEngine.java index 9ce02923eb350..c42ab61686d0c 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/rewrite/MasterSlaveSQLRewriteEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/rewrite/MasterSlaveSQLRewriteEngine.java @@ -15,16 +15,16 @@ *

*/ -package io.shardingsphere.shardingproxy.rewrite; +package io.shardingsphere.core.rewrite; import io.shardingsphere.core.metadata.ShardingMetaData; import io.shardingsphere.core.parsing.parser.sql.SQLStatement; import io.shardingsphere.core.parsing.parser.token.SQLToken; import io.shardingsphere.core.parsing.parser.token.SchemaToken; -import io.shardingsphere.core.rewrite.SQLBuilder; import io.shardingsphere.core.rewrite.placeholder.SchemaPlaceholder; import io.shardingsphere.core.rule.MasterSlaveRule; +import java.util.Collections; import java.util.List; /** @@ -40,8 +40,6 @@ public final class MasterSlaveSQLRewriteEngine { private final String originalSQL; - private final SQLStatement sqlStatement; - private final List sqlTokens; private final ShardingMetaData metaData; @@ -51,13 +49,12 @@ public final class MasterSlaveSQLRewriteEngine { * * @param masterSlaveRule master slave rule * @param originalSQL original SQL - * @param sqlStatement sql statement + * @param sqlStatement SQL statement * @param metaData meta data */ public MasterSlaveSQLRewriteEngine(final MasterSlaveRule masterSlaveRule, final String originalSQL, final SQLStatement sqlStatement, final ShardingMetaData metaData) { this.masterSlaveRule = masterSlaveRule; this.originalSQL = originalSQL; - this.sqlStatement = sqlStatement; sqlTokens = sqlStatement.getSQLTokens(); this.metaData = metaData; } @@ -71,7 +68,7 @@ public String rewrite() { if (sqlTokens.isEmpty()) { return originalSQL; } - SQLBuilder result = new SQLBuilder(null); + SQLBuilder result = new SQLBuilder(Collections.emptyList()); int count = 0; for (SQLToken each : sqlTokens) { if (0 == count) { diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/PreparedStatementExecutorWrapper.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/PreparedStatementExecutorWrapper.java index 3f093956eb6ee..23485cc654188 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/PreparedStatementExecutorWrapper.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/PreparedStatementExecutorWrapper.java @@ -20,12 +20,12 @@ import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.core.parsing.SQLJudgeEngine; import io.shardingsphere.core.parsing.parser.sql.SQLStatement; +import io.shardingsphere.core.rewrite.MasterSlaveSQLRewriteEngine; import io.shardingsphere.core.routing.PreparedStatementRoutingEngine; import io.shardingsphere.core.routing.RouteUnit; import io.shardingsphere.core.routing.SQLRouteResult; import io.shardingsphere.core.routing.SQLUnit; import io.shardingsphere.core.routing.router.masterslave.MasterSlaveRouter; -import io.shardingsphere.shardingproxy.rewrite.MasterSlaveSQLRewriteEngine; import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import lombok.RequiredArgsConstructor; diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/StatementExecutorWrapper.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/StatementExecutorWrapper.java index bedec3c89f85b..73bd94ef818d9 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/StatementExecutorWrapper.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/StatementExecutorWrapper.java @@ -20,12 +20,12 @@ import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.core.parsing.SQLJudgeEngine; import io.shardingsphere.core.parsing.parser.sql.SQLStatement; +import io.shardingsphere.core.rewrite.MasterSlaveSQLRewriteEngine; import io.shardingsphere.core.routing.RouteUnit; import io.shardingsphere.core.routing.SQLRouteResult; import io.shardingsphere.core.routing.SQLUnit; import io.shardingsphere.core.routing.StatementRoutingEngine; import io.shardingsphere.core.routing.router.masterslave.MasterSlaveRouter; -import io.shardingsphere.shardingproxy.rewrite.MasterSlaveSQLRewriteEngine; import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import lombok.RequiredArgsConstructor; From f1886bd3f45de843f9554cd80905be531e101b66 Mon Sep 17 00:00:00 2001 From: terrymanu Date: Thu, 18 Oct 2018 23:34:57 +0800 Subject: [PATCH 10/10] refactor rewrite --- .../rewrite/MasterSlaveSQLRewriteEngine.java | 4 +- .../core/rewrite/SQLRewriteEngine.java | 70 +++++++++---------- 2 files changed, 37 insertions(+), 37 deletions(-) diff --git a/sharding-core/src/main/java/io/shardingsphere/core/rewrite/MasterSlaveSQLRewriteEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/rewrite/MasterSlaveSQLRewriteEngine.java index c42ab61686d0c..268c859feaab9 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/rewrite/MasterSlaveSQLRewriteEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/rewrite/MasterSlaveSQLRewriteEngine.java @@ -75,14 +75,14 @@ public String rewrite() { result.appendLiterals(originalSQL.substring(0, each.getBeginPosition())); } if (each instanceof SchemaToken) { - appendSchemaPlaceholder(originalSQL, result, (SchemaToken) each, count, sqlTokens); + appendSchemaPlaceholder(originalSQL, result, (SchemaToken) each, count); } count++; } return result.toSQL(masterSlaveRule, metaData.getDataSource()); } - private void appendSchemaPlaceholder(final String sql, final SQLBuilder sqlBuilder, final SchemaToken schemaToken, final int count, final List sqlTokens) { + private void appendSchemaPlaceholder(final String sql, final SQLBuilder sqlBuilder, final SchemaToken schemaToken, final int count) { sqlBuilder.appendPlaceholder(new SchemaPlaceholder(schemaToken.getSchemaName().toLowerCase(), null)); int beginPosition = schemaToken.getBeginPosition() + schemaToken.getOriginalLiterals().length(); int endPosition = sqlTokens.size() - 1 == count ? sql.length() : sqlTokens.get(count + 1).getBeginPosition(); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/rewrite/SQLRewriteEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/rewrite/SQLRewriteEngine.java index c0aefa989f752..e7bd9ed3e5cda 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/rewrite/SQLRewriteEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/rewrite/SQLRewriteEngine.java @@ -118,44 +118,44 @@ public SQLBuilder rewrite(final boolean isRewriteLimit) { result.appendLiterals(originalSQL.substring(0, each.getBeginPosition())); } if (each instanceof TableToken) { - appendTablePlaceholder(result, (TableToken) each, count, sqlTokens); + appendTablePlaceholder(result, (TableToken) each, count); } else if (each instanceof SchemaToken) { - appendSchemaPlaceholder(result, (SchemaToken) each, count, sqlTokens); + appendSchemaPlaceholder(result, (SchemaToken) each, count); } else if (each instanceof IndexToken) { - appendIndexPlaceholder(result, (IndexToken) each, count, sqlTokens); + appendIndexPlaceholder(result, (IndexToken) each, count); } else if (each instanceof ItemsToken) { - appendItemsToken(result, (ItemsToken) each, count, sqlTokens); + appendItemsToken(result, (ItemsToken) each, count); } else if (each instanceof InsertValuesToken) { - appendInsertValuesToken(result, (InsertValuesToken) each, count, sqlTokens); + appendInsertValuesToken(result, (InsertValuesToken) each, count); } else if (each instanceof RowCountToken) { - appendLimitRowCount(result, (RowCountToken) each, count, sqlTokens, isRewriteLimit); + appendLimitRowCount(result, (RowCountToken) each, count, isRewriteLimit); } else if (each instanceof OffsetToken) { - appendLimitOffsetToken(result, (OffsetToken) each, count, sqlTokens, isRewriteLimit); + appendLimitOffsetToken(result, (OffsetToken) each, count, isRewriteLimit); } else if (each instanceof OrderByToken) { - appendOrderByToken(result, count, sqlTokens); + appendOrderByToken(result, count); } else if (each instanceof InsertColumnToken) { - appendSymbolToken(result, (InsertColumnToken) each, count, sqlTokens); + appendSymbolToken(result, (InsertColumnToken) each, count); } else if (each instanceof RemoveToken) { - appendRest(result, count, sqlTokens, ((RemoveToken) each).getEndPosition()); + appendRest(result, count, ((RemoveToken) each).getEndPosition()); } count++; } return result; } - private void appendTablePlaceholder(final SQLBuilder sqlBuilder, final TableToken tableToken, final int count, final List sqlTokens) { + private void appendTablePlaceholder(final SQLBuilder sqlBuilder, final TableToken tableToken, final int count) { sqlBuilder.appendPlaceholder(new TablePlaceholder(tableToken.getTableName().toLowerCase(), tableToken.getOriginalLiterals())); int beginPosition = tableToken.getBeginPosition() + tableToken.getSkippedSchemaNameLength() + tableToken.getOriginalLiterals().length(); - appendRest(sqlBuilder, count, sqlTokens, beginPosition); + appendRest(sqlBuilder, count, beginPosition); } - private void appendSchemaPlaceholder(final SQLBuilder sqlBuilder, final SchemaToken schemaToken, final int count, final List sqlTokens) { + private void appendSchemaPlaceholder(final SQLBuilder sqlBuilder, final SchemaToken schemaToken, final int count) { sqlBuilder.appendPlaceholder(new SchemaPlaceholder(schemaToken.getSchemaName().toLowerCase(), schemaToken.getTableName().toLowerCase())); int beginPosition = schemaToken.getBeginPosition() + schemaToken.getOriginalLiterals().length(); - appendRest(sqlBuilder, count, sqlTokens, beginPosition); + appendRest(sqlBuilder, count, beginPosition); } - private void appendIndexPlaceholder(final SQLBuilder sqlBuilder, final IndexToken indexToken, final int count, final List sqlTokens) { + private void appendIndexPlaceholder(final SQLBuilder sqlBuilder, final IndexToken indexToken, final int count) { String indexName = indexToken.getIndexName().toLowerCase(); String logicTableName = indexToken.getTableName().toLowerCase(); if (Strings.isNullOrEmpty(logicTableName)) { @@ -163,10 +163,10 @@ private void appendIndexPlaceholder(final SQLBuilder sqlBuilder, final IndexToke } sqlBuilder.appendPlaceholder(new IndexPlaceholder(indexName, logicTableName)); int beginPosition = indexToken.getBeginPosition() + indexToken.getOriginalLiterals().length(); - appendRest(sqlBuilder, count, sqlTokens, beginPosition); + appendRest(sqlBuilder, count, beginPosition); } - private void appendItemsToken(final SQLBuilder sqlBuilder, final ItemsToken itemsToken, final int count, final List sqlTokens) { + private void appendItemsToken(final SQLBuilder sqlBuilder, final ItemsToken itemsToken, final int count) { for (int i = 0; i < itemsToken.getItems().size(); i++) { if (itemsToken.isFirstOfItemsSpecial() && 0 == i) { sqlBuilder.appendLiterals(SQLUtil.getOriginalValue(itemsToken.getItems().get(i), databaseType)); @@ -175,15 +175,15 @@ private void appendItemsToken(final SQLBuilder sqlBuilder, final ItemsToken item sqlBuilder.appendLiterals(SQLUtil.getOriginalValue(itemsToken.getItems().get(i), databaseType)); } } - appendRest(sqlBuilder, count, sqlTokens, itemsToken.getBeginPosition()); + appendRest(sqlBuilder, count, itemsToken.getBeginPosition()); } - private void appendInsertValuesToken(final SQLBuilder sqlBuilder, final InsertValuesToken insertValuesToken, final int count, final List sqlTokens) { + private void appendInsertValuesToken(final SQLBuilder sqlBuilder, final InsertValuesToken insertValuesToken, final int count) { sqlBuilder.appendPlaceholder(new InsertValuesPlaceholder(insertValuesToken.getTableName().toLowerCase(), shardingConditions)); - appendRest(sqlBuilder, count, sqlTokens, ((InsertStatement) sqlStatement).getInsertValuesListLastPosition()); + appendRest(sqlBuilder, count, ((InsertStatement) sqlStatement).getInsertValuesListLastPosition()); } - private void appendLimitRowCount(final SQLBuilder sqlBuilder, final RowCountToken rowCountToken, final int count, final List sqlTokens, final boolean isRewrite) { + private void appendLimitRowCount(final SQLBuilder sqlBuilder, final RowCountToken rowCountToken, final int count, final boolean isRewrite) { SelectStatement selectStatement = (SelectStatement) sqlStatement; Limit limit = selectStatement.getLimit(); if (!isRewrite) { @@ -194,16 +194,16 @@ private void appendLimitRowCount(final SQLBuilder sqlBuilder, final RowCountToke sqlBuilder.appendLiterals(String.valueOf(limit.isNeedRewriteRowCount() ? rowCountToken.getRowCount() + limit.getOffsetValue() : rowCountToken.getRowCount())); } int beginPosition = rowCountToken.getBeginPosition() + String.valueOf(rowCountToken.getRowCount()).length(); - appendRest(sqlBuilder, count, sqlTokens, beginPosition); + appendRest(sqlBuilder, count, beginPosition); } - private void appendLimitOffsetToken(final SQLBuilder sqlBuilder, final OffsetToken offsetToken, final int count, final List sqlTokens, final boolean isRewrite) { + private void appendLimitOffsetToken(final SQLBuilder sqlBuilder, final OffsetToken offsetToken, final int count, final boolean isRewrite) { sqlBuilder.appendLiterals(isRewrite ? "0" : String.valueOf(offsetToken.getOffset())); int beginPosition = offsetToken.getBeginPosition() + String.valueOf(offsetToken.getOffset()).length(); - appendRest(sqlBuilder, count, sqlTokens, beginPosition); + appendRest(sqlBuilder, count, beginPosition); } - private void appendOrderByToken(final SQLBuilder sqlBuilder, final int count, final List sqlTokens) { + private void appendOrderByToken(final SQLBuilder sqlBuilder, final int count) { SelectStatement selectStatement = (SelectStatement) sqlStatement; StringBuilder orderByLiterals = new StringBuilder(); orderByLiterals.append(" ").append(DefaultKeyword.ORDER).append(" ").append(DefaultKeyword.BY).append(" "); @@ -220,15 +220,15 @@ private void appendOrderByToken(final SQLBuilder sqlBuilder, final int count, fi orderByLiterals.append(" "); sqlBuilder.appendLiterals(orderByLiterals.toString()); int beginPosition = ((SelectStatement) sqlStatement).getGroupByLastPosition(); - appendRest(sqlBuilder, count, sqlTokens, beginPosition); + appendRest(sqlBuilder, count, beginPosition); } - private void appendSymbolToken(final SQLBuilder sqlBuilder, final InsertColumnToken insertColumnToken, final int count, final List sqlTokens) { + private void appendSymbolToken(final SQLBuilder sqlBuilder, final InsertColumnToken insertColumnToken, final int count) { sqlBuilder.appendLiterals(insertColumnToken.getColumnName()); - appendRest(sqlBuilder, count, sqlTokens, insertColumnToken.getBeginPosition()); + appendRest(sqlBuilder, count, insertColumnToken.getBeginPosition()); } - private void appendRest(final SQLBuilder sqlBuilder, final int count, final List sqlTokens, final int beginPosition) { + private void appendRest(final SQLBuilder sqlBuilder, final int count, final int beginPosition) { int endPosition = sqlTokens.size() - 1 == count ? originalSQL.length() : sqlTokens.get(count + 1).getBeginPosition(); sqlBuilder.appendLiterals(originalSQL.substring(beginPosition, endPosition)); } @@ -247,12 +247,12 @@ public SQLUnit generateSQL(final TableUnit tableUnit, final SQLBuilder sqlBuilde private Map getTableTokens(final TableUnit tableUnit) { Map result = new HashMap<>(); - for (RoutingTable routingTable : tableUnit.getRoutingTables()) { - String logicTableName = routingTable.getLogicTableName().toLowerCase(); - result.put(logicTableName, routingTable.getActualTableName()); + for (RoutingTable each : tableUnit.getRoutingTables()) { + String logicTableName = each.getLogicTableName().toLowerCase(); + result.put(logicTableName, each.getActualTableName()); Optional bindingTableRule = shardingRule.findBindingTableRule(logicTableName); if (bindingTableRule.isPresent()) { - result.putAll(getBindingTableTokens(tableUnit.getDataSourceName(), routingTable, bindingTableRule.get())); + result.putAll(getBindingTableTokens(tableUnit.getDataSourceName(), each, bindingTableRule.get())); } } return result; @@ -260,8 +260,8 @@ private Map getTableTokens(final TableUnit tableUnit) { private Map getBindingTableTokens(final String dataSourceName, final RoutingTable routingTable, final BindingTableRule bindingTableRule) { Map result = new HashMap<>(); - for (String eachTable : sqlStatement.getTables().getTableNames()) { - String tableName = eachTable.toLowerCase(); + for (String each : sqlStatement.getTables().getTableNames()) { + String tableName = each.toLowerCase(); if (!tableName.equals(routingTable.getLogicTableName().toLowerCase()) && bindingTableRule.hasLogicTable(tableName)) { result.put(tableName, bindingTableRule.getBindingActualTable(dataSourceName, tableName, routingTable.getActualTableName())); }