This is an automated email from the ASF dual-hosted git repository.

jianglongtao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git


The following commit(s) were added to refs/heads/master by this push:
     new d5bf025f58c Add tests for druid and c3p0 (#27991)
d5bf025f58c is described below

commit d5bf025f58c9195477a51c23357bcead79db96c8
Author: DaleyZou's World <[email protected]>
AuthorDate: Thu Aug 10 17:16:29 2023 +0800

    Add tests for druid and c3p0 (#27991)
    
    * Add tests for druid and c3p0l (#27894)
    Fix setting properties using reflection (#27988)
    * test for Support more data source connection pool
    
    * Fix setting properties using reflection
    
    * * change for Spotless check
    
    * * change for Spotless check
    
    * * change for Spotless check
    
    * * change for Spotless check
    
    * * fix dbcp properties with string
    
    * * Modify the code according to the development specification
    
    * * Extract the setJdbcUrlProperties method
    
    * * Modify as suggested by cr
---
 .../pool/creator/DataSourcePoolCreator.java        | 21 ++++++---
 .../pool/creator/DataSourceReflection.java         | 13 ++++--
 .../metadata/DataSourcePoolMetaDataReflection.java | 16 +++++--
 .../creator/C3P0DataSourcePoolCreatorTest.java     | 54 ++++++++++++++++++++++
 .../creator/DruidDataSourcePoolCreatorTest.java    | 53 +++++++++++++++++++++
 .../infra/util/reflection/ReflectionUtils.java     | 34 ++++++++++++++
 6 files changed, 179 insertions(+), 12 deletions(-)

diff --git 
a/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourcePoolCreator.java
 
b/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourcePoolCreator.java
index bf1e212fc82..11d77b62592 100644
--- 
a/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourcePoolCreator.java
+++ 
b/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourcePoolCreator.java
@@ -44,6 +44,7 @@ import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Optional;
+import java.util.Properties;
 
 /**
  * Data source pool creator.
@@ -203,8 +204,8 @@ public final class DataSourcePoolCreator {
         if (poolMetaData.isPresent()) {
             setDefaultFields(dataSourceReflection, poolMetaData.get());
             setConfiguredFields(dataSourceProps, dataSourceReflection, 
poolMetaData.get());
-            
appendJdbcUrlProperties(dataSourceProps.getCustomDataSourceProperties(), 
result, poolMetaData.get());
-            dataSourceReflection.addDefaultDataSourceProperties();
+            
appendJdbcUrlProperties(dataSourceProps.getCustomDataSourceProperties(), 
result, poolMetaData.get(), dataSourceReflection);
+            
dataSourceReflection.addDefaultDataSourceProperties(poolMetaData.get());
         } else {
             setConfiguredFields(dataSourceProps, dataSourceReflection);
         }
@@ -259,14 +260,22 @@ public final class DataSourcePoolCreator {
     }
     
     @SuppressWarnings("unchecked")
-    private static void appendJdbcUrlProperties(final 
CustomDataSourceProperties customDataSourceProps, final DataSource 
targetDataSource, final DataSourcePoolMetaData poolMetaData) {
+    private static void appendJdbcUrlProperties(final 
CustomDataSourceProperties customDataSourceProps, final DataSource 
targetDataSource, final DataSourcePoolMetaData poolMetaData,
+                                                final DataSourceReflection 
dataSourceReflection) {
         String jdbcUrlPropertiesFieldName = 
poolMetaData.getFieldMetaData().getJdbcUrlPropertiesFieldName();
         if (null != jdbcUrlPropertiesFieldName && 
customDataSourceProps.getProperties().containsKey(jdbcUrlPropertiesFieldName)) {
             Map<String, Object> jdbcUrlProps = (Map<String, Object>) 
customDataSourceProps.getProperties().get(jdbcUrlPropertiesFieldName);
             DataSourcePoolMetaDataReflection dataSourcePoolMetaDataReflection 
= new DataSourcePoolMetaDataReflection(targetDataSource, 
poolMetaData.getFieldMetaData());
-            for (Entry<String, Object> entry : jdbcUrlProps.entrySet()) {
-                
dataSourcePoolMetaDataReflection.getJdbcConnectionProperties().ifPresent(optional
 -> optional.setProperty(entry.getKey(), entry.getValue().toString()));
-            }
+            Optional<Properties> jdbcConnectionPropOptional = 
dataSourcePoolMetaDataReflection.getJdbcConnectionProperties();
+            jdbcConnectionPropOptional.ifPresent(optional -> 
setJdbcUrlProperties(dataSourceReflection, optional, jdbcUrlProps, 
jdbcUrlPropertiesFieldName));
+        }
+    }
+    
+    private static void setJdbcUrlProperties(final DataSourceReflection 
dataSourceReflection, final Properties jdbcConnectionProps, final Map<String, 
Object> customProps,
+                                             final String 
jdbcUrlPropertiesFieldName) {
+        for (Entry<String, Object> entry : customProps.entrySet()) {
+            jdbcConnectionProps.setProperty(entry.getKey(), 
entry.getValue().toString());
         }
+        dataSourceReflection.setField(jdbcUrlPropertiesFieldName, 
jdbcConnectionProps);
     }
 }
diff --git 
a/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourceReflection.java
 
b/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourceReflection.java
index 6e7a15fa4e3..be88be7bbc5 100644
--- 
a/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourceReflection.java
+++ 
b/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/creator/DataSourceReflection.java
@@ -130,6 +130,9 @@ public final class DataSourceReflection {
     @SneakyThrows(ReflectiveOperationException.class)
     private void setField(final Method method, final Object fieldValue) {
         Class<?> paramType = method.getParameterTypes()[0];
+        if (String.class == paramType && 
Properties.class.isAssignableFrom(fieldValue.getClass())) {
+            return;
+        }
         if (int.class == paramType || Integer.class == paramType) {
             method.invoke(dataSource, Integer.parseInt(fieldValue.toString()));
         } else if (long.class == paramType || Long.class == paramType) {
@@ -158,8 +161,10 @@ public final class DataSourceReflection {
     
     /**
      * Add default data source properties.
+     *
+     * @param dataSourcePoolMetaData data source pool meta data
      */
-    public void addDefaultDataSourceProperties() {
+    public void addDefaultDataSourceProperties(final DataSourcePoolMetaData 
dataSourcePoolMetaData) {
         DataSourcePoolMetaDataReflection dataSourcePoolMetaDataReflection = 
new DataSourcePoolMetaDataReflection(dataSource,
                 TypedSPILoader.findService(DataSourcePoolMetaData.class, 
dataSource.getClass().getName())
                         
.map(DataSourcePoolMetaData::getFieldMetaData).orElseGet(DefaultDataSourcePoolFieldMetaData::new));
@@ -170,13 +175,15 @@ public final class DataSourceReflection {
         }
         ConnectionProperties connectionProps = 
DatabaseTypedSPILoader.getService(ConnectionPropertiesParser.class, 
DatabaseTypeFactory.get(jdbcUrl.get())).parse(jdbcUrl.get(), null, null);
         Properties queryProps = connectionProps.getQueryProperties();
+        Properties jdbcProps = jdbcConnectionProps.get();
         for (Entry<Object, Object> entry : 
connectionProps.getDefaultQueryProperties().entrySet()) {
             String defaultPropertyKey = entry.getKey().toString();
             String defaultPropertyValue = entry.getValue().toString();
-            if (!containsDefaultProperty(defaultPropertyKey, 
jdbcConnectionProps.get(), queryProps)) {
-                jdbcConnectionProps.get().setProperty(defaultPropertyKey, 
defaultPropertyValue);
+            if (!containsDefaultProperty(defaultPropertyKey, jdbcProps, 
queryProps)) {
+                jdbcProps.setProperty(defaultPropertyKey, 
defaultPropertyValue);
             }
         }
+        
setField(dataSourcePoolMetaData.getFieldMetaData().getJdbcUrlPropertiesFieldName(),
 jdbcProps);
     }
     
     private boolean containsDefaultProperty(final String defaultPropertyKey, 
final Properties targetDataSourceProps, final Properties queryProps) {
diff --git 
a/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/metadata/DataSourcePoolMetaDataReflection.java
 
b/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/metadata/DataSourcePoolMetaDataReflection.java
index 007864fd696..9f728527789 100644
--- 
a/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/metadata/DataSourcePoolMetaDataReflection.java
+++ 
b/infra/datasource/core/src/main/java/org/apache/shardingsphere/infra/datasource/pool/metadata/DataSourcePoolMetaDataReflection.java
@@ -40,15 +40,25 @@ public final class DataSourcePoolMetaDataReflection {
      * @return JDBC URL
      */
     public Optional<String> getJdbcUrl() {
-        return ReflectionUtils.getFieldValue(targetDataSource, 
dataSourcePoolFieldMetaData.getJdbcUrlFieldName());
+        Optional<String> jdbcUrl = 
ReflectionUtils.getFieldValue(targetDataSource, 
dataSourcePoolFieldMetaData.getJdbcUrlFieldName());
+        if (jdbcUrl.isPresent()) {
+            return jdbcUrl;
+        } else {
+            return ReflectionUtils.getFieldValueByGetMethod(targetDataSource, 
dataSourcePoolFieldMetaData.getJdbcUrlFieldName());
+        }
     }
     
     /**
      * Get JDBC connection properties.
-     * 
+     *
      * @return JDBC connection properties
      */
     public Optional<Properties> getJdbcConnectionProperties() {
-        return ReflectionUtils.getFieldValue(targetDataSource, 
dataSourcePoolFieldMetaData.getJdbcUrlPropertiesFieldName());
+        Optional<Properties> properties = 
ReflectionUtils.getFieldValue(targetDataSource, 
dataSourcePoolFieldMetaData.getJdbcUrlPropertiesFieldName());
+        if (properties.isPresent()) {
+            return properties;
+        } else {
+            return ReflectionUtils.getFieldValueByGetMethod(targetDataSource, 
dataSourcePoolFieldMetaData.getJdbcUrlPropertiesFieldName());
+        }
     }
 }
diff --git 
a/infra/datasource/type/c3p0/src/test/java/org/apache/shardingsphere/infra/datasource/c3p0/creator/C3P0DataSourcePoolCreatorTest.java
 
b/infra/datasource/type/c3p0/src/test/java/org/apache/shardingsphere/infra/datasource/c3p0/creator/C3P0DataSourcePoolCreatorTest.java
new file mode 100644
index 00000000000..0ece9e77035
--- /dev/null
+++ 
b/infra/datasource/type/c3p0/src/test/java/org/apache/shardingsphere/infra/datasource/c3p0/creator/C3P0DataSourcePoolCreatorTest.java
@@ -0,0 +1,54 @@
+/*
+ * 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.infra.datasource.c3p0.creator;
+
+import com.mchange.v2.c3p0.ComboPooledDataSource;
+import 
org.apache.shardingsphere.infra.datasource.pool.creator.DataSourcePoolCreator;
+import org.apache.shardingsphere.infra.datasource.props.DataSourceProperties;
+import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource;
+import org.apache.shardingsphere.test.util.PropertiesBuilder;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+class C3P0DataSourcePoolCreatorTest {
+    
+    @Test
+    void assertCreateDataSource() {
+        ComboPooledDataSource actual = (ComboPooledDataSource) 
DataSourcePoolCreator.create(new 
DataSourceProperties(ComboPooledDataSource.class.getName(), 
createDataSourceProperties()));
+        assertThat(actual.getJdbcUrl(), is("jdbc:mock://127.0.0.1/foo_ds"));
+        assertThat(actual.getUser(), is("root"));
+        assertThat(actual.getPassword(), is("root"));
+        assertThat(actual.getProperties(), is(PropertiesBuilder.build(new 
PropertiesBuilder.Property("foo", "foo_value"), new 
PropertiesBuilder.Property("bar", "bar_value"),
+                new PropertiesBuilder.Property("password", "root"), new 
PropertiesBuilder.Property("user", "root"))));
+    }
+    
+    private Map<String, Object> createDataSourceProperties() {
+        Map<String, Object> result = new HashMap<>();
+        result.put("url", "jdbc:mock://127.0.0.1/foo_ds");
+        result.put("driverClassName", MockedDataSource.class.getName());
+        result.put("username", "root");
+        result.put("password", "root");
+        result.put("properties", PropertiesBuilder.build(new 
PropertiesBuilder.Property("foo", "foo_value"), new 
PropertiesBuilder.Property("bar", "bar_value")));
+        return result;
+    }
+}
diff --git 
a/infra/datasource/type/druid/src/test/java/org/apache/shardingsphere/infra/datasource/druid/creator/DruidDataSourcePoolCreatorTest.java
 
b/infra/datasource/type/druid/src/test/java/org/apache/shardingsphere/infra/datasource/druid/creator/DruidDataSourcePoolCreatorTest.java
new file mode 100644
index 00000000000..4fb33ec36fc
--- /dev/null
+++ 
b/infra/datasource/type/druid/src/test/java/org/apache/shardingsphere/infra/datasource/druid/creator/DruidDataSourcePoolCreatorTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.infra.datasource.druid.creator;
+
+import com.alibaba.druid.pool.DruidDataSource;
+import 
org.apache.shardingsphere.infra.datasource.pool.creator.DataSourcePoolCreator;
+import org.apache.shardingsphere.infra.datasource.props.DataSourceProperties;
+import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource;
+import org.apache.shardingsphere.test.util.PropertiesBuilder;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+class DruidDataSourcePoolCreatorTest {
+    
+    @Test
+    void assertCreateDataSource() {
+        DruidDataSource actual = (DruidDataSource) 
DataSourcePoolCreator.create(new 
DataSourceProperties(DruidDataSource.class.getName(), 
createDataSourceProperties()));
+        assertThat(actual.getUrl(), is("jdbc:mock://127.0.0.1/foo_ds"));
+        assertThat(actual.getUsername(), is("root"));
+        assertThat(actual.getPassword(), is("root"));
+        assertThat(actual.getConnectProperties(), 
is(PropertiesBuilder.build(new PropertiesBuilder.Property("foo", "foo_value"), 
new PropertiesBuilder.Property("bar", "bar_value"))));
+    }
+    
+    private Map<String, Object> createDataSourceProperties() {
+        Map<String, Object> result = new HashMap<>();
+        result.put("url", "jdbc:mock://127.0.0.1/foo_ds");
+        result.put("driverClassName", MockedDataSource.class.getName());
+        result.put("username", "root");
+        result.put("password", "root");
+        result.put("connectProperties", PropertiesBuilder.build(new 
PropertiesBuilder.Property("foo", "foo_value"), new 
PropertiesBuilder.Property("bar", "bar_value")));
+        return result;
+    }
+}
diff --git 
a/infra/util/src/main/java/org/apache/shardingsphere/infra/util/reflection/ReflectionUtils.java
 
b/infra/util/src/main/java/org/apache/shardingsphere/infra/util/reflection/ReflectionUtils.java
index de338d0bc5b..85c91fdf01c 100644
--- 
a/infra/util/src/main/java/org/apache/shardingsphere/infra/util/reflection/ReflectionUtils.java
+++ 
b/infra/util/src/main/java/org/apache/shardingsphere/infra/util/reflection/ReflectionUtils.java
@@ -17,6 +17,7 @@
 
 package org.apache.shardingsphere.infra.util.reflection;
 
+import com.google.common.base.CaseFormat;
 import lombok.AccessLevel;
 import lombok.NoArgsConstructor;
 import lombok.SneakyThrows;
@@ -31,6 +32,8 @@ import java.util.Optional;
 @NoArgsConstructor(access = AccessLevel.PRIVATE)
 public final class ReflectionUtils {
     
+    private static final String GETTER_PREFIX = "get";
+    
     /**
      * Get field value.
      * 
@@ -134,4 +137,35 @@ public final class ReflectionUtils {
         }
         return result;
     }
+    
+    /**
+     * Get field value by get method.
+     *
+     * @param target target
+     * @param fieldName field name
+     * @param <T> type of field value
+     * @return field value
+     */
+    public static <T> Optional<T> getFieldValueByGetMethod(final Object 
target, final String fieldName) {
+        String getterName = GETTER_PREFIX + 
CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, fieldName);
+        final Optional<Method> method = findMethod(target.getClass(), 
getterName);
+        if (method.isPresent()) {
+            T value = invokeMethod(method.get(), target);
+            return Optional.ofNullable(value);
+        } else {
+            return Optional.empty();
+        }
+    }
+    
+    private static Optional<Method> findMethod(final Class<?> clazz, final 
String methodName, final Class<?>... parameterTypes) {
+        try {
+            return Optional.of(clazz.getMethod(methodName, parameterTypes));
+        } catch (NoSuchMethodException e) {
+            Class<?> superclass = clazz.getSuperclass();
+            if (null != superclass && Object.class != superclass) {
+                return findMethod(superclass, methodName, parameterTypes);
+            }
+        }
+        return Optional.empty();
+    }
 }

Reply via email to