Browse Source

使用DataSourceHolder 获取当前数据源

zhouhao 8 năm trước cách đây
mục cha
commit
eb07284644
15 tập tin đã thay đổi với 44 bổ sung461 xóa
  1. 1 11
      hsweb-web-core/src/main/java/org/hsweb/web/core/datasource/DataSourceHolder.java
  2. 3 25
      hsweb-web-dao/hsweb-web-dao-mybatis/src/main/java/org/hsweb/web/mybatis/MyBatisAutoConfiguration.java
  3. 1 2
      hsweb-web-dao/hsweb-web-dao-mybatis/src/main/java/org/hsweb/web/mybatis/MybatisDaoAutoConfiguration.java
  4. 3 23
      hsweb-web-dao/hsweb-web-dao-mybatis/src/main/java/org/hsweb/web/mybatis/plgins/pager/PagerInterceptor.java
  5. 0 0
      hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/OAuth2AccessMapper.xml
  6. 0 0
      hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/OAuth2ClientMapper.xml
  7. 0 59
      hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/mysql/OAuth2AccessMapper.xml
  8. 0 64
      hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/oracle/OAuth2ClientMapper.xml
  9. 31 33
      hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/DataBaseAutoConfiguration.java
  10. 2 3
      hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/SchedulerAutoConfiguration.java
  11. 0 4
      hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/form/DynamicFormServiceImpl.java
  12. 0 90
      hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/form/validator/java/JavaDycBeanValidator.java
  13. 0 130
      hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/form/validator/java/JavaDycBeanValidatorFactory.java
  14. 2 16
      hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/system/DataBaseManagerServiceImpl.java
  15. 1 1
      hsweb-web-service/hsweb-web-service-simple/src/test/java/org/hsweb/web/service/impl/quartz/QuartzJobServiceImplTest.java

+ 1 - 11
hsweb-web-core/src/main/java/org/hsweb/web/core/datasource/DataSourceHolder.java

@@ -17,15 +17,10 @@
 package org.hsweb.web.core.datasource;
 
 
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
 import javax.sql.DataSource;
 import java.sql.Connection;
 import java.sql.SQLException;
 
-@Component
 public class DataSourceHolder {
 
     private static DynamicDataSource dynamicDataSource;
@@ -34,17 +29,12 @@ public class DataSourceHolder {
 
     private static DatabaseType defaultDatabaseType;
 
-    @Autowired(required = false)
-    private DataSource dataSource;
-
-    @PostConstruct
-    public void init() throws SQLException {
+    public void init(DataSource dataSource) throws SQLException {
         if (null != dataSource) {
             Connection connection = null;
             try {
                 connection = dataSource.getConnection();
                 install(dataSource, DatabaseType.fromJdbcUrl(connection.getMetaData().getURL()));
-                dataSource = null;
             } finally {
                 if (null != connection)
                     connection.close();

+ 3 - 25
hsweb-web-dao/hsweb-web-dao-mybatis/src/main/java/org/hsweb/web/mybatis/MyBatisAutoConfiguration.java

@@ -19,35 +19,23 @@ package org.hsweb.web.mybatis;
 import org.apache.ibatis.mapping.DatabaseIdProvider;
 import org.apache.ibatis.plugin.Interceptor;
 import org.apache.ibatis.session.SqlSessionFactory;
-import org.hsweb.web.core.datasource.DataSourceHolder;
-import org.hsweb.web.datasource.dynamic.DynamicDataSourceAutoConfiguration;
-import org.hsweb.web.mybatis.MybatisProperties;
 import org.hsweb.web.mybatis.dynamic.DynamicDataSourceSqlSessionFactoryBuilder;
 import org.mybatis.spring.SqlSessionFactoryBean;
 import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.AutoConfigureAfter;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.core.io.DefaultResourceLoader;
-import org.springframework.core.io.Resource;
 import org.springframework.core.io.ResourceLoader;
-import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 import org.springframework.util.StringUtils;
 
 import javax.sql.DataSource;
-import java.io.IOException;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Properties;
 
 @Configuration
-@AutoConfigureAfter(DynamicDataSourceAutoConfiguration.class)
 @EnableConfigurationProperties(MybatisProperties.class)
+@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
 public class MyBatisAutoConfiguration {
 
     @Autowired
@@ -60,17 +48,7 @@ public class MyBatisAutoConfiguration {
     private ResourceLoader resourceLoader = new DefaultResourceLoader();
 
     @Autowired(required = false)
-    private DatabaseIdProvider databaseIdProvider = new DatabaseIdProvider() {
-        @Override
-        public void setProperties(Properties p) {
-
-        }
-
-        @Override
-        public String getDatabaseId(DataSource dataSource) throws SQLException {
-            return DataSourceHolder.getActiveDatabaseType().name();
-        }
-    };
+    private DatabaseIdProvider databaseIdProvider;
 
     @Bean(name = "sqlSessionFactory")
     public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {

+ 1 - 2
hsweb-web-dao/hsweb-web-dao-mybatis/src/main/java/org/hsweb/web/mybatis/MybatisDaoAutoConfiguration.java

@@ -1,6 +1,5 @@
 package org.hsweb.web.mybatis;
 
-import org.hsweb.web.datasource.dynamic.DynamicDataSourceAutoConfiguration;
 import org.hsweb.web.mybatis.utils.ResultMapsUtils;
 import org.mybatis.spring.SqlSessionTemplate;
 import org.mybatis.spring.annotation.MapperScan;
@@ -15,7 +14,7 @@ import javax.annotation.PostConstruct;
 @Configuration
 @ComponentScan(basePackages = {"org.hsweb.web.mybatis"})
 @MapperScan(basePackages = {"org.hsweb.web.dao"})
-@AutoConfigureAfter(DynamicDataSourceAutoConfiguration.class)
+@AutoConfigureAfter(MyBatisAutoConfiguration.class)
 @EnableConfigurationProperties(MybatisProperties.class)
 public class MybatisDaoAutoConfiguration {
 

+ 3 - 23
hsweb-web-dao/hsweb-web-dao-mybatis/src/main/java/org/hsweb/web/mybatis/plgins/pager/PagerInterceptor.java

@@ -1,8 +1,6 @@
 package org.hsweb.web.mybatis.plgins.pager;
 
 import org.apache.ibatis.executor.Executor;
-import org.apache.ibatis.executor.resultset.ResultSetHandler;
-import org.apache.ibatis.executor.statement.RoutingStatementHandler;
 import org.apache.ibatis.executor.statement.StatementHandler;
 import org.apache.ibatis.mapping.MappedStatement;
 import org.apache.ibatis.plugin.*;
@@ -11,11 +9,8 @@ import org.apache.ibatis.reflection.SystemMetaObject;
 import org.apache.ibatis.session.ResultHandler;
 import org.apache.ibatis.session.RowBounds;
 import org.hsweb.web.bean.common.QueryParam;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.hsweb.web.core.datasource.DataSourceHolder;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
-import org.springframework.boot.context.properties.ConfigurationProperties;
 import org.springframework.context.ApplicationContext;
 import org.springframework.stereotype.Component;
 
@@ -28,14 +23,10 @@ import java.util.Properties;
         RowBounds.class, ResultHandler.class})})
 @Component
 public class PagerInterceptor implements Interceptor {
-    protected Logger logger = LoggerFactory.getLogger(this.getClass());
     protected Map<String, PagerHelper> pagerHelperBase = new HashMap<>();
 
-    protected String dialect = null;
     @Autowired
     private ApplicationContext context;
-    @Autowired
-    private DataSourceProperties properties;
 
     @Override
     public Object intercept(Invocation target) throws Throwable {
@@ -51,7 +42,7 @@ public class PagerInterceptor implements Interceptor {
             Object obj = statementHandler.getParameterHandler().getParameterObject();
             if (obj instanceof QueryParam) {
                 QueryParam param = (QueryParam) obj;
-                PagerHelper helper = pagerHelperBase.get(dialect);
+                PagerHelper helper = pagerHelperBase.get(getDialect());
                 if (helper != null && param.isPaging() && !sql.contains("count(0)")) {
                     String newSql = helper.doPaging(param, sql);
                     metaStatementHandler.setValue("delegate.boundSql.sql", newSql);
@@ -63,26 +54,15 @@ public class PagerInterceptor implements Interceptor {
 
     @Override
     public void setProperties(Properties properties) {
-        System.out.println(properties);
     }
 
     @PostConstruct
     public void init() {
         Map<String, PagerHelper> helperMap = context.getBeansOfType(PagerHelper.class);
         helperMap.forEach((name, helper) -> pagerHelperBase.put(helper.getDialect(), helper));
-        dialect = getDialect();
     }
 
     public String getDialect() {
-        String url = properties.getDriverClassName();
-        if (url.contains("mysql")) {
-            return "mysql";
-        } else if (url.contains("oracle")) {
-            return "oracle";
-        } else if (url.contains("h2")) {
-            return "h2";
-        } else
-            logger.error("mybatis pager dialect not found!");
-        return "undefine";
+        return DataSourceHolder.getDefaultDatabaseType().name();
     }
 }

hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/oracle/OAuth2AccessMapper.xml → hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/OAuth2AccessMapper.xml


hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/mysql/OAuth2ClientMapper.xml → hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/OAuth2ClientMapper.xml


+ 0 - 59
hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/mysql/OAuth2AccessMapper.xml

@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!--
-  ~ Copyright 2015-2016 http://hsweb.me
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~     http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License.
-  -->
-
-<!DOCTYPE mapper
-        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
-        "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
-<mapper namespace="org.hsweb.web.oauth2.dao.OAuth2AccessMapper">
-    <resultMap id="OAuth2AccessResultMap" type="org.hsweb.web.oauth2.po.OAuth2Access">
-        <id property="id" column="u_id" javaType="string" jdbcType="VARCHAR"/>
-        <result property="clientId" column="client_id" javaType="String" jdbcType="VARCHAR"/>
-        <result property="userId" column="user_id" javaType="String" jdbcType="VARCHAR"/>
-        <result property="accessToken" column="access_token" javaType="String" jdbcType="VARCHAR"/>
-        <result property="refreshToken" column="refresh_token" javaType="String" jdbcType="VARCHAR"/>
-        <result property="expireIn" column="expire_in" javaType="int" jdbcType="NUMERIC"/>
-        <result property="createDate" column="create_date" javaType="java.util.Date" jdbcType="TIMESTAMP"/>
-    </resultMap>
-
-    <!--用于动态生成sql所需的配置-->
-    <sql id="config">
-        <bind name="resultMapId" value="'OAuth2AccessResultMap'"/>
-        <bind name="tableName" value="'s_oauth2_access'"/>
-    </sql>
-    <insert id="insert" parameterType="org.hsweb.web.bean.common.InsertParam">
-        <include refid="config"/>
-        <include refid="BasicMapper.buildInsertSql"/>
-    </insert>
-
-    <delete id="deleteById" parameterType="String">
-        delete from s_oauth2_access where u_id=#{id}
-    </delete>
-
-    <select id="selectByPk" parameterType="string" resultMap="OAuth2AccessResultMap">
-        select * from s_oauth2_access where u_id=#{id}
-    </select>
-
-    <select id="select" parameterType="org.hsweb.web.bean.common.QueryParam" resultMap="OAuth2AccessResultMap">
-        <include refid="config"/>
-        <include refid="BasicMapper.buildSelectSql"/>
-    </select>
-
-    <select id="total" parameterType="org.hsweb.web.bean.common.QueryParam" resultType="int">
-        <include refid="config"/>
-        <include refid="BasicMapper.buildTotalSql"/>
-    </select>
-</mapper>

+ 0 - 64
hsweb-web-oauth2/hsweb-web-oauth2-mybatis/src/main/resources/org/hsweb/web/dao/impl/mybatis/mapper/oracle/OAuth2ClientMapper.xml

@@ -1,64 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<!--
-  ~ Copyright 2015-2016 http://hsweb.me
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~     http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License.
-  -->
-
-<!DOCTYPE mapper
-        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
-        "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
-<mapper namespace="org.hsweb.web.oauth2.dao.OAuth2ClientMapper">
-    <resultMap id="OAuth2ClientResultMap" type="org.hsweb.web.oauth2.po.OAuth2Client">
-        <id property="id" column="u_id" javaType="string" jdbcType="VARCHAR"/>
-        <result property="userId" column="user_id" javaType="String" jdbcType="VARCHAR"/>
-        <result property="name" column="name" javaType="String" jdbcType="VARCHAR"/>
-        <result property="secret" column="secret" javaType="String" jdbcType="VARCHAR"/>
-        <result property="comment" column="comment" javaType="String" jdbcType="VARCHAR"/>
-        <result property="status" column="status" javaType="int" jdbcType="INTEGER"/>
-    </resultMap>
-
-    <!--用于动态生成sql所需的配置-->
-    <sql id="config">
-        <bind name="resultMapId" value="'OAuth2ClientResultMap'"/>
-        <bind name="tableName" value="'s_oauth2_client'"/>
-    </sql>
-    <insert id="insert" parameterType="org.hsweb.web.bean.common.InsertParam">
-        <include refid="config"/>
-        <include refid="BasicMapper.buildInsertSql"/>
-    </insert>
-
-    <delete id="delete" parameterType="org.hsweb.web.bean.common.DeleteParam">
-        <include refid="config"/>
-        <include refid="BasicMapper.buildDeleteSql"/>
-    </delete>
-
-    <update id="update" parameterType="org.hsweb.web.bean.common.UpdateParam">
-        <include refid="config"/>
-        <include refid="BasicMapper.buildUpdateSql"/>
-    </update>
-
-    <select id="selectByPk" parameterType="string" resultMap="OAuth2ClientResultMap">
-        select * from s_oauth2_client where u_id=#{id}
-    </select>
-
-    <select id="select" parameterType="org.hsweb.web.bean.common.QueryParam" resultMap="OAuth2ClientResultMap">
-        <include refid="config"/>
-        <include refid="BasicMapper.buildSelectSql"/>
-    </select>
-
-    <select id="total" parameterType="org.hsweb.web.bean.common.QueryParam" resultType="int">
-        <include refid="config"/>
-        <include refid="BasicMapper.buildTotalSql"/>
-    </select>
-</mapper>

+ 31 - 33
hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/DataBaseAutoConfiguration.java

@@ -14,33 +14,25 @@ import org.hsweb.ezorm.render.dialect.OracleDatabaseMeta;
 import org.hsweb.ezorm.run.Database;
 import org.hsweb.ezorm.run.simple.SimpleDatabase;
 import org.hsweb.web.core.authorize.ExpressionScopeBean;
+import org.hsweb.web.core.datasource.DataSourceHolder;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.AutoConfigureOrder;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
-import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
-import org.springframework.boot.context.properties.ConfigurationProperties;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
-import javax.annotation.PostConstruct;
 import javax.annotation.Resource;
+import java.sql.SQLException;
 import java.util.HashMap;
 import java.util.Map;
 
-/**
- * Created by zhouhao on 16-4-20.
- */
 @Configuration
-@ConfigurationProperties(
-        prefix = "spring.datasource"
-)
+@AutoConfigureOrder
 public class DataBaseAutoConfiguration {
     @Resource
     private SqlExecutor sqlExecutor;
 
-    @Autowired
-    private DataSourceProperties properties;
-
     @Autowired(required = false)
     private ValidatorFactory validatorFactory;
 
@@ -50,34 +42,40 @@ public class DataBaseAutoConfiguration {
     @Autowired(required = false)
     private Map<String, ExpressionScopeBean> expressionScopeBeanMap;
 
-
     @Bean
     @ConditionalOnMissingBean(TableMetaParser.class)
     public TableMetaParser tableMetaParser() {
-        String driverClassName = properties.getDriverClassName();
-        if (driverClassName.contains("mysql")) {
-            return new MysqlTableMetaParser(sqlExecutor);
-        } else if (driverClassName.contains("oracle")) {
-            return new OracleTableMetaParser(sqlExecutor);
-        }else if (driverClassName.contains("h2")) {
-            return new H2TableMetaParser(sqlExecutor);
+        switch (DataSourceHolder.getDefaultDatabaseType()) {
+            case mysql:
+                return new MysqlTableMetaParser(sqlExecutor);
+            case oracle:
+                return new OracleTableMetaParser(sqlExecutor);
+            case h2:
+                return new H2TableMetaParser(sqlExecutor);
+            default:
+                return null;
         }
-        return null;
     }
 
     @Bean
-    public Database database() {
-        DatabaseMetaData dataBaseMetaData = null;
-        String driverClassName = properties.getDriverClassName();
-        if (driverClassName.contains("mysql")) {
-            dataBaseMetaData = new MysqlDatabaseMeta();
-        } else if (driverClassName.contains("oracle")) {
-            dataBaseMetaData = new OracleDatabaseMeta();
-        } else if (driverClassName.contains("h2")) {
-            dataBaseMetaData = new H2DatabaseMeta();
+    public Database database(javax.sql.DataSource dataSource) throws SQLException {
+        DataSourceHolder holder = new DataSourceHolder();
+        holder.init(dataSource);
+        DatabaseMetaData dataBaseMetaData;
+        switch (DataSourceHolder.getDefaultDatabaseType()) {
+            case mysql:
+                dataBaseMetaData = new MysqlDatabaseMeta();
+                break;
+            case oracle:
+                dataBaseMetaData = new OracleDatabaseMeta();
+                break;
+            case h2:
+                dataBaseMetaData = new H2DatabaseMeta();
+                break;
+            default:
+                dataBaseMetaData = new OracleDatabaseMeta();
+                break;
         }
-        if (dataBaseMetaData == null)
-            dataBaseMetaData = new OracleDatabaseMeta();
         if (objectWrapperFactory != null)
             dataBaseMetaData.setObjectWrapperFactory(objectWrapperFactory);
         if (validatorFactory != null)

+ 2 - 3
hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/SchedulerAutoConfiguration.java

@@ -23,9 +23,8 @@ import org.quartz.core.QuartzScheduler;
 import org.quartz.impl.StdSchedulerFactory;
 import org.quartz.spi.JobFactory;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
-import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
-import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.annotation.Bean;
@@ -35,12 +34,12 @@ import org.springframework.scheduling.quartz.SchedulerFactoryBean;
 import org.springframework.transaction.PlatformTransactionManager;
 
 import javax.sql.DataSource;
-import java.util.List;
 import java.util.Map;
 
 @Configuration
 @ConditionalOnClass(QuartzScheduler.class)
 @EnableConfigurationProperties(SchedulerProperties.class)
+@AutoConfigureAfter(DataBaseAutoConfiguration.class)
 public class SchedulerAutoConfiguration {
 
     @Autowired

+ 0 - 4
hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/form/DynamicFormServiceImpl.java

@@ -454,8 +454,4 @@ public class DynamicFormServiceImpl implements DynamicFormService, ExpressionSco
         return result;
     }
 
-
-    public static void main(String[] args) {
-        Arrays.asList(1, 2, 3).forEach(System.out::println);
-    }
 }

+ 0 - 90
hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/form/validator/java/JavaDycBeanValidator.java

@@ -1,90 +0,0 @@
-/*
- * Copyright 2015-2016 http://hsweb.me
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.hsweb.web.service.impl.form.validator.java;
-
-import org.apache.commons.beanutils.BeanMap;
-import org.apache.commons.beanutils.BeanUtils;
-import org.hsweb.ezorm.exception.ValidationException;
-import org.hsweb.ezorm.meta.expand.Validator;
-import org.hsweb.web.bean.validator.ValidateResults;
-import org.hsweb.web.core.exception.BusinessException;
-import org.springframework.util.ReflectionUtils;
-
-import javax.validation.ConstraintViolation;
-import java.lang.reflect.Field;
-import java.util.*;
-
-public class JavaDycBeanValidator implements Validator {
-
-    private Class clazz;
-    private javax.validation.Validator hibernateValidator;
-
-
-    public JavaDycBeanValidator(Class clazz, javax.validation.Validator hibernateValidator) {
-        this.clazz = clazz;
-        this.hibernateValidator = hibernateValidator;
-    }
-
-    public boolean validateMap(Map<Object, Object> data, Operation operation) {
-        ValidateResults results = new ValidateResults();
-        try {
-            Object validatorTarget = clazz.newInstance();
-            Set<ConstraintViolation<Object>> result = new LinkedHashSet<>();
-            if (operation == Operation.INSERT) {
-                data.forEach((key, value) -> {
-                    try {
-                        BeanUtils.setProperty(validatorTarget, (String) key, value);
-                    } catch (Exception e) {
-                    }
-                });
-                result.addAll(hibernateValidator.validate(validatorTarget));
-            } else
-                data.forEach((key, value) -> {
-                    Field field = ReflectionUtils.findField(clazz, (String) key);
-                    if (field != null)
-                        result.addAll(hibernateValidator.validateValue(clazz, (String) key, value));
-                });
-            if (result.size() > 0) {
-                for (ConstraintViolation<Object> violation : result) {
-                    String property = violation.getPropertyPath().toString();
-                    results.addResult(property, violation.getMessage());
-                }
-            }
-        } catch (Exception e) {
-            throw new BusinessException("验证器异常!", e, 500);
-        }
-        if (results.size() > 0) throw new ValidationException(results.get(0).getMessage(), results);
-        return true;
-    }
-
-    @Override
-    public boolean validate(Object data, Operation operation) throws ValidationException {
-        if (data instanceof Map)
-            return validateMap(((Map) data), operation);
-        if (data instanceof Collection) {
-            for (Object o : ((Collection) data)) {
-                validate(o, operation);
-            }
-        } else {
-            BeanMap beanMap = new BeanMap();
-            beanMap.setBean(data);
-            validateMap(beanMap, operation);
-        }
-        return true;
-    }
-
-}

+ 0 - 130
hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/form/validator/java/JavaDycBeanValidatorFactory.java

@@ -1,130 +0,0 @@
-/*
- * Copyright 2015-2016 http://hsweb.me
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.hsweb.web.service.impl.form.validator.java;
-
-import org.hsweb.commons.StringUtils;
-import org.hsweb.expands.script.engine.DynamicScriptEngine;
-import org.hsweb.expands.script.engine.DynamicScriptEngineFactory;
-import org.hsweb.ezorm.meta.FieldMetaData;
-import org.hsweb.ezorm.meta.TableMetaData;
-import org.hsweb.ezorm.meta.expand.Validator;
-import org.hsweb.ezorm.meta.expand.ValidatorFactory;
-import org.hsweb.web.core.exception.BusinessException;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * 基于groovy动态bean的校验器
- */
-//@Component
-public class JavaDycBeanValidatorFactory implements ValidatorFactory {
-
-    @Autowired
-    private javax.validation.Validator hibernateValidator;
-
-    private Map<String, Validator> base = new HashMap<>();
-
-    private static final Map<Class, String> simpleType = new HashMap<>();
-
-    protected static DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine("java");
-
-    public static final String basePackage = "org.hsweb.web.bean.dyn_form";
-
-    private static final String[] imports = {
-            "import org.hibernate.validator.constraints.*;",
-            "import javax.validation.constraints.*;"
-    };
-
-    static {
-        simpleType.put(Integer.class, "int");
-        simpleType.put(Long.class, "long");
-        simpleType.put(String.class, "String");
-        simpleType.put(Double.class, "double");
-        simpleType.put(Float.class, "float");
-        simpleType.put(Boolean.class, "boolean");
-        simpleType.put(Short.class, "short");
-        simpleType.put(Byte.class, "byte");
-        simpleType.put(Character.class, "char");
-    }
-
-    @Override
-    public Validator createValidator(TableMetaData metaData) {
-        return initValidator(metaData);
-    }
-
-    /**
-     * 根据表结构动态生成一个基于hibernate-validator的bean
-     *
-     * @param metaData 表结构
-     * @return 验证器对象
-     */
-    public Validator initValidator(TableMetaData metaData) {
-        StringBuilder script = new StringBuilder();
-        String className = StringUtils.concat(basePackage, ".", metaData.getName());
-        script.append("package ").append(basePackage).append(";\n");
-        for (String anImport : imports) {
-            script.append(anImport).append("\n");
-        }
-        script.append("public class ").append(metaData.getName()).append("{\n");
-        boolean hasValidator = false;
-        for (FieldMetaData fieldMetaData : metaData.getFields()) {
-            String typeName = simpleType.get(fieldMetaData.getJavaType());
-            if (typeName == null) typeName = fieldMetaData.getJavaType().getName();
-            if (fieldMetaData.getValidator() == null || fieldMetaData.getValidator().isEmpty()) continue;
-            for (String ann : fieldMetaData.getValidator()) {
-                hasValidator = true;
-                script.append("\t@").append(ann).append("\n");
-            }
-            script.append("\tprivate ")
-                    .append(typeName).append(" ")
-                    .append(fieldMetaData.getName()).append(";\n\n");
-        }
-        //没有配置验证器
-        if (!hasValidator) return null;
-        for (FieldMetaData fieldMetaData : metaData.getFields()) {
-            String typeName = simpleType.get(fieldMetaData.getJavaType());
-            if (typeName == null) typeName = fieldMetaData.getJavaType().getName();
-            if (fieldMetaData.getValidator() == null || fieldMetaData.getValidator().isEmpty()) continue;
-            script.append("public ")
-                    .append(typeName).append("boolean".equals(typeName) ? "is" : " get")
-                    .append(StringUtils.toUpperCaseFirstOne(fieldMetaData.getName()))
-                    .append("(){\n")
-                    .append("\treturn this.").append(fieldMetaData.getName()).append(";")
-                    .append("\n}\n");
-            script.append("public void set").append(StringUtils.toUpperCaseFirstOne(fieldMetaData.getName()))
-                    .append("(")
-                    .append(typeName).append(" ").append(fieldMetaData.getName())
-                    .append(")")
-                    .append("{\n")
-                    .append("\tthis.").append(fieldMetaData.getName()).append("=").append(fieldMetaData.getName()).append(";")
-                    .append("\n}\n\n");
-        }
-        script.append("}");
-        try {
-            engine.compile(className, script.toString());
-        } catch (Exception e) {
-            throw new BusinessException("创建动态表单验证器失败!", e, 500);
-        }
-        JavaDycBeanValidator validator = new JavaDycBeanValidator(((Class) engine.execute(className).getResult()), hibernateValidator);
-        base.put(metaData.getName(), validator);
-        return validator;
-    }
-
-
-}

+ 2 - 16
hsweb-web-service/hsweb-web-service-simple/src/main/java/org/hsweb/web/service/impl/system/DataBaseManagerServiceImpl.java

@@ -15,6 +15,7 @@ import org.hsweb.ezorm.render.dialect.H2DatabaseMeta;
 import org.hsweb.ezorm.render.dialect.MysqlDatabaseMeta;
 import org.hsweb.ezorm.render.dialect.OracleDatabaseMeta;
 import org.hsweb.ezorm.render.support.simple.SimpleSQL;
+import org.hsweb.web.core.datasource.DataSourceHolder;
 import org.hsweb.web.core.datasource.DynamicDataSource;
 import org.hsweb.web.core.exception.BusinessException;
 import org.hsweb.web.core.exception.NotFoundException;
@@ -136,22 +137,7 @@ public class DataBaseManagerServiceImpl implements DataBaseManagerService {
     }
 
     public DBType getDBType() {
-        String datasourceId = DynamicDataSource.getActiveDataSourceId();
-        String driver = dataSourceProperties.getDriverClassName();
-        if (datasourceId != null) {
-            org.hsweb.web.bean.po.datasource.DataSource dataSource = dataSourceService.selectByPk(datasourceId);
-            driver = dataSource.getDriver();
-        }
-        if (driver.contains("mysql")) {
-            return DBType.mysql;
-        }
-        if (driver.contains("oracle")) {
-            return DBType.oracle;
-        }
-        if (driver.contains("h2")) {
-            return DBType.h2;
-        }
-        throw new NotFoundException(driver);
+        return DBType.valueOf(DataSourceHolder.getActiveDatabaseType().name());
     }
 
     enum DBType {

+ 1 - 1
hsweb-web-service/hsweb-web-service-simple/src/test/java/org/hsweb/web/service/impl/quartz/QuartzJobServiceImplTest.java

@@ -30,7 +30,6 @@ import javax.annotation.Resource;
 /**
  * @author zhouhao
  */
-@Component
 public class QuartzJobServiceImplTest extends AbstractTestCase {
 
     @Resource
@@ -38,6 +37,7 @@ public class QuartzJobServiceImplTest extends AbstractTestCase {
 
     @Resource
     private UserService userService;
+
     static final String jobId = "test";
 
     @Test