提交 0bf938c8 编写于 作者: 孙不服 提交者: guangyuan

Feature 3185 jdbc orchestration. (#3568)

* add sharding-jdbc-orchestration-new for orchestration-5.x

* add a UT class for `YamlInstanceConfigurationSwapperUtil`.

* rename package `org.apache.shardingsphere.shardingjdbc.orchestration` to `org.apache.shardingsphere.shardingjdbc.orchestration.temp`.

* modify unit test class.
上级 a1db914a
......@@ -30,5 +30,6 @@
<modules>
<module>sharding-jdbc-core</module>
<module>sharding-jdbc-orchestration</module>
<module>sharding-jdbc-orchestration-new</module>
</modules>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc</artifactId>
<version>4.0.0-RC3-SNAPSHOT</version>
</parent>
<artifactId>sharding-jdbc-orchestration-new</artifactId>
<name>${project.artifactId}</name>
<dependencies>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-orchestration-core-new</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-orchestration-center</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-core-entry</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP-java7</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-orchestration-reg-api</artifactId>
<version>4.0.0-RC3-SNAPSHOT</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api;
import org.apache.shardingsphere.api.config.encrypt.EncryptRuleConfiguration;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.EncryptDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationEncryptDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;
/**
* Orchestration encrypt data source factory.
*
* @author yangyi
*/
public final class OrchestrationEncryptDataSourceFactory {
/**
* Create orchestration encrypt data source.
*
* @param dataSource data source
* @param encryptRuleConfig encrypt rule configuration
* @param props properties
* @param orchestrationConfig orchestration configuration
* @return orchestration encrypt data source
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final DataSource dataSource,
final EncryptRuleConfiguration encryptRuleConfig, final Properties props, final OrchestrationConfiguration orchestrationConfig) throws SQLException {
if (null == encryptRuleConfig || encryptRuleConfig.getEncryptors().isEmpty()) {
return createDataSource(orchestrationConfig);
}
return new OrchestrationEncryptDataSource(new EncryptDataSource(dataSource, new EncryptRule(encryptRuleConfig), props), orchestrationConfig);
}
/**
* Create orchestration encrypt data source.
*
* @param orchestrationConfig orchestration configuration
* @return orchestration encrypt data source
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final OrchestrationConfiguration orchestrationConfig) throws SQLException {
return new OrchestrationEncryptDataSource(orchestrationConfig);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.core.rule.MasterSlaveRule;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.MasterSlaveDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationMasterSlaveDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
/**
* Orchestration sharding data source factory.
*
* @author panjuan
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class OrchestrationMasterSlaveDataSourceFactory {
/**
* Create master-slave data source.
*
* @param dataSourceMap data source map
* @param masterSlaveRuleConfig master-slave rule configuration
* @param props properties
* @param orchestrationConfig orchestration configuration
* @return master-slave data source
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig,
final Properties props, final OrchestrationConfiguration orchestrationConfig) throws SQLException {
if (null == masterSlaveRuleConfig || null == masterSlaveRuleConfig.getMasterDataSourceName()) {
return createDataSource(orchestrationConfig);
}
MasterSlaveDataSource masterSlaveDataSource = new MasterSlaveDataSource(dataSourceMap, new MasterSlaveRule(masterSlaveRuleConfig), props);
return new OrchestrationMasterSlaveDataSource(masterSlaveDataSource, orchestrationConfig);
}
/**
* Create master-slave data source.
*
* @param orchestrationConfig orchestration configuration
* @return master-slave data source
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final OrchestrationConfiguration orchestrationConfig) throws SQLException {
return new OrchestrationMasterSlaveDataSource(orchestrationConfig);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationShardingDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
/**
* Orchestration sharding data source factory.
*
* @author panjuan
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class OrchestrationShardingDataSourceFactory {
/**
* Create sharding data source.
*
* @param dataSourceMap data source map
* @param shardingRuleConfig sharding rule configuration
* @param orchestrationConfig orchestration configuration
* @param props properties for data source
* @return sharding data source
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final ShardingRuleConfiguration shardingRuleConfig,
final Properties props, final OrchestrationConfiguration orchestrationConfig) throws SQLException {
if (null == shardingRuleConfig || shardingRuleConfig.getTableRuleConfigs().isEmpty()) {
return createDataSource(orchestrationConfig);
}
ShardingDataSource shardingDataSource = new ShardingDataSource(dataSourceMap, new ShardingRule(shardingRuleConfig, dataSourceMap.keySet()), props);
return new OrchestrationShardingDataSource(shardingDataSource, orchestrationConfig);
}
/**
* Create sharding data source.
*
* @param orchestrationConfig orchestration configuration
* @return sharding data source
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final OrchestrationConfiguration orchestrationConfig) throws SQLException {
return new OrchestrationShardingDataSource(orchestrationConfig);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.yaml.config.encrypt.YamlEncryptRuleConfiguration;
import org.apache.shardingsphere.core.yaml.engine.YamlEngine;
import org.apache.shardingsphere.core.yaml.swapper.impl.EncryptRuleConfigurationYamlSwapper;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.config.YamlInstanceConfiguration;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.EncryptDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationEncryptDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util.YamlInstanceConfigurationSwapperUtil;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.yaml.YamlOrchestrationEncryptRuleConfiguration;
/**
* Orchestration encrypt data source factory for YAML.
*
* @author yangyi
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class YamlOrchestrationEncryptDataSourceFactory {
private static final EncryptRuleConfigurationYamlSwapper ENCRYPT_RULE_SWAPPER = new EncryptRuleConfigurationYamlSwapper();
/**
* Create encrypt data source.
*
* @param yamlFile YAML file for encrypt rule configuration with data source
* @return encrypt data source
* @throws IOException IO exception
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final File yamlFile) throws IOException, SQLException {
YamlOrchestrationEncryptRuleConfiguration config = unmarshal(yamlFile);
return createDataSource(config.getDataSource(), config.getEncryptRule(), config.getOrchestration(), config.getProps());
}
/**
* Create encrypt data source.
*
* @param dataSource data source
* @param yamlFile YAML file for encrypt rule configuration without data source
* @return encrypt data source
* @throws IOException IO exception
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final DataSource dataSource, final File yamlFile) throws IOException, SQLException {
YamlOrchestrationEncryptRuleConfiguration config = unmarshal(yamlFile);
return createDataSource(dataSource, config.getEncryptRule(), config.getOrchestration(), config.getProps());
}
/**
* Create encrypt data source.
*
* @param yamlBytes YAML bytes for for encrypt rule configuration with data source
* @return encrypt data source
* @throws IOException IO exception
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final byte[] yamlBytes) throws IOException, SQLException {
YamlOrchestrationEncryptRuleConfiguration config = unmarshal(yamlBytes);
return createDataSource(config.getDataSource(), config.getEncryptRule(), config.getOrchestration(), config.getProps());
}
/**
* Create encrypt data source.
*
* @param dataSource data source
* @param yamlBytes YAML bytes for encrypt rule configuration without data source
* @return encrypt data source
* @throws IOException IO exception
* @throws SQLException SQL exception
*/
public static DataSource createDataSource(final DataSource dataSource, final byte[] yamlBytes) throws IOException, SQLException {
YamlOrchestrationEncryptRuleConfiguration config = unmarshal(yamlBytes);
return createDataSource(dataSource, config.getEncryptRule(), config.getOrchestration(), config.getProps());
}
private static DataSource createDataSource(final DataSource dataSource, final YamlEncryptRuleConfiguration yamlEncryptRuleConfiguration,
final Map<String, YamlInstanceConfiguration> yamlInstanceConfigurationMap, final Properties properties) throws SQLException {
if (null == yamlEncryptRuleConfiguration) {
return new OrchestrationEncryptDataSource(new OrchestrationConfiguration(YamlInstanceConfigurationSwapperUtil.marshal(yamlInstanceConfigurationMap)));
} else {
EncryptDataSource encryptDataSource = new EncryptDataSource(dataSource, new EncryptRule(ENCRYPT_RULE_SWAPPER.swap(yamlEncryptRuleConfiguration)), properties);
return new OrchestrationEncryptDataSource(encryptDataSource, new OrchestrationConfiguration(YamlInstanceConfigurationSwapperUtil.marshal(yamlInstanceConfigurationMap)));
}
}
private static YamlOrchestrationEncryptRuleConfiguration unmarshal(final File yamlFile) throws IOException {
return YamlEngine.unmarshal(yamlFile, YamlOrchestrationEncryptRuleConfiguration.class);
}
private static YamlOrchestrationEncryptRuleConfiguration unmarshal(final byte[] yamlBytes) throws IOException {
return YamlEngine.unmarshal(yamlBytes, YamlOrchestrationEncryptRuleConfiguration.class);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.core.rule.MasterSlaveRule;
import org.apache.shardingsphere.core.yaml.config.masterslave.YamlMasterSlaveRuleConfiguration;
import org.apache.shardingsphere.core.yaml.engine.YamlEngine;
import org.apache.shardingsphere.core.yaml.swapper.impl.MasterSlaveRuleConfigurationYamlSwapper;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.config.YamlInstanceConfiguration;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.MasterSlaveDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationMasterSlaveDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util.YamlInstanceConfigurationSwapperUtil;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.yaml.YamlOrchestrationMasterSlaveRuleConfiguration;
/**
* Orchestration master-slave data source factory for YAML.
*
* @author zhangliang
* @author caohao
* @author panjuan
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class YamlOrchestrationMasterSlaveDataSourceFactory {
private static final MasterSlaveRuleConfigurationYamlSwapper MASTER_SLAVE_RULE_SWAPPER = new MasterSlaveRuleConfigurationYamlSwapper();
/**
* Create master-slave data source.
*
* @param yamlFile YAML file for master-slave rule configuration with data sources
* @return master-slave data source
* @throws SQLException SQL exception
* @throws IOException IO exception
*/
public static DataSource createDataSource(final File yamlFile) throws SQLException, IOException {
YamlOrchestrationMasterSlaveRuleConfiguration config = unmarshal(yamlFile);
return createDataSource(config.getDataSources(), config.getMasterSlaveRule(), config.getProps(), config.getOrchestration());
}
/**
* Create master-slave data source.
*
* @param dataSourceMap data source map
* @param yamlFile YAML file for master-slave rule configuration without data sources
* @return master-slave data source
* @throws SQLException SQL exception
* @throws IOException IO exception
*/
public static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final File yamlFile) throws SQLException, IOException {
YamlOrchestrationMasterSlaveRuleConfiguration config = unmarshal(yamlFile);
return createDataSource(dataSourceMap, config.getMasterSlaveRule(), config.getProps(), config.getOrchestration());
}
/**
* Create master-slave data source.
*
* @param yamlBytes YAML bytes for master-slave rule configuration with data sources
* @return master-slave data source
* @throws SQLException SQL exception
* @throws IOException IO exception
*/
public static DataSource createDataSource(final byte[] yamlBytes) throws SQLException, IOException {
YamlOrchestrationMasterSlaveRuleConfiguration config = unmarshal(yamlBytes);
return createDataSource(config.getDataSources(), config.getMasterSlaveRule(), config.getProps(), config.getOrchestration());
}
/**
* Create master-slave data source.
*
* @param dataSourceMap data source map
* @param yamlBytes YAML bytes for master-slave rule configuration without data sources
* @return master-slave data source
* @throws SQLException SQL exception
* @throws IOException IO exception
*/
public static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final byte[] yamlBytes) throws SQLException, IOException {
YamlOrchestrationMasterSlaveRuleConfiguration config = unmarshal(yamlBytes);
return createDataSource(dataSourceMap, config.getMasterSlaveRule(), config.getProps(), config.getOrchestration());
}
private static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final YamlMasterSlaveRuleConfiguration yamlMasterSlaveRuleConfiguration,
final Properties props, final Map<String, YamlInstanceConfiguration> yamlInstanceConfigurationMap) throws SQLException {
if (null == yamlMasterSlaveRuleConfiguration) {
return new OrchestrationMasterSlaveDataSource(new OrchestrationConfiguration(YamlInstanceConfigurationSwapperUtil.marshal(yamlInstanceConfigurationMap)));
} else {
MasterSlaveDataSource masterSlaveDataSource = new MasterSlaveDataSource(dataSourceMap, new MasterSlaveRule(MASTER_SLAVE_RULE_SWAPPER.swap(yamlMasterSlaveRuleConfiguration)), props);
return new OrchestrationMasterSlaveDataSource(masterSlaveDataSource, new OrchestrationConfiguration(YamlInstanceConfigurationSwapperUtil.marshal(yamlInstanceConfigurationMap)));
}
}
private static YamlOrchestrationMasterSlaveRuleConfiguration unmarshal(final File yamlFile) throws IOException {
return YamlEngine.unmarshal(yamlFile, YamlOrchestrationMasterSlaveRuleConfiguration.class);
}
private static YamlOrchestrationMasterSlaveRuleConfiguration unmarshal(final byte[] yamlBytes) throws IOException {
return YamlEngine.unmarshal(yamlBytes, YamlOrchestrationMasterSlaveRuleConfiguration.class);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.yaml.config.sharding.YamlShardingRuleConfiguration;
import org.apache.shardingsphere.core.yaml.engine.YamlEngine;
import org.apache.shardingsphere.core.yaml.swapper.impl.ShardingRuleConfigurationYamlSwapper;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.config.YamlInstanceConfiguration;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util.YamlInstanceConfigurationSwapperUtil;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.yaml.YamlOrchestrationShardingRuleConfiguration;
/**
* Orchestration sharding data source factory for YAML.
*
* @author zhangliang
* @author caohao
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class YamlOrchestrationShardingDataSourceFactory {
private static final ShardingRuleConfigurationYamlSwapper SHARDING_RULE_SWAPPER = new ShardingRuleConfigurationYamlSwapper();
/**
* Create sharding data source.
*
* @param yamlFile YAML file for rule configuration of databases and tables sharding with data sources
* @return sharding data source
* @throws SQLException SQL exception
* @throws IOException IO exception
*/
public static DataSource createDataSource(final File yamlFile) throws SQLException, IOException {
YamlOrchestrationShardingRuleConfiguration config = unmarshal(yamlFile);
return createDataSource(config.getDataSources(), config.getShardingRule(), config.getProps(), config.getOrchestration());
}
/**
* Create sharding data source.
*
* @param dataSourceMap data source map
* @param yamlFile YAML file for rule configuration of databases and tables sharding without data sources
* @return sharding data source
* @throws SQLException SQL exception
* @throws IOException IO exception
*/
public static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final File yamlFile) throws SQLException, IOException {
YamlOrchestrationShardingRuleConfiguration config = unmarshal(yamlFile);
return createDataSource(dataSourceMap, config.getShardingRule(), config.getProps(), config.getOrchestration());
}
/**
* Create sharding data source.
*
* @param yamlBytes YAML bytes for rule configuration of databases and tables sharding with data sources
* @return sharding data source
* @throws SQLException SQL exception
* @throws IOException IO exception
*/
public static DataSource createDataSource(final byte[] yamlBytes) throws SQLException, IOException {
YamlOrchestrationShardingRuleConfiguration config = unmarshal(yamlBytes);
return createDataSource(config.getDataSources(), config.getShardingRule(), config.getProps(), config.getOrchestration());
}
/**
* Create sharding data source.
*
* @param dataSourceMap data source map
* @param yamlBytes YAML bytes for rule configuration of databases and tables sharding without data sources
* @return sharding data source
* @throws SQLException SQL exception
* @throws IOException IO exception
*/
public static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final byte[] yamlBytes) throws SQLException, IOException {
YamlOrchestrationShardingRuleConfiguration config = unmarshal(yamlBytes);
return createDataSource(dataSourceMap, config.getShardingRule(), config.getProps(), config.getOrchestration());
}
private static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final YamlShardingRuleConfiguration yamlShardingRuleConfiguration,
final Properties props, final Map<String, YamlInstanceConfiguration> yamlInstanceConfigurationMap) throws SQLException {
if (null == yamlShardingRuleConfiguration) {
return new OrchestrationShardingDataSource(new OrchestrationConfiguration(YamlInstanceConfigurationSwapperUtil.marshal(yamlInstanceConfigurationMap)));
} else {
ShardingDataSource shardingDataSource = new ShardingDataSource(
dataSourceMap, new ShardingRule(SHARDING_RULE_SWAPPER.swap(yamlShardingRuleConfiguration), dataSourceMap.keySet()), props);
return new OrchestrationShardingDataSource(shardingDataSource, new OrchestrationConfiguration(YamlInstanceConfigurationSwapperUtil.marshal(yamlInstanceConfigurationMap)));
}
}
private static YamlOrchestrationShardingRuleConfiguration unmarshal(final File yamlFile) throws IOException {
return YamlEngine.unmarshal(yamlFile, YamlOrchestrationShardingRuleConfiguration.class);
}
private static YamlOrchestrationShardingRuleConfiguration unmarshal(final byte[] yamlBytes) throws IOException {
return YamlEngine.unmarshal(yamlBytes, YamlOrchestrationShardingRuleConfiguration.class);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.connection;
import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationConnection;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.metadata.CircuitBreakerDatabaseMetaData;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.statement.CircuitBreakerPreparedStatement;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.statement.CircuitBreakerStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLWarning;
import java.sql.Statement;
/**
* Circuit breaker connection.
*
* @author caohao
*/
public final class CircuitBreakerConnection extends AbstractUnsupportedOperationConnection {
@Override
public DatabaseMetaData getMetaData() {
return new CircuitBreakerDatabaseMetaData();
}
@Override
public void setReadOnly(final boolean readOnly) {
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public void setTransactionIsolation(final int level) {
}
@Override
public int getTransactionIsolation() {
return Connection.TRANSACTION_NONE;
}
@Override
public SQLWarning getWarnings() {
return null;
}
@Override
public void clearWarnings() {
}
@Override
public void setAutoCommit(final boolean autoCommit) {
}
@Override
public boolean getAutoCommit() {
return false;
}
@Override
public void commit() {
}
@Override
public void rollback() {
}
@Override
public void setHoldability(final int holdability) {
}
@Override
public int getHoldability() {
return 0;
}
@Override
public PreparedStatement prepareStatement(final String sql) {
return new CircuitBreakerPreparedStatement();
}
@Override
public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency) {
return new CircuitBreakerPreparedStatement();
}
@Override
public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) {
return new CircuitBreakerPreparedStatement();
}
@Override
public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) {
return new CircuitBreakerPreparedStatement();
}
@Override
public PreparedStatement prepareStatement(final String sql, final int[] columnIndexes) {
return new CircuitBreakerPreparedStatement();
}
@Override
public PreparedStatement prepareStatement(final String sql, final String[] columnNames) {
return new CircuitBreakerPreparedStatement();
}
@Override
public Statement createStatement() {
return new CircuitBreakerStatement();
}
@Override
public Statement createStatement(final int resultSetType, final int resultSetConcurrency) {
return new CircuitBreakerStatement();
}
@Override
public Statement createStatement(final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) {
return new CircuitBreakerStatement();
}
@Override
public void close() {
}
@Override
public boolean isClosed() {
return false;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.datasource;
import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.connection.CircuitBreakerConnection;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.logging.Logger;
/**
* Circuit breaker datasource.
*
* @author caohao
*/
public final class CircuitBreakerDataSource extends AbstractUnsupportedOperationDataSource implements AutoCloseable {
@Override
public void close() {
}
@Override
public Connection getConnection() {
return new CircuitBreakerConnection();
}
@Override
public Connection getConnection(final String username, final String password) {
return new CircuitBreakerConnection();
}
@Override
public PrintWriter getLogWriter() {
return null;
}
@Override
public void setLogWriter(final PrintWriter out) {
}
@Override
public Logger getParentLogger() {
return null;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.resultset;
import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationResultSet;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
/**
* Circuit breaker result set.
*
* @author caohao
*/
public final class CircuitBreakerResultSet extends AbstractUnsupportedOperationResultSet {
@Override
public boolean next() {
return false;
}
@Override
public void close() {
}
@Override
public boolean wasNull() {
return true;
}
@Override
public String getString(final int columnIndex) {
return "";
}
@Override
public String getString(final String columnLabel) {
return "";
}
@Override
public boolean getBoolean(final int columnIndex) {
return false;
}
@Override
public boolean getBoolean(final String columnLabel) {
return false;
}
@Override
public byte getByte(final int columnIndex) {
return 0;
}
@Override
public byte getByte(final String columnLabel) {
return 0;
}
@Override
public short getShort(final int columnIndex) {
return 0;
}
@Override
public short getShort(final String columnLabel) {
return 0;
}
@Override
public int getInt(final int columnIndex) {
return 0;
}
@Override
public int getInt(final String columnLabel) {
return 0;
}
@Override
public long getLong(final int columnIndex) {
return 0;
}
@Override
public long getLong(final String columnLabel) {
return 0;
}
@Override
public float getFloat(final int columnIndex) {
return 0;
}
@Override
public float getFloat(final String columnLabel) {
return 0;
}
@Override
public double getDouble(final int columnIndex) {
return 0;
}
@Override
public double getDouble(final String columnLabel) {
return 0;
}
@Override
public byte[] getBytes(final int columnIndex) {
return new byte[0];
}
@Override
public byte[] getBytes(final String columnLabel) {
return new byte[0];
}
@Override
public Date getDate(final int columnIndex) {
return null;
}
@Override
public Date getDate(final String columnLabel) {
return null;
}
@Override
public Date getDate(final int columnIndex, final Calendar cal) {
return null;
}
@Override
public Date getDate(final String columnLabel, final Calendar cal) {
return null;
}
@Override
public Time getTime(final int columnIndex) {
return null;
}
@Override
public Time getTime(final String columnLabel) {
return null;
}
@Override
public Time getTime(final int columnIndex, final Calendar cal) {
return null;
}
@Override
public Time getTime(final String columnLabel, final Calendar cal) {
return null;
}
@Override
public Timestamp getTimestamp(final int columnIndex) {
return null;
}
@Override
public Timestamp getTimestamp(final String columnLabel) {
return null;
}
@Override
public Timestamp getTimestamp(final int columnIndex, final Calendar cal) {
return null;
}
@Override
public Timestamp getTimestamp(final String columnLabel, final Calendar cal) {
return null;
}
@Override
public InputStream getAsciiStream(final int columnIndex) {
return null;
}
@Override
public InputStream getAsciiStream(final String columnLabel) {
return null;
}
@SuppressWarnings("deprecation")
@Override
public InputStream getUnicodeStream(final int columnIndex) {
return null;
}
@SuppressWarnings("deprecation")
@Override
public InputStream getUnicodeStream(final String columnLabel) {
return null;
}
@Override
public InputStream getBinaryStream(final int columnIndex) {
return null;
}
@Override
public InputStream getBinaryStream(final String columnLabel) {
return null;
}
@Override
public SQLWarning getWarnings() {
return null;
}
@Override
public void clearWarnings() {
}
@Override
public ResultSetMetaData getMetaData() {
return new CircuitBreakerResultSetMetaData();
}
@Override
public Object getObject(final int columnIndex) {
return null;
}
@Override
public Object getObject(final String columnLabel) {
return null;
}
@Override
public int findColumn(final String columnLabel) {
return 0;
}
@Override
public Reader getCharacterStream(final int columnIndex) {
return null;
}
@Override
public Reader getCharacterStream(final String columnLabel) {
return null;
}
@Override
public BigDecimal getBigDecimal(final int columnIndex) {
return null;
}
@Override
public BigDecimal getBigDecimal(final String columnLabel) {
return null;
}
@SuppressWarnings("deprecation")
@Override
public BigDecimal getBigDecimal(final int columnIndex, final int scale) {
return null;
}
@SuppressWarnings("deprecation")
@Override
public BigDecimal getBigDecimal(final String columnLabel, final int scale) {
return null;
}
@Override
public void setFetchDirection(final int direction) {
}
@Override
public int getFetchDirection() {
return ResultSet.FETCH_FORWARD;
}
@Override
public void setFetchSize(final int rows) {
}
@Override
public int getFetchSize() {
return 0;
}
@Override
public int getType() {
return ResultSet.TYPE_FORWARD_ONLY;
}
@Override
public int getConcurrency() {
return ResultSet.CONCUR_READ_ONLY;
}
@Override
public Statement getStatement() {
return null;
}
@Override
public Blob getBlob(final int columnIndex) {
return null;
}
@Override
public Blob getBlob(final String columnLabel) {
return null;
}
@Override
public Clob getClob(final int columnIndex) {
return null;
}
@Override
public Clob getClob(final String columnLabel) {
return null;
}
@Override
public URL getURL(final int columnIndex) {
return null;
}
@Override
public URL getURL(final String columnLabel) {
return null;
}
@Override
public boolean isClosed() {
return false;
}
@Override
public SQLXML getSQLXML(final int columnIndex) {
return null;
}
@Override
public SQLXML getSQLXML(final String columnLabel) {
return null;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.resultset;
import java.sql.ResultSetMetaData;
/**
* Circuit breaker result set metadata.
*
* @author caohao
*/
public final class CircuitBreakerResultSetMetaData implements ResultSetMetaData {
@Override
public int getColumnCount() {
return 0;
}
@Override
public boolean isAutoIncrement(final int column) {
return false;
}
@Override
public boolean isCaseSensitive(final int column) {
return false;
}
@Override
public boolean isSearchable(final int column) {
return false;
}
@Override
public boolean isCurrency(final int column) {
return false;
}
@Override
public int isNullable(final int column) {
return ResultSetMetaData.columnNullable;
}
@Override
public boolean isSigned(final int column) {
return false;
}
@Override
public int getColumnDisplaySize(final int column) {
return 0;
}
@Override
public String getColumnLabel(final int column) {
return null;
}
@Override
public String getColumnName(final int column) {
return null;
}
@Override
public String getSchemaName(final int column) {
return null;
}
@Override
public int getPrecision(final int column) {
return 0;
}
@Override
public int getScale(final int column) {
return 0;
}
@Override
public String getTableName(final int column) {
return null;
}
@Override
public String getCatalogName(final int column) {
return null;
}
@Override
public int getColumnType(final int column) {
return 0;
}
@Override
public String getColumnTypeName(final int column) {
return null;
}
@Override
public boolean isReadOnly(final int column) {
return false;
}
@Override
public boolean isWritable(final int column) {
return false;
}
@Override
public boolean isDefinitelyWritable(final int column) {
return false;
}
@Override
public String getColumnClassName(final int column) {
return null;
}
@Override
public <T> T unwrap(final Class<T> iface) {
return null;
}
@Override
public boolean isWrapperFor(final Class<?> iface) {
return false;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.statement;
import lombok.Getter;
import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationPreparedStatement;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.connection.CircuitBreakerConnection;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.resultset.CircuitBreakerResultSet;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
/**
* Circuit breaker preparedStatement.
*
* @author caohao
*/
@Getter
public final class CircuitBreakerPreparedStatement extends AbstractUnsupportedOperationPreparedStatement {
@Override
public void setNull(final int parameterIndex, final int sqlType) {
}
@Override
public void setNull(final int parameterIndex, final int sqlType, final String typeName) {
}
@Override
public void setBoolean(final int parameterIndex, final boolean x) {
}
@Override
public void setByte(final int parameterIndex, final byte x) {
}
@Override
public void setShort(final int parameterIndex, final short x) {
}
@Override
public void setInt(final int parameterIndex, final int x) {
}
@Override
public void setLong(final int parameterIndex, final long x) {
}
@Override
public void setFloat(final int parameterIndex, final float x) {
}
@Override
public void setDouble(final int parameterIndex, final double x) {
}
@Override
public void setBigDecimal(final int parameterIndex, final BigDecimal x) {
}
@Override
public void setString(final int parameterIndex, final String x) {
}
@Override
public void setBytes(final int parameterIndex, final byte[] x) {
}
@Override
public void setDate(final int parameterIndex, final Date x) {
}
@Override
public void setDate(final int parameterIndex, final Date x, final Calendar cal) {
}
@Override
public void setTime(final int parameterIndex, final Time x) {
}
@Override
public void setTime(final int parameterIndex, final Time x, final Calendar cal) {
}
@Override
public void setTimestamp(final int parameterIndex, final Timestamp x) {
}
@Override
public void setTimestamp(final int parameterIndex, final Timestamp x, final Calendar cal) {
}
@Override
public void setAsciiStream(final int parameterIndex, final InputStream x, final int length) {
}
@Override
public void setAsciiStream(final int parameterIndex, final InputStream x) {
}
@Override
public void setAsciiStream(final int parameterIndex, final InputStream x, final long length) {
}
@SuppressWarnings("deprecation")
@Override
public void setUnicodeStream(final int parameterIndex, final InputStream x, final int length) {
}
@Override
public void setBinaryStream(final int parameterIndex, final InputStream x, final int length) {
}
@Override
public void setBinaryStream(final int parameterIndex, final InputStream x, final long length) {
}
@Override
public void setBinaryStream(final int parameterIndex, final InputStream x) {
}
@Override
public void clearParameters() {
}
@Override
public void setObject(final int parameterIndex, final Object x) {
}
@Override
public void setObject(final int parameterIndex, final Object x, final int targetSqlType) {
}
@Override
public void setObject(final int parameterIndex, final Object x, final int targetSqlType, final int scaleOrLength) {
}
@Override
public boolean execute() {
return false;
}
@Override
public void clearBatch() {
}
@Override
public void addBatch() {
}
@Override
public void setCharacterStream(final int parameterIndex, final Reader reader, final int length) {
}
@Override
public void setCharacterStream(final int parameterIndex, final Reader reader, final long length) {
}
@Override
public void setCharacterStream(final int parameterIndex, final Reader reader) {
}
@Override
public void setBlob(final int parameterIndex, final Blob x) {
}
@Override
public void setBlob(final int parameterIndex, final InputStream inputStream, final long length) {
}
@Override
public void setBlob(final int parameterIndex, final InputStream inputStream) {
}
@Override
public void setClob(final int parameterIndex, final Clob x) {
}
@Override
public void setClob(final int parameterIndex, final Reader reader, final long length) {
}
@Override
public void setClob(final int parameterIndex, final Reader reader) {
}
@Override
public void setURL(final int parameterIndex, final URL x) {
}
@Override
public void setSQLXML(final int parameterIndex, final SQLXML xmlObject) {
}
@Override
public int[] executeBatch() {
return new int[]{-1};
}
@Override
public Connection getConnection() {
return new CircuitBreakerConnection();
}
@Override
public ResultSet getGeneratedKeys() {
return new CircuitBreakerResultSet();
}
@Override
public int getResultSetHoldability() {
return 0;
}
@Override
public ResultSet getResultSet() {
return new CircuitBreakerResultSet();
}
@Override
public int getResultSetConcurrency() {
return ResultSet.CONCUR_READ_ONLY;
}
@Override
public int getResultSetType() {
return ResultSet.TYPE_FORWARD_ONLY;
}
@Override
protected boolean isAccumulate() {
return false;
}
@Override
protected Collection<? extends Statement> getRoutedStatements() {
return Collections.emptyList();
}
@Override
public ResultSet executeQuery() {
return new CircuitBreakerResultSet();
}
@Override
public int executeUpdate() {
return -1;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.statement;
import lombok.Getter;
import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationStatement;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.connection.CircuitBreakerConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLWarning;
/**
* Circuit breaker statement.
*
* @author caohao
*/
@Getter
public final class CircuitBreakerStatement extends AbstractUnsupportedOperationStatement {
@Override
public void close() {
}
@Override
public int getMaxFieldSize() {
return 0;
}
@Override
public void setMaxFieldSize(final int max) {
}
@Override
public int getMaxRows() {
return 0;
}
@Override
public void setMaxRows(final int max) {
}
@Override
public void setEscapeProcessing(final boolean enable) {
}
@Override
public int getQueryTimeout() {
return 0;
}
@Override
public void setQueryTimeout(final int seconds) {
}
@Override
public void cancel() {
}
@Override
public SQLWarning getWarnings() {
return null;
}
@Override
public void clearWarnings() {
}
@Override
public ResultSet getResultSet() {
return null;
}
@Override
public int getUpdateCount() {
return 0;
}
@Override
public void setFetchSize(final int rows) {
}
@Override
public int getFetchSize() {
return 0;
}
@Override
public int getResultSetConcurrency() {
return ResultSet.CONCUR_READ_ONLY;
}
@Override
public int getResultSetType() {
return ResultSet.TYPE_FORWARD_ONLY;
}
@Override
public Connection getConnection() {
return new CircuitBreakerConnection();
}
@Override
public boolean getMoreResults() {
return false;
}
@Override
public boolean getMoreResults(final int current) {
return false;
}
@Override
public ResultSet getGeneratedKeys() {
return null;
}
@Override
public ResultSet executeQuery(final String sql) {
return null;
}
@Override
public int executeUpdate(final String sql) {
return 0;
}
@Override
public int executeUpdate(final String sql, final int autoGeneratedKeys) {
return 0;
}
@Override
public int executeUpdate(final String sql, final int[] columnIndexes) {
return 0;
}
@Override
public int executeUpdate(final String sql, final String[] columnNames) {
return 0;
}
@Override
public boolean execute(final String sql) {
return false;
}
@Override
public boolean execute(final String sql, final int autoGeneratedKeys) {
return false;
}
@Override
public boolean execute(final String sql, final int[] columnIndexes) {
return false;
}
@Override
public boolean execute(final String sql, final String[] columnNames) {
return false;
}
@Override
public int getResultSetHoldability() {
return 0;
}
@Override
public boolean isClosed() {
return false;
}
@Override
public void setPoolable(final boolean poolable) {
}
@Override
public boolean isPoolable() {
return false;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;
import com.google.common.eventbus.Subscribe;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.api.config.RuleConfiguration;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import org.apache.shardingsphere.core.constant.ShardingConstant;
import org.apache.shardingsphere.orchestration.temp.internal.eventbus.ShardingOrchestrationEventBus;
import org.apache.shardingsphere.orchestration.temp.internal.registry.ShardingOrchestrationFacade;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.event.CircuitStateChangedEvent;
import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.AbstractDataSourceAdapter;
import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.datasource.CircuitBreakerDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util.DataSourceConverter;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Abstract orchestration data source.
*
* @author panjuan
*/
public abstract class AbstractOrchestrationDataSource extends AbstractUnsupportedOperationDataSource implements AutoCloseable {
@Getter
@Setter
private PrintWriter logWriter = new PrintWriter(System.out);
@Getter(AccessLevel.PROTECTED)
private final ShardingOrchestrationFacade shardingOrchestrationFacade;
private boolean isCircuitBreak;
@Getter(AccessLevel.PROTECTED)
private final Map<String, DataSourceConfiguration> dataSourceConfigurations = new LinkedHashMap<>();
public AbstractOrchestrationDataSource(final ShardingOrchestrationFacade shardingOrchestrationFacade) {
this.shardingOrchestrationFacade = shardingOrchestrationFacade;
ShardingOrchestrationEventBus.getInstance().register(this);
}
protected abstract DataSource getDataSource();
@Override
public final Connection getConnection() throws SQLException {
return isCircuitBreak ? new CircuitBreakerDataSource().getConnection() : getDataSource().getConnection();
}
@Override
public final Connection getConnection(final String username, final String password) throws SQLException {
return getConnection();
}
@Override
public final Logger getParentLogger() {
return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
}
@Override
public final void close() throws Exception {
((AbstractDataSourceAdapter) getDataSource()).close();
shardingOrchestrationFacade.close();
}
/**
/**
* Renew circuit breaker state.
*
* @param circuitStateChangedEvent circuit state changed event
*/
@Subscribe
public final synchronized void renew(final CircuitStateChangedEvent circuitStateChangedEvent) {
isCircuitBreak = circuitStateChangedEvent.isCircuitBreak();
}
protected final void initShardingOrchestrationFacade() {
shardingOrchestrationFacade.init();
dataSourceConfigurations.putAll(shardingOrchestrationFacade.getConfigService().loadDataSourceConfigurations(ShardingConstant.LOGIC_SCHEMA_NAME));
}
protected final void initShardingOrchestrationFacade(
final Map<String, Map<String, DataSourceConfiguration>> dataSourceConfigurations, final Map<String, RuleConfiguration> schemaRuleMap, final Properties props) {
shardingOrchestrationFacade.init(dataSourceConfigurations, schemaRuleMap, null, props);
this.dataSourceConfigurations.putAll(dataSourceConfigurations.get(ShardingConstant.LOGIC_SCHEMA_NAME));
}
protected final synchronized Map<String, DataSource> getChangedDataSources(final Map<String, DataSource> oldDataSources, final Map<String, DataSourceConfiguration> newDataSources) {
Map<String, DataSource> result = new LinkedHashMap<>(oldDataSources);
Map<String, DataSourceConfiguration> modifiedDataSources = getModifiedDataSources(newDataSources);
result.keySet().removeAll(getDeletedDataSources(newDataSources));
result.keySet().removeAll(modifiedDataSources.keySet());
result.putAll(DataSourceConverter.getDataSourceMap(modifiedDataSources));
result.putAll(DataSourceConverter.getDataSourceMap(getAddedDataSources(newDataSources)));
return result;
}
protected final synchronized Map<String, DataSourceConfiguration> getModifiedDataSources(final Map<String, DataSourceConfiguration> dataSourceConfigurations) {
Map<String, DataSourceConfiguration> result = new LinkedHashMap<>();
for (Entry<String, DataSourceConfiguration> entry : dataSourceConfigurations.entrySet()) {
if (isModifiedDataSource(entry)) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
private synchronized boolean isModifiedDataSource(final Entry<String, DataSourceConfiguration> dataSourceNameAndConfig) {
return dataSourceConfigurations.containsKey(dataSourceNameAndConfig.getKey()) && !dataSourceConfigurations.get(dataSourceNameAndConfig.getKey()).equals(dataSourceNameAndConfig.getValue());
}
protected final synchronized List<String> getDeletedDataSources(final Map<String, DataSourceConfiguration> dataSourceConfigurations) {
List<String> result = new LinkedList<>(this.dataSourceConfigurations.keySet());
result.removeAll(dataSourceConfigurations.keySet());
return result;
}
private synchronized Map<String, DataSourceConfiguration> getAddedDataSources(final Map<String, DataSourceConfiguration> dataSourceConfigurations) {
return Maps.filterEntries(dataSourceConfigurations, new Predicate<Entry<String, DataSourceConfiguration>>() {
@Override
public boolean apply(final Entry<String, DataSourceConfiguration> input) {
return !AbstractOrchestrationDataSource.this.dataSourceConfigurations.containsKey(input.getKey());
}
});
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource;
import com.google.common.base.Preconditions;
import com.google.common.eventbus.Subscribe;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.shardingsphere.api.config.RuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptRuleConfiguration;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import org.apache.shardingsphere.core.constant.ShardingConstant;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.temp.internal.registry.ShardingOrchestrationFacade;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.DataSourceChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.EncryptRuleChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.PropertiesChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.service.ConfigurationService;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.EncryptDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util.DataSourceConverter;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Orchestration encrypt data source.
*
* @author yangyi
*/
@Getter(AccessLevel.PROTECTED)
public class OrchestrationEncryptDataSource extends AbstractOrchestrationDataSource {
private static final String ENCRYPT_DATASOURCE = "dataSource";
private EncryptDataSource dataSource;
public OrchestrationEncryptDataSource(final OrchestrationConfiguration orchestrationConfig) throws SQLException {
super(new ShardingOrchestrationFacade(orchestrationConfig, Collections.singletonList(ShardingConstant.LOGIC_SCHEMA_NAME)));
ConfigurationService configService = getShardingOrchestrationFacade().getConfigService();
EncryptRuleConfiguration encryptRuleConfig = configService.loadEncryptRuleConfiguration(ShardingConstant.LOGIC_SCHEMA_NAME);
Preconditions.checkState(!encryptRuleConfig.getEncryptors().isEmpty(), "No available encrypt rule configuration to load.");
Map<String, DataSourceConfiguration> dataSourceConfigurations = configService.loadDataSourceConfigurations(ShardingConstant.LOGIC_SCHEMA_NAME);
checkDataSourceConfiguration(dataSourceConfigurations);
dataSource = new EncryptDataSource(
DataSourceConverter.getDataSourceMap(dataSourceConfigurations).values().iterator().next(), new EncryptRule(encryptRuleConfig), configService.loadProperties());
initShardingOrchestrationFacade();
}
public OrchestrationEncryptDataSource(final EncryptDataSource dataSource, final OrchestrationConfiguration orchestrationConfig) throws SQLException {
super(new ShardingOrchestrationFacade(orchestrationConfig, Collections.singletonList(ShardingConstant.LOGIC_SCHEMA_NAME)));
this.dataSource = new EncryptDataSource(
dataSource.getDataSource(), new EncryptRule(dataSource.getRuntimeContext().getRule().getRuleConfiguration()), dataSource.getRuntimeContext().getProps().getProps());
initShardingOrchestrationFacade(
Collections.singletonMap(ShardingConstant.LOGIC_SCHEMA_NAME, DataSourceConverter.getDataSourceConfigurationMap(Collections.singletonMap(ENCRYPT_DATASOURCE, dataSource.getDataSource()))),
getRuleConfigurationMap(), dataSource.getRuntimeContext().getProps().getProps());
}
private void checkDataSourceConfiguration(final Map<String, DataSourceConfiguration> dataSourceConfigurations) {
Preconditions.checkState(1 == dataSourceConfigurations.size(), String.format("There should be only one datasource for encrypt, but now has %d datasource(s)", dataSourceConfigurations.size()));
}
private Map<String, RuleConfiguration> getRuleConfigurationMap() {
Map<String, RuleConfiguration> result = new HashMap<>(1);
result.put(ShardingConstant.LOGIC_SCHEMA_NAME, dataSource.getRuntimeContext().getRule().getRuleConfiguration());
return result;
}
/**
* Renew encrypt data source.
*
* @param dataSourceChangedEvent data source changed event
*/
@Subscribe
@SneakyThrows
public final synchronized void renew(final DataSourceChangedEvent dataSourceChangedEvent) {
Map<String, DataSourceConfiguration> dataSourceConfigurations = dataSourceChangedEvent.getDataSourceConfigurations();
dataSource.close();
checkDataSourceConfiguration(dataSourceConfigurations);
dataSource = new EncryptDataSource(DataSourceConverter.getDataSourceMap(
dataSourceConfigurations).values().iterator().next(), dataSource.getRuntimeContext().getRule(), dataSource.getRuntimeContext().getProps().getProps());
getDataSourceConfigurations().clear();
getDataSourceConfigurations().putAll(dataSourceConfigurations);
}
/**
* Renew encrypt rule.
*
* @param encryptRuleChangedEvent encrypt configuration changed event
*/
@Subscribe
@SneakyThrows
public final synchronized void renew(final EncryptRuleChangedEvent encryptRuleChangedEvent) {
dataSource = new EncryptDataSource(
dataSource.getDataSource(), new EncryptRule(encryptRuleChangedEvent.getEncryptRuleConfiguration()), dataSource.getRuntimeContext().getProps().getProps());
}
/**
* Renew properties.
*
* @param propertiesChangedEvent properties changed event
*/
@SneakyThrows
@Subscribe
public final synchronized void renew(final PropertiesChangedEvent propertiesChangedEvent) {
dataSource = new EncryptDataSource(dataSource.getDataSource(), dataSource.getRuntimeContext().getRule(), propertiesChangedEvent.getProps());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.eventbus.Subscribe;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.shardingsphere.api.config.RuleConfiguration;
import org.apache.shardingsphere.api.config.masterslave.LoadBalanceStrategyConfiguration;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import org.apache.shardingsphere.core.constant.ShardingConstant;
import org.apache.shardingsphere.core.rule.MasterSlaveRule;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.temp.internal.registry.ShardingOrchestrationFacade;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.DataSourceChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.MasterSlaveRuleChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.PropertiesChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.service.ConfigurationService;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.event.DisabledStateChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.schema.OrchestrationShardingSchema;
import org.apache.shardingsphere.orchestration.temp.internal.rule.OrchestrationMasterSlaveRule;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.MasterSlaveDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util.DataSourceConverter;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Orchestration master-slave datasource.
*
* @author panjuan
*/
@Getter(AccessLevel.PROTECTED)
public class OrchestrationMasterSlaveDataSource extends AbstractOrchestrationDataSource {
private MasterSlaveDataSource dataSource;
public OrchestrationMasterSlaveDataSource(final OrchestrationConfiguration orchestrationConfig) throws SQLException {
super(new ShardingOrchestrationFacade(orchestrationConfig, Collections.singletonList(ShardingConstant.LOGIC_SCHEMA_NAME)));
ConfigurationService configService = getShardingOrchestrationFacade().getConfigService();
MasterSlaveRuleConfiguration masterSlaveRuleConfig = configService.loadMasterSlaveRuleConfiguration(ShardingConstant.LOGIC_SCHEMA_NAME);
Preconditions.checkState(!Strings.isNullOrEmpty(masterSlaveRuleConfig.getMasterDataSourceName()), "No available master slave rule configuration to load.");
dataSource = new MasterSlaveDataSource(DataSourceConverter.getDataSourceMap(configService.loadDataSourceConfigurations(ShardingConstant.LOGIC_SCHEMA_NAME)),
new OrchestrationMasterSlaveRule(masterSlaveRuleConfig), configService.loadProperties());
initShardingOrchestrationFacade();
}
public OrchestrationMasterSlaveDataSource(final MasterSlaveDataSource masterSlaveDataSource, final OrchestrationConfiguration orchestrationConfig) throws SQLException {
super(new ShardingOrchestrationFacade(orchestrationConfig, Collections.singletonList(ShardingConstant.LOGIC_SCHEMA_NAME)));
dataSource = new MasterSlaveDataSource(masterSlaveDataSource.getDataSourceMap(),
new OrchestrationMasterSlaveRule(masterSlaveDataSource.getRuntimeContext().getRule().getRuleConfiguration()),
masterSlaveDataSource.getRuntimeContext().getProps().getProps());
initShardingOrchestrationFacade(Collections.singletonMap(ShardingConstant.LOGIC_SCHEMA_NAME, DataSourceConverter.getDataSourceConfigurationMap(dataSource.getDataSourceMap())),
getRuleConfigurationMap(), dataSource.getRuntimeContext().getProps().getProps());
}
private Map<String, RuleConfiguration> getRuleConfigurationMap() {
MasterSlaveRule masterSlaveRule = dataSource.getRuntimeContext().getRule();
Map<String, RuleConfiguration> result = new HashMap<>();
result.put(ShardingConstant.LOGIC_SCHEMA_NAME, new MasterSlaveRuleConfiguration(
masterSlaveRule.getName(), masterSlaveRule.getMasterDataSourceName(), masterSlaveRule.getSlaveDataSourceNames(),
new LoadBalanceStrategyConfiguration(masterSlaveRule.getLoadBalanceAlgorithm().getType(), masterSlaveRule.getLoadBalanceAlgorithm().getProperties())));
return result;
}
/**
* Renew master-slave rule.
*
* @param masterSlaveRuleChangedEvent master-slave configuration changed event
*/
@Subscribe
@SneakyThrows
public final synchronized void renew(final MasterSlaveRuleChangedEvent masterSlaveRuleChangedEvent) {
dataSource = new MasterSlaveDataSource(dataSource.getDataSourceMap(),
new OrchestrationMasterSlaveRule(masterSlaveRuleChangedEvent.getMasterSlaveRuleConfiguration()), dataSource.getRuntimeContext().getProps().getProps());
}
/**
* Renew master-slave data source.
*
* @param dataSourceChangedEvent data source changed event
*/
@Subscribe
@SneakyThrows
public final synchronized void renew(final DataSourceChangedEvent dataSourceChangedEvent) {
Map<String, DataSourceConfiguration> dataSourceConfigurations = dataSourceChangedEvent.getDataSourceConfigurations();
dataSource.close(getDeletedDataSources(dataSourceConfigurations));
dataSource.close(getModifiedDataSources(dataSourceConfigurations).keySet());
dataSource = new MasterSlaveDataSource(getChangedDataSources(
dataSource.getDataSourceMap(), dataSourceConfigurations), dataSource.getRuntimeContext().getRule(), dataSource.getRuntimeContext().getProps().getProps());
getDataSourceConfigurations().clear();
getDataSourceConfigurations().putAll(dataSourceConfigurations);
}
/**
* Renew properties.
*
* @param propertiesChangedEvent properties changed event
*/
@SneakyThrows
@Subscribe
public final synchronized void renew(final PropertiesChangedEvent propertiesChangedEvent) {
dataSource = new MasterSlaveDataSource(dataSource.getDataSourceMap(), dataSource.getRuntimeContext().getRule(), propertiesChangedEvent.getProps());
}
/**
* Renew disabled data source names.
*
* @param disabledStateChangedEvent disabled state changed event
*/
@Subscribe
public synchronized void renew(final DisabledStateChangedEvent disabledStateChangedEvent) {
OrchestrationShardingSchema shardingSchema = disabledStateChangedEvent.getShardingSchema();
if (ShardingConstant.LOGIC_SCHEMA_NAME.equals(shardingSchema.getSchemaName())) {
((OrchestrationMasterSlaveRule) dataSource.getRuntimeContext().getRule()).updateDisabledDataSourceNames(
shardingSchema.getDataSourceName(), disabledStateChangedEvent.isDisabled());
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource;
import com.google.common.base.Preconditions;
import com.google.common.eventbus.Subscribe;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.shardingsphere.api.config.RuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import org.apache.shardingsphere.core.constant.ShardingConstant;
import org.apache.shardingsphere.core.rule.MasterSlaveRule;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.temp.internal.registry.ShardingOrchestrationFacade;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.DataSourceChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.PropertiesChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.ShardingRuleChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.service.ConfigurationService;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.event.DisabledStateChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.schema.OrchestrationShardingSchema;
import org.apache.shardingsphere.orchestration.temp.internal.rule.OrchestrationMasterSlaveRule;
import org.apache.shardingsphere.orchestration.temp.internal.rule.OrchestrationShardingRule;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util.DataSourceConverter;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Orchestration sharding datasource.
*
* @author panjuan
*/
@Getter(AccessLevel.PROTECTED)
public class OrchestrationShardingDataSource extends AbstractOrchestrationDataSource {
private ShardingDataSource dataSource;
public OrchestrationShardingDataSource(final OrchestrationConfiguration orchestrationConfig) throws SQLException {
super(new ShardingOrchestrationFacade(orchestrationConfig, Collections.singletonList(ShardingConstant.LOGIC_SCHEMA_NAME)));
ConfigurationService configService = getShardingOrchestrationFacade().getConfigService();
ShardingRuleConfiguration shardingRuleConfig = configService.loadShardingRuleConfiguration(ShardingConstant.LOGIC_SCHEMA_NAME);
Preconditions.checkState(null != shardingRuleConfig && !shardingRuleConfig.getTableRuleConfigs().isEmpty(), "Missing the sharding rule configuration on registry center");
dataSource = new ShardingDataSource(DataSourceConverter.getDataSourceMap(configService.loadDataSourceConfigurations(ShardingConstant.LOGIC_SCHEMA_NAME)),
new OrchestrationShardingRule(shardingRuleConfig, configService.loadDataSourceConfigurations(ShardingConstant.LOGIC_SCHEMA_NAME).keySet()), configService.loadProperties());
initShardingOrchestrationFacade();
}
public OrchestrationShardingDataSource(final ShardingDataSource shardingDataSource, final OrchestrationConfiguration orchestrationConfig) throws SQLException {
super(new ShardingOrchestrationFacade(orchestrationConfig, Collections.singletonList(ShardingConstant.LOGIC_SCHEMA_NAME)));
dataSource = new ShardingDataSource(shardingDataSource.getDataSourceMap(), new OrchestrationShardingRule(shardingDataSource.getRuntimeContext().getRule().getRuleConfiguration(),
shardingDataSource.getDataSourceMap().keySet()), shardingDataSource.getRuntimeContext().getProps().getProps());
initShardingOrchestrationFacade(Collections.singletonMap(ShardingConstant.LOGIC_SCHEMA_NAME, DataSourceConverter.getDataSourceConfigurationMap(dataSource.getDataSourceMap())),
getRuleConfigurationMap(), dataSource.getRuntimeContext().getProps().getProps());
}
private Map<String, RuleConfiguration> getRuleConfigurationMap() {
Map<String, RuleConfiguration> result = new LinkedHashMap<>(1, 1);
result.put(ShardingConstant.LOGIC_SCHEMA_NAME, dataSource.getRuntimeContext().getRule().getRuleConfiguration());
return result;
}
/**
* Renew sharding rule.
*
* @param shardingRuleChangedEvent sharding rule changed event
*/
@Subscribe
@SneakyThrows
public final synchronized void renew(final ShardingRuleChangedEvent shardingRuleChangedEvent) {
dataSource = new ShardingDataSource(dataSource.getDataSourceMap(), new OrchestrationShardingRule(shardingRuleChangedEvent.getShardingRuleConfiguration(),
dataSource.getDataSourceMap().keySet()), dataSource.getRuntimeContext().getProps().getProps());
}
/**
* Renew sharding data source.
*
* @param dataSourceChangedEvent data source changed event
*/
@Subscribe
@SneakyThrows
public final synchronized void renew(final DataSourceChangedEvent dataSourceChangedEvent) {
Map<String, DataSourceConfiguration> dataSourceConfigurations = dataSourceChangedEvent.getDataSourceConfigurations();
dataSource.close(getDeletedDataSources(dataSourceConfigurations));
dataSource.close(getModifiedDataSources(dataSourceConfigurations).keySet());
dataSource = new ShardingDataSource(getChangedDataSources(dataSource.getDataSourceMap(), dataSourceConfigurations),
dataSource.getRuntimeContext().getRule(), dataSource.getRuntimeContext().getProps().getProps());
getDataSourceConfigurations().clear();
getDataSourceConfigurations().putAll(dataSourceConfigurations);
}
/**
* Renew properties.
*
* @param propertiesChangedEvent properties changed event
*/
@SneakyThrows
@Subscribe
public final synchronized void renew(final PropertiesChangedEvent propertiesChangedEvent) {
dataSource = new ShardingDataSource(dataSource.getDataSourceMap(), dataSource.getRuntimeContext().getRule(), propertiesChangedEvent.getProps());
}
/**
* Renew disabled data source names.
*
* @param disabledStateChangedEvent disabled state changed event
*/
@Subscribe
public synchronized void renew(final DisabledStateChangedEvent disabledStateChangedEvent) {
OrchestrationShardingSchema shardingSchema = disabledStateChangedEvent.getShardingSchema();
if (ShardingConstant.LOGIC_SCHEMA_NAME.equals(shardingSchema.getSchemaName())) {
for (MasterSlaveRule each : dataSource.getRuntimeContext().getRule().getMasterSlaveRules()) {
((OrchestrationMasterSlaveRule) each).updateDisabledDataSourceNames(shardingSchema.getDataSourceName(), disabledStateChangedEvent.isDisabled());
}
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import javax.sql.DataSource;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Data source converter.
*
* @author panjuan
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DataSourceConverter {
/**
* Get data source map.
*
* @param dataSourceConfigurationMap data source configuration map
* @return data source map
*/
public static Map<String, DataSource> getDataSourceMap(final Map<String, DataSourceConfiguration> dataSourceConfigurationMap) {
Map<String, DataSource> result = new LinkedHashMap<>(dataSourceConfigurationMap.size(), 1);
for (Entry<String, DataSourceConfiguration> entry : dataSourceConfigurationMap.entrySet()) {
result.put(entry.getKey(), entry.getValue().createDataSource());
}
return result;
}
/**
* Get data source configuration map.
*
* @param dataSourceMap data source map
* @return data source configuration map
*/
public static Map<String, DataSourceConfiguration> getDataSourceConfigurationMap(final Map<String, DataSource> dataSourceMap) {
Map<String, DataSourceConfiguration> result = new LinkedHashMap<>(dataSourceMap.size(), 1);
for (Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
result.put(entry.getKey(), DataSourceConfiguration.getDataSourceConfiguration(entry.getValue()));
}
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.shardingsphere.orchestration.center.configuration.InstanceConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.config.YamlInstanceConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.swapper.InstanceConfigurationYamlSwapper;
/**
* YamlInstanceConfiguration swapper util.
*
* @author sunbufu
*/
public class YamlInstanceConfigurationSwapperUtil {
private static final InstanceConfigurationYamlSwapper INSTANCE_SWAPPER = new InstanceConfigurationYamlSwapper();
/**
* marshal YamlInstanceConfiguration map to InstanceConfiguration map.
*
* @param yamlInstanceConfigurationMap YamlInstanceConfiguration map
* @return InstanceConfiguration map
*/
public static Map<String, InstanceConfiguration> marshal(final Map<String, YamlInstanceConfiguration> yamlInstanceConfigurationMap) {
Map<String, InstanceConfiguration> result = new LinkedHashMap<>(yamlInstanceConfigurationMap.size(), 1);
for (Map.Entry<String, YamlInstanceConfiguration> each : yamlInstanceConfigurationMap.entrySet()) {
result.put(each.getKey(), INSTANCE_SWAPPER.swap(each.getValue()));
}
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.yaml;
import java.util.Map;
import java.util.Properties;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.core.yaml.config.encrypt.YamlRootEncryptRuleConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.config.YamlInstanceConfiguration;
/**
* Orchestration encrypt configuration for YAML.
*
* @author yangyi
*/
@Getter
@Setter
public final class YamlOrchestrationEncryptRuleConfiguration extends YamlRootEncryptRuleConfiguration {
private Map<String, YamlInstanceConfiguration> orchestration;
private Properties props = new Properties();
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.yaml;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.core.yaml.config.masterslave.YamlRootMasterSlaveConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.config.YamlInstanceConfiguration;
/**
* Orchestration master-slave configuration for YAML.
*
* @author caohao
*/
@Getter
@Setter
public final class YamlOrchestrationMasterSlaveRuleConfiguration extends YamlRootMasterSlaveConfiguration {
private Map<String, YamlInstanceConfiguration> orchestration;
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.yaml;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.core.yaml.config.sharding.YamlRootShardingConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.config.YamlInstanceConfiguration;
/**
* Orchestration sharding configuration for YAML.
*
* @author caohao
*/
@Getter
@Setter
public final class YamlOrchestrationShardingRuleConfiguration extends YamlRootShardingConfiguration {
private Map<String, YamlInstanceConfiguration> orchestration;
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api;
import java.util.Collections;
import java.util.Map;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.shardingsphere.api.config.encrypt.EncryptRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptorRuleConfiguration;
import org.apache.shardingsphere.orchestration.center.configuration.InstanceConfiguration;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.temp.constant.OrchestrationType;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationEncryptDataSource;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
public final class OrchestrationEncryptDataSourceFactoryTest {
@Test
public void assertCreateDataSourceWithDataSource() throws SQLException {
DataSource dataSource = OrchestrationEncryptDataSourceFactory.createDataSource(getDataSource(), getEncryptRuleConfiguration(), new Properties(), getOrchestrationConfiguration());
assertThat(dataSource, instanceOf(OrchestrationEncryptDataSource.class));
}
@Test
public void assertCreateDataSourceWithoutDataSource() throws SQLException {
DataSource dataSource = OrchestrationEncryptDataSourceFactory.createDataSource(getOrchestrationConfiguration());
assertThat(dataSource, instanceOf(OrchestrationEncryptDataSource.class));
}
@Test
public void assertCreateDataSourceWithEmptyRule() throws SQLException {
DataSource dataSource = OrchestrationEncryptDataSourceFactory.createDataSource(null, null, null, getOrchestrationConfiguration());
assertThat(dataSource, instanceOf(OrchestrationEncryptDataSource.class));
}
private DataSource getDataSource() {
BasicDataSource result = new BasicDataSource();
result.setDriverClassName("org.h2.Driver");
result.setUrl("jdbc:h2:mem:ds_encrypt;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL");
result.setUsername("sa");
result.setPassword("");
return result;
}
private EncryptRuleConfiguration getEncryptRuleConfiguration() {
EncryptRuleConfiguration result = new EncryptRuleConfiguration();
Properties properties = new Properties();
properties.setProperty("aes.key.value", "123456");
EncryptorRuleConfiguration encryptorRuleConfig = new EncryptorRuleConfiguration("aes", properties);
result.getEncryptors().put("order_encryptor", encryptorRuleConfig);
return result;
}
private OrchestrationConfiguration getOrchestrationConfiguration() {
InstanceConfiguration instanceConfiguration = new InstanceConfiguration("TestRegistryCenter");
String orchestrationType = OrchestrationType.REGISTRY_CENTER.getValue() + "," + OrchestrationType.CONFIG_CENTER.getValue();
instanceConfiguration.setOrchestrationType(orchestrationType);
instanceConfiguration.setNamespace("test_ms");
instanceConfiguration.setServerLists("localhost:3181");
Map<String, InstanceConfiguration> instanceConfigurationMap = Collections.singletonMap("test", instanceConfiguration);
return new OrchestrationConfiguration(instanceConfigurationMap);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml;
import org.apache.commons.dbcp2.BasicDataSource;
import org.h2.tools.RunScript;
import org.junit.BeforeClass;
import javax.sql.DataSource;
import java.io.File;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
public abstract class AbstractYamlDataSourceTest {
@BeforeClass
public static void createSchema() throws SQLException {
for (String each : getSchemaFiles()) {
RunScript.execute(createDataSource(getFileName(each)).getConnection(), new InputStreamReader(AbstractYamlDataSourceTest.class.getClassLoader().getResourceAsStream(each)));
}
}
protected static DataSource createDataSource(final String dsName) {
BasicDataSource result = new BasicDataSource();
result.setDriverClassName(org.h2.Driver.class.getName());
result.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL", dsName));
result.setUsername("sa");
result.setMaxTotal(100);
return result;
}
private static String getFileName(final String dataSetFile) {
String fileName = new File(dataSetFile).getName();
if (-1 == fileName.lastIndexOf(".")) {
return fileName;
}
return fileName.substring(0, fileName.lastIndexOf("."));
}
private static List<String> getSchemaFiles() {
return Arrays.asList("yaml/schema/sharding/db0.sql", "yaml/schema/sharding/db1.sql",
"yaml/schema/ms/db_master.sql", "yaml/schema/ms/db_slave_0.sql", "yaml/schema/ms/db_slave_1.sql",
"yaml/schema/sharding_ms/db0_master.sql", "yaml/schema/sharding_ms/db1_master.sql",
"yaml/schema/sharding_ms/db0_slave.sql", "yaml/schema/sharding_ms/db1_slave.sql");
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml;
import lombok.SneakyThrows;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationEncryptDataSource;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.sql.SQLException;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
public final class YamlOrchestrationEncryptDataSourceFactoryTest {
@Test
public void assertCreateDataSourceByYamlFile() throws URISyntaxException, IOException, SQLException {
File yamlFile = new File(OrchestrationEncryptDataSource.class.getResource("/yaml/unit/encryptWithRegistryCenter.yaml").toURI());
DataSource dataSource = YamlOrchestrationEncryptDataSourceFactory.createDataSource(yamlFile);
assertThat(dataSource, instanceOf(OrchestrationEncryptDataSource.class));
}
@Test
public void assertCreateDataSourceByYamlFileWithDataSource() throws URISyntaxException, IOException, SQLException {
File yamlFile = new File(OrchestrationEncryptDataSource.class.getResource("/yaml/unit/encryptWithRegistryCenter.yaml").toURI());
DataSource dataSource = YamlOrchestrationEncryptDataSourceFactory.createDataSource(getDataSource(), yamlFile);
assertThat(dataSource, instanceOf(OrchestrationEncryptDataSource.class));
}
@Test
public void assertCreateDataSourceByYamlFileWithoutRule() throws URISyntaxException, IOException, SQLException {
File yamlFile = new File(OrchestrationEncryptDataSource.class.getResource("/yaml/unit/noRule.yaml").toURI());
DataSource dataSource = YamlOrchestrationEncryptDataSourceFactory.createDataSource(getDataSource(), yamlFile);
assertThat(dataSource, instanceOf(OrchestrationEncryptDataSource.class));
}
@Test
public void assertCreateDataSourceByYamlBytes() throws IOException, SQLException {
DataSource dataSource = YamlOrchestrationEncryptDataSourceFactory.createDataSource(readBytesFromYamlFile());
assertThat(dataSource, instanceOf(OrchestrationEncryptDataSource.class));
}
@Test
public void assertCreateDataSourceByYamlBytesWithDataSource() throws IOException, SQLException {
DataSource dataSource = YamlOrchestrationEncryptDataSourceFactory.createDataSource(getDataSource(), readBytesFromYamlFile());
assertThat(dataSource, instanceOf(OrchestrationEncryptDataSource.class));
}
@SneakyThrows
private byte[] readBytesFromYamlFile() {
File yamlFile = new File(OrchestrationEncryptDataSource.class.getResource("/yaml/unit/encryptWithRegistryCenter.yaml").toURI());
byte[] result = new byte[(int) yamlFile.length()];
try (InputStream inputStream = new FileInputStream(yamlFile)) {
inputStream.read(result);
}
return result;
}
private DataSource getDataSource() {
BasicDataSource result = new BasicDataSource();
result.setDriverClassName("org.h2.Driver");
result.setUrl("jdbc:h2:mem:ds_encrypt;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL");
result.setUsername("sa");
result.setPassword("");
return result;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class DecrementShardingKeyGenerator implements ShardingKeyGenerator {
@Getter
private final String type = "DECREMENT";
private final AtomicInteger sequence = new AtomicInteger(100);
@Getter
@Setter
private Properties properties = new Properties();
@Override
public Comparable<?> generateKey() {
return sequence.decrementAndGet();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class IncrementShardingKeyGenerator implements ShardingKeyGenerator {
private static final AtomicInteger SEQUENCE = new AtomicInteger(100);
@Getter
private final String type = "INCREMENT";
@Getter
@Setter
private Properties properties = new Properties();
@Override
public Comparable<?> generateKey() {
return SEQUENCE.incrementAndGet();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.fixture;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import java.util.Collection;
public final class MultiAlgorithm implements ComplexKeysShardingAlgorithm<String> {
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final ComplexKeysShardingValue<String> shardingValue) {
return null;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.fixture;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import java.util.Collection;
public final class SingleAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Integer> shardingValue) {
for (String each : availableTargetNames) {
if (each.endsWith(shardingValue.getValue() % 10 + "")) {
return each;
}
}
throw new UnsupportedOperationException();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.masterslave;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.AbstractYamlDataSourceTest;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.YamlOrchestrationMasterSlaveDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationMasterSlaveDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
@RequiredArgsConstructor
public class YamlOrchestrationMasterSlaveIntegrateTest extends AbstractYamlDataSourceTest {
private final String filePath;
private final boolean hasDataSource;
@Parameters(name = "{index}:{0}-{1}")
public static Collection init() {
return Arrays.asList(new Object[][]{
{"/yaml/integrate/ms/configWithMasterSlaveDataSourceWithoutProps.yaml", true},
{"/yaml/integrate/ms/configWithMasterSlaveDataSourceWithoutProps.yaml", false},
{"/yaml/integrate/ms/configWithMasterSlaveDataSourceWithProps.yaml", true},
{"/yaml/integrate/ms/configWithMasterSlaveDataSourceWithProps.yaml", false},
});
}
@Test
public void assertWithDataSource() throws Exception {
File yamlFile = new File(YamlOrchestrationMasterSlaveIntegrateTest.class.getResource(filePath).toURI());
DataSource dataSource;
if (hasDataSource) {
dataSource = YamlOrchestrationMasterSlaveDataSourceFactory.createDataSource(yamlFile);
} else {
dataSource = YamlOrchestrationMasterSlaveDataSourceFactory.createDataSource(Maps.asMap(Sets.newHashSet("db_master", "db_slave_0", "db_slave_1"), new Function<String, DataSource>() {
@Override
public DataSource apply(final String key) {
return AbstractYamlDataSourceTest.createDataSource(key);
}
}), yamlFile);
}
try (Connection conn = dataSource.getConnection();
Statement stm = conn.createStatement()) {
stm.executeQuery("SELECT * FROM t_order");
stm.executeQuery("SELECT * FROM t_order_item");
stm.executeQuery("SELECT * FROM t_config");
}
((OrchestrationMasterSlaveDataSource) dataSource).close();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.sharding;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.AbstractYamlDataSourceTest;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.YamlOrchestrationShardingDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationShardingDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
@RequiredArgsConstructor
public class YamlOrchestrationShardingIntegrateTest extends AbstractYamlDataSourceTest {
private final String filePath;
private final boolean hasDataSource;
@Parameters(name = "{index}:{0}-{1}")
public static Collection init() {
return Arrays.asList(new Object[][]{
{"/yaml/integrate/sharding/configWithDataSourceWithoutProps.yaml", true},
{"/yaml/integrate/sharding/configWithoutDataSourceWithoutProps.yaml", false},
{"/yaml/integrate/sharding/configWithDataSourceWithProps.yaml", true},
{"/yaml/integrate/sharding/configWithoutDataSourceWithProps.yaml", false},
});
}
@Test
public void assertWithDataSource() throws Exception {
File yamlFile = new File(YamlOrchestrationShardingIntegrateTest.class.getResource(filePath).toURI());
DataSource dataSource;
if (hasDataSource) {
dataSource = YamlOrchestrationShardingDataSourceFactory.createDataSource(yamlFile);
} else {
dataSource = YamlOrchestrationShardingDataSourceFactory.createDataSource(Maps.asMap(Sets.newHashSet("db0", "db1"), new Function<String, DataSource>() {
@Override
public DataSource apply(final String key) {
return AbstractYamlDataSourceTest.createDataSource(key);
}
}), yamlFile);
}
try (Connection conn = dataSource.getConnection();
Statement stm = conn.createStatement()) {
stm.execute(String.format("INSERT INTO t_order(user_id,status) values(%d, %s)", 10, "'insert'"));
stm.executeQuery("SELECT * FROM t_order");
stm.executeQuery("SELECT * FROM t_order_item");
stm.executeQuery("SELECT * FROM config");
}
((OrchestrationShardingDataSource) dataSource).close();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.sharding;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.AbstractYamlDataSourceTest;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.api.yaml.YamlOrchestrationShardingDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource.OrchestrationShardingDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
@RunWith(Parameterized.class)
@RequiredArgsConstructor
public class YamlOrchestrationShardingWithMasterSlaveIntegrateTest extends AbstractYamlDataSourceTest {
private final String filePath;
private final boolean hasDataSource;
@Parameters(name = "{index}:{0}-{1}")
public static Collection init() {
return Arrays.asList(new Object[][]{
{"/yaml/integrate/sharding_ms/configWithDataSourceWithoutProps.yaml", true},
{"/yaml/integrate/sharding_ms/configWithoutDataSourceWithoutProps.yaml", false},
{"/yaml/integrate/sharding_ms/configWithDataSourceWithProps.yaml", true},
{"/yaml/integrate/sharding_ms/configWithoutDataSourceWithProps.yaml", false},
});
}
@Test
public void assertWithDataSource() throws Exception {
File yamlFile = new File(YamlOrchestrationShardingWithMasterSlaveIntegrateTest.class.getResource(filePath).toURI());
DataSource dataSource;
if (hasDataSource) {
dataSource = YamlOrchestrationShardingDataSourceFactory.createDataSource(yamlFile);
} else {
Map<String, DataSource> dataSourceMap = Maps.asMap(Sets.newHashSet("db0_master", "db0_slave", "db1_master", "db1_slave"), new Function<String, DataSource>() {
@Override
public DataSource apply(final String key) {
return AbstractYamlDataSourceTest.createDataSource(key);
}
});
Map<String, DataSource> result = new HashMap<>();
for (Entry<String, DataSource> each : dataSourceMap.entrySet()) {
result.put(each.getKey(), each.getValue());
}
dataSource = YamlOrchestrationShardingDataSourceFactory.createDataSource(result, yamlFile);
}
try (Connection conn = dataSource.getConnection();
Statement stm = conn.createStatement()) {
stm.execute(String.format("INSERT INTO t_order(user_id,status) values(%d, %s)", 10, "'insert'"));
stm.executeQuery("SELECT * FROM t_order");
stm.executeQuery("SELECT * FROM t_order_item");
stm.executeQuery("SELECT * FROM config");
}
((OrchestrationShardingDataSource) dataSource).close();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.connection;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.metadata.CircuitBreakerDatabaseMetaData;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.statement.CircuitBreakerPreparedStatement;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.statement.CircuitBreakerStatement;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public final class CircuitBreakerConnectionTest {
private final CircuitBreakerConnection connection = new CircuitBreakerConnection();
private final String sql = "select 1";
@Test
public void assertGetMetaData() {
assertTrue(connection.getMetaData() instanceof CircuitBreakerDatabaseMetaData);
}
@Test
public void setReadOnly() {
connection.setReadOnly(true);
assertFalse(connection.isReadOnly());
}
@Test
public void assertIsReadOnly() {
assertFalse(connection.isReadOnly());
}
@Test
public void assertSetTransactionIsolation() {
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
assertThat(connection.getTransactionIsolation(), is(Connection.TRANSACTION_NONE));
}
@Test
public void assertGetTransactionIsolation() {
assertThat(connection.getTransactionIsolation(), is(Connection.TRANSACTION_NONE));
}
@Test
public void assertGetWarnings() {
assertNull(connection.getWarnings());
}
@Test
public void assertClearWarnings() {
connection.clearWarnings();
}
@Test
public void assertSetAutoCommit() {
connection.setAutoCommit(true);
assertFalse(connection.getAutoCommit());
}
@Test
public void assertGetAutoCommit() {
assertFalse(connection.getAutoCommit());
}
@Test
public void assertCommit() {
connection.commit();
}
@Test
public void assertRollback() {
connection.rollback();
}
@Test
public void assertSetHoldability() {
connection.setHoldability(-1);
assertThat(connection.getHoldability(), is(0));
}
@Test
public void assertGetHoldability() {
assertThat(connection.getHoldability(), is(0));
}
@Test
public void assertPrepareStatement() {
assertTrue(connection.prepareStatement(sql) instanceof CircuitBreakerPreparedStatement);
assertTrue(connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) instanceof CircuitBreakerPreparedStatement);
assertTrue(connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT) instanceof CircuitBreakerPreparedStatement);
assertTrue(connection.prepareStatement(sql, Statement.NO_GENERATED_KEYS) instanceof CircuitBreakerPreparedStatement);
assertTrue(connection.prepareStatement(sql, new int[]{0}) instanceof CircuitBreakerPreparedStatement);
assertTrue(connection.prepareStatement(sql, new String[]{""}) instanceof CircuitBreakerPreparedStatement);
}
@Test
public void assertCreateStatement() {
assertTrue(connection.createStatement() instanceof CircuitBreakerStatement);
assertTrue(connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) instanceof CircuitBreakerStatement);
assertTrue(connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT) instanceof CircuitBreakerStatement);
}
@Test
public void assertClose() {
connection.close();
}
@Test
public void assertIsClosed() {
assertFalse(connection.isClosed());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.datasource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.connection.CircuitBreakerConnection;
import org.junit.Test;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public final class CircuitBreakerDataSourceTest {
private final CircuitBreakerDataSource dataSource = new CircuitBreakerDataSource();
@Test
public void assertClose() {
dataSource.close();
}
@Test
public void assertGetConnection() {
assertTrue(dataSource.getConnection() instanceof CircuitBreakerConnection);
assertTrue(dataSource.getConnection("", "") instanceof CircuitBreakerConnection);
}
@Test
public void assertGetLogWriter() {
assertNull(dataSource.getLogWriter());
}
@Test
public void assertSetLogWriter() {
dataSource.setLogWriter(null);
assertNull(dataSource.getLogWriter());
}
@Test
public void assertGetParentLogger() {
assertNull(dataSource.getParentLogger());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource;
import com.google.common.base.Optional;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.shardingsphere.api.config.encrypt.EncryptColumnRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptTableRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptorRuleConfiguration;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import org.apache.shardingsphere.core.constant.ShardingConstant;
import org.apache.shardingsphere.orchestration.center.configuration.InstanceConfiguration;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.temp.constant.OrchestrationType;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.DataSourceChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.EncryptRuleChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.PropertiesChangedEvent;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlEncryptDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.connection.EncryptConnection;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.EncryptDataSource;
import org.junit.Before;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.File;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public final class OrchestrationEncryptDataSourceTest {
private OrchestrationEncryptDataSource encryptDataSource;
@Before
public void setUp() throws Exception {
encryptDataSource = new OrchestrationEncryptDataSource(getEncryptDatasource(), getOrchestrationConfiguration());
}
private EncryptDataSource getEncryptDatasource() throws URISyntaxException {
File yamlFile = new File(OrchestrationEncryptDataSource.class.getResource("/yaml/unit/encrypt.yaml").toURI());
return (EncryptDataSource) YamlEncryptDataSourceFactory.createDataSource(yamlFile);
}
private OrchestrationConfiguration getOrchestrationConfiguration() {
InstanceConfiguration instanceConfiguration = new InstanceConfiguration("TestRegistryCenter");
String orchestrationType = OrchestrationType.REGISTRY_CENTER.getValue() + "," + OrchestrationType.CONFIG_CENTER.getValue();
instanceConfiguration.setOrchestrationType(orchestrationType);
instanceConfiguration.setNamespace("test_encrypt");
instanceConfiguration.setServerLists("localhost:3181");
Map<String, InstanceConfiguration> instanceConfigurationMap = Collections.singletonMap("test", instanceConfiguration);
return new OrchestrationConfiguration(instanceConfigurationMap);
}
@Test
public void assertInitializeOrchestrationEncryptDataSource() throws SQLException {
DataSource dataSource = new OrchestrationEncryptDataSource(getOrchestrationConfiguration());
assertThat(dataSource.getConnection(), instanceOf(EncryptConnection.class));
}
@Test
public void assertRenewRule() {
encryptDataSource.renew(getEncryptRuleChangedEvent());
assertThat(encryptDataSource.getDataSource().getRuntimeContext().getRule().getEncryptTableNames().size(), is(1));
assertThat(encryptDataSource.getDataSource().getRuntimeContext().getRule().getEncryptTableNames().iterator().next(), is("t_order_item"));
assertThat(encryptDataSource.getDataSource().getRuntimeContext().getRule().getCipherColumn("t_order_item", "item_id"), is("cipher_item_id"));
assertThat(encryptDataSource.getDataSource().getRuntimeContext().getRule().findPlainColumn("t_order_item", "item_id"), is(Optional.of("plain_item_id")));
Map<String, EncryptorRuleConfiguration> encryptorRuleConfigurations = encryptDataSource.getDataSource().getRuntimeContext().getRule().getRuleConfiguration().getEncryptors();
assertThat(encryptorRuleConfigurations.size(), is(1));
assertTrue(encryptorRuleConfigurations.containsKey("order_encryptor"));
EncryptorRuleConfiguration encryptorRuleConfig = encryptorRuleConfigurations.get("order_encryptor");
assertThat(encryptorRuleConfig.getType(), is("md5"));
assertThat(encryptorRuleConfig.getProperties().stringPropertyNames().size(), is(0));
}
private EncryptRuleChangedEvent getEncryptRuleChangedEvent() {
EncryptRuleConfiguration encryptRuleConfig = new EncryptRuleConfiguration();
encryptRuleConfig.getEncryptors().put("order_encryptor", new EncryptorRuleConfiguration("md5", new Properties()));
encryptRuleConfig.getTables().put("t_order_item",
new EncryptTableRuleConfiguration(Collections.singletonMap("item_id", new EncryptColumnRuleConfiguration("plain_item_id", "cipher_item_id", "", "order_encryptor"))));
return new EncryptRuleChangedEvent(ShardingConstant.LOGIC_SCHEMA_NAME, encryptRuleConfig);
}
@Test
public void assertRenewDataSource() throws SQLException {
assertThat(encryptDataSource.getConnection().getMetaData().getURL(), is("jdbc:h2:mem:ds_encrypt"));
encryptDataSource.renew(new DataSourceChangedEvent(ShardingConstant.LOGIC_SCHEMA_NAME, getDataSourceConfigurations()));
assertThat(encryptDataSource.getConnection().getMetaData().getURL(), is("jdbc:h2:mem:test"));
}
private Map<String, DataSourceConfiguration> getDataSourceConfigurations() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
dataSource.setUsername("sa");
dataSource.setPassword("");
return Collections.singletonMap("ds_test", DataSourceConfiguration.getDataSourceConfiguration(dataSource));
}
@Test
public void assertRenewDataSourceWithError() {
try {
encryptDataSource.renew(new DataSourceChangedEvent(ShardingConstant.LOGIC_SCHEMA_NAME, Collections.<String, DataSourceConfiguration>emptyMap()));
} catch (IllegalStateException ex) {
assertThat(ex.getMessage(), is("There should be only one datasource for encrypt, but now has 0 datasource(s)"));
}
}
@Test
public void assertRenewProperties() {
encryptDataSource.renew(getPropertiesChangedEvent());
assertThat(encryptDataSource.getDataSource().getRuntimeContext().getProps().getProps().getProperty("sql.show"), is("true"));
}
private PropertiesChangedEvent getPropertiesChangedEvent() {
Properties properties = new Properties();
properties.setProperty("sql.show", "true");
return new PropertiesChangedEvent(properties);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.shardingsphere.api.config.masterslave.LoadBalanceStrategyConfiguration;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import org.apache.shardingsphere.core.constant.ShardingConstant;
import org.apache.shardingsphere.core.exception.ShardingException;
import org.apache.shardingsphere.orchestration.center.configuration.InstanceConfiguration;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.temp.constant.OrchestrationType;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.DataSourceChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.MasterSlaveRuleChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.PropertiesChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.event.CircuitStateChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.event.DisabledStateChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.schema.OrchestrationShardingSchema;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlMasterSlaveDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.MasterSlaveDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.circuit.connection.CircuitBreakerConnection;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class OrchestrationMasterSlaveDataSourceTest {
private static OrchestrationMasterSlaveDataSource masterSlaveDataSource;
@BeforeClass
public static void setUp() throws SQLException, IOException, URISyntaxException {
masterSlaveDataSource = new OrchestrationMasterSlaveDataSource(getMasterSlaveDataSource(), getOrchestrationConfiguration());
}
private static MasterSlaveDataSource getMasterSlaveDataSource() throws IOException, SQLException, URISyntaxException {
File yamlFile = new File(OrchestrationMasterSlaveDataSource.class.getResource("/yaml/unit/masterSlave.yaml").toURI());
return (MasterSlaveDataSource) YamlMasterSlaveDataSourceFactory.createDataSource(yamlFile);
}
private static OrchestrationConfiguration getOrchestrationConfiguration() {
InstanceConfiguration instanceConfiguration = new InstanceConfiguration("TestRegistryCenter");
String orchestrationType = OrchestrationType.REGISTRY_CENTER.getValue() + "," + OrchestrationType.CONFIG_CENTER.getValue();
instanceConfiguration.setOrchestrationType(orchestrationType);
instanceConfiguration.setNamespace("test_ms");
instanceConfiguration.setServerLists("localhost:3181");
Map<String, InstanceConfiguration> instanceConfigurationMap = Collections.singletonMap("test", instanceConfiguration);
return new OrchestrationConfiguration(instanceConfigurationMap);
}
@Test
public void assertInitializeOrchestrationMasterSlaveDataSource() throws SQLException {
OrchestrationMasterSlaveDataSource masterSlaveDataSource = new OrchestrationMasterSlaveDataSource(getOrchestrationConfiguration());
assertThat(masterSlaveDataSource.getConnection(), instanceOf(Connection.class));
}
@Test
public void assertRenewRule() {
masterSlaveDataSource.renew(getMasterSlaveRuleChangedEvent());
assertThat(masterSlaveDataSource.getDataSource().getRuntimeContext().getRule().getName(), is("new_ms"));
}
private MasterSlaveRuleChangedEvent getMasterSlaveRuleChangedEvent() {
MasterSlaveRuleConfiguration masterSlaveRuleConfiguration = new MasterSlaveRuleConfiguration(
"new_ms", "ds_m", Collections.singletonList("ds_s"), new LoadBalanceStrategyConfiguration("ROUND_ROBIN"));
return new MasterSlaveRuleChangedEvent(ShardingConstant.LOGIC_SCHEMA_NAME, masterSlaveRuleConfiguration);
}
@Test
public void assertRenewDataSource() {
masterSlaveDataSource.renew(new DataSourceChangedEvent(ShardingConstant.LOGIC_SCHEMA_NAME, getDataSourceConfigurations()));
assertThat(masterSlaveDataSource.getDataSource().getDataSourceMap().size(), is(1));
}
private Map<String, DataSourceConfiguration> getDataSourceConfigurations() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
dataSource.setUsername("sa");
dataSource.setPassword("");
return Collections.singletonMap("ds_test", DataSourceConfiguration.getDataSourceConfiguration(dataSource));
}
@Test
public void assertRenewProperties() {
masterSlaveDataSource.renew(getPropertiesChangedEvent());
assertThat(masterSlaveDataSource.getDataSource().getRuntimeContext().getProps().getProps().getProperty("sql.show"), is("true"));
}
private PropertiesChangedEvent getPropertiesChangedEvent() {
Properties properties = new Properties();
properties.setProperty("sql.show", "true");
return new PropertiesChangedEvent(properties);
}
@Test
public void assertRenewDisabledState() {
masterSlaveDataSource.renew(getDisabledStateChangedEvent());
assertThat(masterSlaveDataSource.getDataSource().getRuntimeContext().getRule().getSlaveDataSourceNames().size(), is(0));
}
private DisabledStateChangedEvent getDisabledStateChangedEvent() {
OrchestrationShardingSchema shardingSchema = new OrchestrationShardingSchema("logic_db.ds_s");
return new DisabledStateChangedEvent(shardingSchema, true);
}
@Test
public void assertRenewCircuitState() throws SQLException {
masterSlaveDataSource.renew(new CircuitStateChangedEvent(true));
assertThat(masterSlaveDataSource.getConnection(), instanceOf(CircuitBreakerConnection.class));
}
@Test
public void assertGetDataSource() {
assertThat(masterSlaveDataSource.getDataSource(), instanceOf(MasterSlaveDataSource.class));
}
@Test
public void assertGetConnection() throws SQLException {
assertThat(masterSlaveDataSource.getConnection("root", "root"), instanceOf(Connection.class));
}
@Test(expected = ShardingException.class)
public void assertClose() throws Exception {
masterSlaveDataSource.close();
try {
masterSlaveDataSource.getDataSource().getDataSourceMap().values().iterator().next().getConnection();
} catch (final SQLException ex) {
throw new ShardingException(ex.getMessage());
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.datasource;
import lombok.SneakyThrows;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.shardingsphere.api.config.masterslave.LoadBalanceStrategyConfiguration;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import org.apache.shardingsphere.core.constant.ShardingConstant;
import org.apache.shardingsphere.orchestration.center.configuration.InstanceConfiguration;
import org.apache.shardingsphere.orchestration.center.configuration.OrchestrationConfiguration;
import org.apache.shardingsphere.orchestration.temp.constant.OrchestrationType;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.DataSourceChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.PropertiesChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.config.event.ShardingRuleChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.event.DisabledStateChangedEvent;
import org.apache.shardingsphere.orchestration.temp.internal.registry.state.schema.OrchestrationShardingSchema;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class OrchestrationShardingDataSourceTest {
private static OrchestrationShardingDataSource shardingDataSource;
@BeforeClass
public static void setUp() throws SQLException, IOException, URISyntaxException {
shardingDataSource = new OrchestrationShardingDataSource(getShardingDataSource(), getOrchestrationConfiguration());
}
private static ShardingDataSource getShardingDataSource() throws IOException, SQLException, URISyntaxException {
File yamlFile = new File(OrchestrationShardingDataSourceTest.class.getResource("/yaml/unit/sharding.yaml").toURI());
return (ShardingDataSource) YamlShardingDataSourceFactory.createDataSource(yamlFile);
}
private static OrchestrationConfiguration getOrchestrationConfiguration() {
InstanceConfiguration instanceConfiguration = new InstanceConfiguration("TestRegistryCenter");
String orchestrationType = OrchestrationType.REGISTRY_CENTER.getValue() + "," + OrchestrationType.CONFIG_CENTER.getValue();
instanceConfiguration.setOrchestrationType(orchestrationType);
instanceConfiguration.setNamespace("test_sharding");
instanceConfiguration.setServerLists("localhost:3181");
Map<String, InstanceConfiguration> instanceConfigurationMap = Collections.singletonMap("test", instanceConfiguration);
return new OrchestrationConfiguration(instanceConfigurationMap);
}
@Test
@SneakyThrows
public void assertInitializeOrchestrationShardingDataSource() {
OrchestrationShardingDataSource shardingDataSource = new OrchestrationShardingDataSource(getOrchestrationConfiguration());
assertThat(shardingDataSource.getConnection(), instanceOf(Connection.class));
}
@Test
public void assertRenewRule() {
shardingDataSource.renew(new ShardingRuleChangedEvent(ShardingConstant.LOGIC_SCHEMA_NAME, getShardingRuleConfig()));
assertThat(shardingDataSource.getDataSource().getRuntimeContext().getRule().getTableRules().size(), is(1));
}
private ShardingRuleConfiguration getShardingRuleConfig() {
ShardingRuleConfiguration result = new ShardingRuleConfiguration();
result.getTableRuleConfigs().add(new TableRuleConfiguration("logic_table", "ds_ms.table_${0..1}"));
result.getMasterSlaveRuleConfigs().add(getMasterSlaveRuleConfiguration());
return result;
}
private MasterSlaveRuleConfiguration getMasterSlaveRuleConfiguration() {
return new MasterSlaveRuleConfiguration("ds_ms", "ds_m", Collections.singletonList("ds_s"), new LoadBalanceStrategyConfiguration("ROUND_ROBIN"));
}
@Test
public void assertRenewDataSource() {
shardingDataSource.renew(new DataSourceChangedEvent(ShardingConstant.LOGIC_SCHEMA_NAME, getDataSourceConfigurations()));
assertThat(shardingDataSource.getDataSource().getDataSourceMap().size(), is(3));
}
private Map<String, DataSourceConfiguration> getDataSourceConfigurations() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
dataSource.setUsername("sa");
dataSource.setPassword("");
Map<String, DataSourceConfiguration> result = new LinkedHashMap<>();
result.put("ds_m", DataSourceConfiguration.getDataSourceConfiguration(dataSource));
result.put("ds_s", DataSourceConfiguration.getDataSourceConfiguration(dataSource));
result.put("ds_0", DataSourceConfiguration.getDataSourceConfiguration(dataSource));
return result;
}
@Test
public void assertRenewProperties() {
shardingDataSource.renew(getPropertiesChangedEvent());
assertThat(shardingDataSource.getDataSource().getRuntimeContext().getProps().getProps().getProperty("sql.show"), is("true"));
}
private PropertiesChangedEvent getPropertiesChangedEvent() {
Properties properties = new Properties();
properties.setProperty("sql.show", "true");
return new PropertiesChangedEvent(properties);
}
@Test
public void assertRenewDisabledState() {
shardingDataSource.renew(getDisabledStateChangedEvent());
assertThat(shardingDataSource.getDataSource().getRuntimeContext().getRule().getMasterSlaveRules().iterator().next().getSlaveDataSourceNames().size(), is(0));
}
private DisabledStateChangedEvent getDisabledStateChangedEvent() {
OrchestrationShardingSchema shardingSchema = new OrchestrationShardingSchema("logic_db.ds_s");
return new DisabledStateChangedEvent(shardingSchema, true);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.orchestration.temp.internal.util;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.shardingsphere.core.config.DataSourceConfiguration;
import org.junit.Test;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DataSourceConverterTest {
@Test
public void assertGetDataSourceMap() {
Map<String, DataSourceConfiguration> dataSourceConfigurationMap = new HashMap<>(2, 1);
DataSourceConfiguration dataSourceConfiguration0 = mock(DataSourceConfiguration.class);
DataSource dataSource0 = mock(DataSource.class);
when(dataSourceConfiguration0.createDataSource()).thenReturn(dataSource0);
dataSourceConfigurationMap.put("ds_0", dataSourceConfiguration0);
DataSourceConfiguration dataSourceConfiguration1 = mock(DataSourceConfiguration.class);
DataSource dataSource1 = mock(DataSource.class);
when(dataSourceConfiguration1.createDataSource()).thenReturn(dataSource1);
dataSourceConfigurationMap.put("ds_1", dataSourceConfiguration1);
Map<String, DataSource> actual = DataSourceConverter.getDataSourceMap(dataSourceConfigurationMap);
assertThat(actual.size(), is(2));
assertThat(actual.get("ds_0"), is(dataSource0));
assertThat(actual.get("ds_1"), is(dataSource1));
}
@Test
public void assertGetDataSourceConfigurationMap() {
Map<String, DataSourceConfiguration> actual = DataSourceConverter.getDataSourceConfigurationMap(createDataSourceMap());
assertThat(actual.size(), is(2));
assertNotNull(actual.get("ds_0"));
assertNotNull(actual.get("ds_1"));
}
private Map<String, DataSource> createDataSourceMap() {
Map<String, DataSource> result = new LinkedHashMap<>(2, 1);
result.put("ds_0", createDataSource("ds_0"));
result.put("ds_1", createDataSource("ds_1"));
return result;
}
private DataSource createDataSource(final String name) {
BasicDataSource result = new BasicDataSource();
result.setDriverClassName("com.mysql.jdbc.Driver");
result.setUrl("jdbc:mysql://localhost:3306/" + name);
result.setUsername("root");
result.setPassword("root");
return result;
}
}
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
org.apache.shardingsphere.shardingjdbc.orchestration.temp.util.TestRegistryCenter
......@@ -18,7 +18,9 @@
package org.apache.shardingsphere.orchestration.center.configuration;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
......@@ -31,6 +33,8 @@ import lombok.Setter;
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public final class OrchestrationConfiguration {
/**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册