소스 검색

job配置服务升级提交

wangzhinan 2 년 전
부모
커밋
b7693e9c0b
100개의 변경된 파일15727개의 추가작업 그리고 16개의 파일을 삭제
  1. 49 0
      common/common-data-elasticsearch/pom.xml
  2. 81 0
      common/common-data-elasticsearch/src/main/java/com/yihu/ehr/elasticsearch/ElasticSearchPool.java
  3. 780 0
      common/common-data-elasticsearch/src/main/java/com/yihu/ehr/elasticsearch/ElasticSearchUtil.java
  4. 45 0
      common/common-data-elasticsearch/src/main/java/com/yihu/ehr/elasticsearch/config/ElasticSearchConfig.java
  5. 46 0
      common/common-data-hbase/pom.xml
  6. 32 0
      common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/AbstractHBaseClient.java
  7. 213 0
      common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/HBaseAdmin.java
  8. 395 0
      common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/HBaseDao.java
  9. 158 0
      common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/TableBundle.java
  10. 86 0
      common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/config/HbaseConfig.java
  11. 13 0
      common/common-data-hbase/src/main/resources/hbase-site.xml
  12. 163 0
      common/common-data-hbase/src/main/resources/hbase/core-site.xml
  13. 243 0
      common/common-data-hbase/src/main/resources/hbase/hbase-site.xml
  14. 348 0
      common/common-data-hbase/src/main/resources/hbase/hdfs-site.xml
  15. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/interfacemg/BaseThirdUserDO.java
  16. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/interfacemg/BaseThirdUserInterfaceDO.java
  17. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/interfacemg/BaseThirdUserInterfaceLogDO.java
  18. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/interfacemg/BaseThirdUserInterfaceStandardDO.java
  19. 8 5
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/interfacemg/BaseUserInterfaceEndpoint.java
  20. 5 5
      svr/svr-base/src/main/java/com/yihu/jw/base/service/interfacemg/BaseUserInterfaceService.java
  21. 1 1
      svr/svr-base/src/main/resources/bootstrap.yml
  22. 1 1
      svr/svr-internet-hospital-job/src/main/java/com/yihu/Application.java
  23. 42 0
      svr/svr-quota/.gitignore
  24. BIN
      svr/svr-quota/doc/统计架构.png
  25. 267 0
      svr/svr-quota/pom.xml
  26. 14 0
      svr/svr-quota/readme.MD
  27. 23 0
      svr/svr-quota/src/main/java/com/yihu/quota/SvrQuotaApplication.java
  28. 50 0
      svr/svr-quota/src/main/java/com/yihu/quota/config/AsyncConfig.java
  29. 25 0
      svr/svr-quota/src/main/java/com/yihu/quota/config/quota/JobFactory.java
  30. 52 0
      svr/svr-quota/src/main/java/com/yihu/quota/config/quota/SchedulerConfig.java
  31. 1801 0
      svr/svr-quota/src/main/java/com/yihu/quota/constants/ServiceApi.java
  32. 436 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/BaseController.java
  33. 436 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/ElasticSearchController.java
  34. 198 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/ElasticSearchEndPoint.java
  35. 86 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/JobController.java
  36. 93 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/MedicalInsuranceController.java
  37. 335 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/QuotaController.java
  38. 1050 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/QuotaReportController.java
  39. 108 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/QuotaReportStatisticsController.java
  40. 440 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/SingleDiseasesController.java
  41. 362 0
      svr/svr-quota/src/main/java/com/yihu/quota/controller/SolrStatisticsEndPoint.java
  42. 30 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/RsResourceQuotaDao.java
  43. 13 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/TjQuotaDao.java
  44. 18 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/TjQuotaGovProvisionDao.java
  45. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/TjQuotaLogDao.java
  46. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dict/SystemDictDao.java
  47. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dict/SystemDictListDao.java
  48. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dimension/TjDimensionMainDao.java
  49. 12 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dimension/TjDimensionSlaveDao.java
  50. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dimension/TjQuotaDimensionMainDao.java
  51. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dimension/TjQuotaDimensionSlaveDao.java
  52. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/save/TjDataSaveDao.java
  53. 14 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/save/TjQuotaDataSaveDao.java
  54. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/source/TjDataSourceDao.java
  55. 11 0
      svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/source/TjQuotaDataSourceDao.java
  56. 268 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/Contant.java
  57. 47 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/ExtractConverUtil.java
  58. 99 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/conver/AgeConvert.java
  59. 24 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/conver/Convert.java
  60. 44 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/conver/ConvertHelper.java
  61. 162 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/ExtractHelper.java
  62. 279 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/ExtractPercentHelper.java
  63. 723 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/ExtractUtil.java
  64. 451 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/es/EsExtract.java
  65. 444 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/es/EsResultExtract.java
  66. 176 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/mysql/MysqlExtract.java
  67. 283 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/solr/SolrExtract.java
  68. 91 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/model/DbConfig.java
  69. 326 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/model/EsConfig.java
  70. 122 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/save/ExtractDataWithRunnable.java
  71. 148 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/save/LargDataWithRunnable.java
  72. 39 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/save/SaveHelper.java
  73. 129 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/save/es/ElastricSearchSave.java
  74. 403 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/util/ElasticsearchUtil.java
  75. 59 0
      svr/svr-quota/src/main/java/com/yihu/quota/etl/util/EsClientUtil.java
  76. 333 0
      svr/svr-quota/src/main/java/com/yihu/quota/job/EsQuotaJob.java
  77. 190 0
      svr/svr-quota/src/main/java/com/yihu/quota/job/EsQuotaPercentJob.java
  78. 106 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/RsResourceQuota.java
  79. 229 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/TjQuota.java
  80. 119 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/TjQuotaGovProvision.java
  81. 88 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/TjQuotaLog.java
  82. 114 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dict/SystemDict.java
  83. 152 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dict/SystemDictList.java
  84. 195 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dimension/TjDimensionMain.java
  85. 172 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dimension/TjDimensionSlave.java
  86. 84 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dimension/TjQuotaDimensionMain.java
  87. 114 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dimension/TjQuotaDimensionSlave.java
  88. 180 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/save/TjDataSave.java
  89. 76 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/save/TjQuotaDataSave.java
  90. 173 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/source/TjDataSource.java
  91. 83 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/source/TjQuotaDataSource.java
  92. 47 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/rest/HospitalComposeModel.java
  93. 30 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/rest/QuotaReport.java
  94. 39 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/rest/QuotaTreeModel.java
  95. 28 0
      svr/svr-quota/src/main/java/com/yihu/quota/model/rest/ResultModel.java
  96. 17 0
      svr/svr-quota/src/main/java/com/yihu/quota/service/dict/DictService.java
  97. 26 0
      svr/svr-quota/src/main/java/com/yihu/quota/service/dimension/TjDimensionMainService.java
  98. 32 0
      svr/svr-quota/src/main/java/com/yihu/quota/service/dimension/TjDimensionSlaveService.java
  99. 108 0
      svr/svr-quota/src/main/java/com/yihu/quota/service/job/JobService.java
  100. 0 0
      svr/svr-quota/src/main/java/com/yihu/quota/service/medicalInsurance/MedicalInsuranceService.java

+ 49 - 0
common/common-data-elasticsearch/pom.xml

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>com.yihu.jw</groupId>
        <artifactId>wlyy-lib-parent-pom</artifactId>
        <version>2.4.0</version>
        <relativePath>../../wlyy-lib-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>common-data-elasticsearch</artifactId>
    <version>${project.parent.version}</version>
    <dependencies>
        <!-- true -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <!-- ElasticSearch -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.nlpcn</groupId>
            <artifactId>elasticsearch-sql</artifactId>
            <version>2.4.1.0</version>
        </dependency>
        <!-- ElasticSearch -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>

+ 81 - 0
common/common-data-elasticsearch/src/main/java/com/yihu/ehr/elasticsearch/ElasticSearchPool.java

@ -0,0 +1,81 @@
package com.yihu.ehr.elasticsearch;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.ElasticSearchDruidDataSourceFactory;
import com.yihu.ehr.elasticsearch.config.ElasticSearchConfig;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.net.InetSocketAddress;
import java.util.Properties;
/**
 * Created by progr1mmer on 2018/1/4.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ElasticSearchPool {
    private static volatile TransportClient transportClient;
    @Autowired
    private ElasticSearchConfig elasticSearchConfig;
    private TransportClient getTransportClient() {
        Settings settings = Settings.builder()
                .put("cluster.name", elasticSearchConfig.getClusterName())
                .put("client.transport.sniff", false)
                .build();
        String[] nodeArr = elasticSearchConfig.getClusterNodes().split(",");
        InetSocketTransportAddress[] socketArr = new InetSocketTransportAddress[nodeArr.length];
        for (int i = 0; i < socketArr.length; i++) {
            if (!StringUtils.isEmpty(nodeArr[i])) {
                String[] nodeInfo = nodeArr[i].split(":");
                socketArr[i] = new InetSocketTransportAddress(new InetSocketAddress(nodeInfo[0], new Integer(nodeInfo[1])));
            }
        }
        return TransportClient.builder().settings(settings).build().addTransportAddresses(socketArr);
    }
    /**
     * 1.TransportClient本身支持多线程的数据请求
     * 2.移除多个TransportClient的线程池支持,减少Socket链接
     * 3.基于多重检查的单例模式,兼顾安全和效率
     * 4.为提高效率,使用完毕后请勿进行 transportClient.close() 的关闭操作
     * @return
     */
    public TransportClient getClient() {
        if (transportClient != null) {
            if (transportClient.connectedNodes().isEmpty()) {
                synchronized (TransportClient.class) {
                    if (transportClient.connectedNodes().isEmpty()) {
                        transportClient = getTransportClient();
                    }
                }
            }
            return transportClient;
        }
        synchronized (TransportClient.class) {
            if (null == transportClient) {
                transportClient = getTransportClient();
            }
        }
        return transportClient;
    }
    public DruidDataSource getDruidDataSource() throws Exception {
        Properties properties = new Properties();
        properties.put("url", "jdbc:elasticsearch://" + elasticSearchConfig.getClusterNodes() + "/");
        DruidDataSource druidDataSource = (DruidDataSource) ElasticSearchDruidDataSourceFactory
                .createDataSource(properties);
        druidDataSource.setInitialSize(1);
        return druidDataSource;
    }
}

+ 780 - 0
common/common-data-elasticsearch/src/main/java/com/yihu/ehr/elasticsearch/ElasticSearchUtil.java

@ -0,0 +1,780 @@
package com.yihu.ehr.elasticsearch;
import com.alibaba.druid.pool.DruidDataSource;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequestBuilder;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.engine.DocumentMissingException;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.InternalCardinality;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.sum.SumBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParseException;
import java.util.*;
/**
 * Util - Es搜索服务
 * Created by progr1mmer on 2017/12/2.
 */
@Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ElasticSearchUtil {
    @Autowired
    private ElasticSearchPool elasticSearchPool;
    /**
     * 创建映射
     *  注意:保存数据之前如果没有创建相应的字
     *  段映射会导致搜索结果不准确
     * @param index
     * @param type
     * @param source
     * @param setting - 该设置根据需要进行配置
     * @throws IOException
     */
    public void mapping (String index, String type, Map<String, Map<String, String>> source, Map<String, Object> setting) throws IOException{
        TransportClient transportClient = elasticSearchPool.getClient();
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("properties");
        for (String field : source.keySet()) {
            xContentBuilder.startObject(field);
            Map<String, String> propsMap = source.get(field);
            for (String prop : propsMap.keySet()) {
                xContentBuilder.field(prop, propsMap.get(prop));
            }
            xContentBuilder.endObject();
        }
        xContentBuilder.endObject().endObject();
        CreateIndexRequestBuilder createIndexRequestBuilder = transportClient.admin().indices().prepareCreate(index);
        createIndexRequestBuilder.addMapping(type, xContentBuilder);
        /*Map<String, Object> settingSource = new HashMap<>();
        settingSource.put("index.translog.flush_threshold_size", "1g"); //log文件大小
        settingSource.put("index.translog.flush_threshold_ops", "100000"); //flush触发次数
        settingSource.put("index.translog.durability", "async"); //异步更新
        settingSource.put("index.refresh_interval", "30s"); //刷新间隔
        settingSource.put("index.number_of_replicas", 1); //副本数
        settingSource.put("index.number_of_shards", 3); //分片数
        createIndexRequestBuilder.setSettings(settingSource);*/
        if (setting != null && !setting.isEmpty()) {
            createIndexRequestBuilder.setSettings(setting);
        }
        createIndexRequestBuilder.get();
    }
    /**
     * 移除索引 - 整个移除
     * @param index
     */
    public void remove (String index){
        TransportClient transportClient = elasticSearchPool.getClient();
        DeleteIndexRequestBuilder deleteIndexRequestBuilder = transportClient.admin().indices().prepareDelete(index);
        deleteIndexRequestBuilder.get();
    }
    /**
     * 添加数据
     * @param index
     * @param type
     * @param source
     * @return
     * @throws ParseException
     */
    public Map<String, Object> index (String index, String type, Map<String, Object> source) throws ParseException{
        TransportClient transportClient = elasticSearchPool.getClient();
        String _id = (String) source.remove("_id");
        if (StringUtils.isEmpty(_id)) {
            IndexResponse response = transportClient.prepareIndex(index, type).setSource(source).get();
            source.put("_id", response.getId());
        } else {
            IndexResponse response = transportClient.prepareIndex(index, type, _id).setSource(source).get();
            source.put("_id", response.getId());
        }
        return source;
    }
    /**
     * 批量添加数据 - 效率高
     * @param index
     * @param type
     * @param source
     * @throws ParseException
     */
    public void bulkIndex (String index, String type, List<Map<String, Object>> source) throws ParseException{
        if (source.size() > 0) {
            TransportClient transportClient = elasticSearchPool.getClient();
            BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
            source.forEach(item -> {
                String _id = (String) item.remove("_id");
                if (StringUtils.isEmpty(_id)) {
                    bulkRequestBuilder.add(transportClient.prepareIndex(index, type).setSource(item));
                } else {
                    bulkRequestBuilder.add(transportClient.prepareIndex(index, type, _id).setSource(item));
                }
            });
            bulkRequestBuilder.get();
        }
    }
    /**
     * 删除数据
     * @param index
     * @param type
     * @param id
     */
    public void delete (String index, String type, String id) {
        TransportClient transportClient = elasticSearchPool.getClient();
        transportClient.prepareDelete(index, type, id).get();
    }
    /**
     * 批量删除数据
     * @param index
     * @param type
     * @param idArr
     */
    public void bulkDelete (String index, String type, String [] idArr) {
        if (idArr.length > 0) {
            TransportClient transportClient = elasticSearchPool.getClient();
            BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
            for (String id : idArr) {
                bulkRequestBuilder.add(transportClient.prepareDelete(index, type, id));
            }
            bulkRequestBuilder.get();
        }
    }
    /**
     * 根据字段批量删除数据
     * @param index
     * @param type
     * @param field
     * @param value
     */
    public void deleteByField(String index, String type, String field, Object value) {
        deleteByFilter(index, type, field + "=" + value);
    }
    /**
     * 根据条件批量删除数据
     * @param index
     * @param type
     * @param filters
     */
    public void deleteByFilter(String index, String type, String filters) {
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        deleteByFilter(index, type, queryBuilder);
    }
    /**
     * 根据条件批量删除数据
     * @param index
     * @param type
     * @param queryBuilder
     */
    public void deleteByFilter(String index, String type, QueryBuilder queryBuilder) {
        long count = count(index, type, queryBuilder);
        long page = count/10000 == 0 ? 1 :count/10000 +1;
        for (long i =0;i<page;i++) {
            List<String> idList = getIds(index, type, queryBuilder);
            if (idList.size() > 0) {
                TransportClient transportClient = elasticSearchPool.getClient();
                String[] idArr = new String[idList.size()];
                idArr = idList.toArray(idArr);
                BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
                for (String id : idArr) {
                    bulkRequestBuilder.add(transportClient.prepareDelete(index, type, id));
                }
                bulkRequestBuilder.get();
            }
        }
    }
    /**
     * 更新数据 - 返回最新文档
     * @param index
     * @param type
     * @param id
     * @param source
     * @return
     * @throws DocumentMissingException
     */
    public Map<String, Object> update(String index, String type, String id, Map<String, Object> source) throws DocumentMissingException {
        TransportClient transportClient = elasticSearchPool.getClient();
        source.remove("_id");
        transportClient.prepareUpdate(index, type, id).setDoc(source).setRetryOnConflict(5).get();
        return findById(index, type, id);
    }
    /**
     * 更新数据 - 不返回文档
     * @param index
     * @param type
     * @param id
     * @param source
     * @throws DocumentMissingException
     */
    public void voidUpdate (String index, String type, String id, Map<String, Object> source) throws DocumentMissingException {
        TransportClient transportClient = elasticSearchPool.getClient();
        source.remove("_id");
        transportClient.prepareUpdate(index, type, id).setDoc(source).setRetryOnConflict(5).get();
    }
    /**
     * 批量更新数据
     * @param index
     * @param type
     * @param source
     * @throws DocumentMissingException
     */
    public void bulkUpdate(String index, String type, List<Map<String, Object>> source) throws DocumentMissingException {
        if (source.size() > 0) {
            TransportClient transportClient = elasticSearchPool.getClient();
            BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
            source.forEach(item -> {
                String _id = (String)item.remove("_id");
                if (!StringUtils.isEmpty(_id)) {
                    bulkRequestBuilder.add(transportClient.prepareUpdate(index, type, _id).setDoc(item).setRetryOnConflict(5));
                }
            });
            bulkRequestBuilder.get();
        }
    }
    /**
     * 根据ID查找数据
     * @param index
     * @param type
     * @param id
     * @return
     */
    public Map<String, Object> findById(String index, String type, String id) {
        TransportClient transportClient = elasticSearchPool.getClient();
        GetRequest getRequest = new GetRequest(index, type, id);
        GetResponse response = transportClient.get(getRequest).actionGet();
        Map<String, Object> source = response.getSource();
        if (source != null) {
            source.put("_id", response.getId());
        }
        return source;
    }
    /**
     * 根据字段查找数据
     * @param index
     * @param type
     * @param field
     * @param value
     * @return
     */
    public List<Map<String, Object>> findByField(String index, String type, String field, Object value) {
        return list(index, type, field + "=" + value);
    }
    /**
     * 获取文档列表
     * @param index
     * @param type
     * @param filters
     * @return
     */
    public List<Map<String, Object>> list(String index, String type, String filters) {
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        return list(index, type, queryBuilder);
    }
    /**
     * 获取文档列表
     * @param index
     * @param type
     * @param queryBuilder
     * @return
     */
    public List<Map<String, Object>> list(String index, String type, QueryBuilder queryBuilder) {
        int size = (int)count(index, type, queryBuilder);
        SearchRequestBuilder builder = searchRequestBuilder(index, type, queryBuilder, null, 0, size);
        SearchResponse response = builder.get();
        SearchHits hits = response.getHits();
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        for (SearchHit hit : hits.getHits()) {
            Map<String, Object> source = hit.getSource();
            source.put("_id", hit.getId());
            resultList.add(source);
        }
        return resultList;
    }
    /**
     * 获取文档分页
     * @param index
     * @param type
     * @param filters
     * @param page
     * @param size
     * @return
     */
    public Page<Map<String, Object>> page(String index, String type, String filters, int page, int size) {
        return page(index, type, filters, null, page, size);
    }
    /**
     * 获取文档分页
     * @param index
     * @param type
     * @param filters
     * @param sorts
     * @param page
     * @param size
     * @return
     */
    public Page<Map<String, Object>> pageBySort(String index, String type, String filters, String sorts, int page, int size) {
        return page(index, type, filters, sorts, page, size);
    }
    /**
     * 获取分档分页 - 带分页功能
     * @param index
     * @param type
     * @param filters
     * @param sorts
     * @param page
     * @param size
     * @return
     */
    public Page<Map<String, Object>> page(String index, String type, String filters, String sorts, int page, int size) {
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        List<SortBuilder> sortBuilders = getSortBuilder(sorts);
        return page(index, type, queryBuilder, sortBuilders, page, size);
    }
    /**
     * 获取分档分页 - 带分页功能
     * @param index
     * @param type
     * @param queryBuilder
     * @param sortBuilders
     * @param page
     * @param size
     * @return
     */
    public Page<Map<String, Object>> page(String index, String type, QueryBuilder queryBuilder, List<SortBuilder> sortBuilders, int page, int size) {
        SearchRequestBuilder builder = searchRequestBuilder(index, type, queryBuilder, sortBuilders, (page - 1) * size, size);
        SearchResponse response = builder.get();
        SearchHits hits = response.getHits();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            Map<String, Object> source = hit.getSource();
            source.put("_id", hit.getId());
            resultList.add(source);
        }
        PageRequest pageRequest = PageRequest.of(page-1,size);
        return new PageImpl<>(resultList, pageRequest, hits.totalHits());
    }
    /**
     * 获取ID列表
     * @param index
     * @param type
     * @param filters
     * @return
     */
    public List<String> getIds (String index, String type, String filters){
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        return getIds(index, type, queryBuilder);
    }
    /**
     * 获取ID列表
     * @param index
     * @param type
     * @param queryBuilder
     * 最多只能一万条
     * @return
     */
    public List<String> getIds (String index, String type, QueryBuilder queryBuilder) {
        int size = (int)count(index, type, queryBuilder);
        size = size > 10000 ? 10000:size;
        SearchRequestBuilder builder = searchRequestBuilder(index, type, queryBuilder, null, 0, size);
        SearchResponse response = builder.get();
        SearchHits hits = response.getHits();
        List<String> resultList = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            resultList.add(hit.getId());
        }
        return resultList;
    }
    /**
     * 获取文档数
     * @param index
     * @param type
     * @param filters
     * @return
     */
    public long count(String index, String type, String filters) {
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        return count(index, type, queryBuilder);
    }
    /**
     * 获取文档数
     * @param index
     * @param type
     * @param queryBuilder
     * @return
     */
    public long count(String index, String type, QueryBuilder queryBuilder) {
        SearchRequestBuilder builder = searchRequestBuilder(index, type, queryBuilder, null, null, null);
        return builder.get().getHits().totalHits();
    }
    /**
     * 根据SQL查找数据
     * @param field
     * @param sql
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> findBySql(List<String> field, String sql) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        DruidDataSource druidDataSource = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            druidDataSource = elasticSearchPool.getDruidDataSource();
            connection = druidDataSource.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Map<String, Object> rowData = new HashMap<>();
                for (String _field : field) {
                    rowData.put(_field, resultSet.getObject(_field));
                }
                list.add(rowData);
            }
            return list;
        } catch (Exception e) {
            if (!"Error".equals(e.getMessage())){
                e.printStackTrace();
            }
            return new ArrayList<>();
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
            if (druidDataSource != null) {
                druidDataSource.close();
            }
        }
    }
    /**
     * 根据SQL查找数据
     * @param sql
     * @return
     * @throws Exception
     */
    public ResultSet findBySql(String sql) throws Exception {
        DruidDataSource druidDataSource = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            druidDataSource = elasticSearchPool.getDruidDataSource();
            connection = druidDataSource.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            return resultSet;
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
            if (druidDataSource != null) {
                druidDataSource.close();
            }
        }
    }
    /**
     * 根据日期分组
     * @param index
     * @param type
     * @param filters
     * @param start
     * @param end
     * @param field
     * @param interval
     * @param format
     * @return
     */
    public Map<String, Long> dateHistogram(String index, String type, String filters, Date start, Date end, String field, DateHistogramInterval interval, String format) {
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        SearchRequestBuilder builder = searchRequestBuilder(index, type, queryBuilder, null, 0, 0);
        DateHistogramBuilder dateHistogramBuilder = new DateHistogramBuilder(index + "-" + field);
        dateHistogramBuilder.field(field);
        dateHistogramBuilder.interval(interval);
        if (!StringUtils.isEmpty(format)) {
            dateHistogramBuilder.format(format);
        }
        dateHistogramBuilder.minDocCount(0);
        dateHistogramBuilder.extendedBounds(start.getTime(), end.getTime());
        builder.addAggregation(dateHistogramBuilder);
        SearchResponse response = builder.get();
        Histogram histogram = response.getAggregations().get(index + "-" + field);
        Map<String, Long> temp = new HashMap<>();
        histogram.getBuckets().forEach(item -> temp.put(item.getKeyAsString(), item.getDocCount()));
        return temp;
    }
    /**
     * 查询去重数量
     * @param index
     * @param type
     * @param filters
     * @param filed
     * @return
     */
    public int cardinality(String index, String type, String filters, String filed){
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        SearchRequestBuilder builder = searchRequestBuilder(index, type, queryBuilder, null, 0, 0);
        CardinalityBuilder cardinality = AggregationBuilders.cardinality("cardinality").field(filed);
        builder.addAggregation(cardinality);
        SearchResponse response = builder.get();
        InternalCardinality internalCard = response.getAggregations().get("cardinality");
        return new Double(internalCard.getProperty("value").toString()).intValue();
    }
    /**
     * 分组统计
     * @param index
     * @param type
     * @param filters
     * @param groupField
     * @return
     */
    public Map<String, Long> countByGroup(String index, String type, String filters, String groupField) {
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        SearchRequestBuilder builder = searchRequestBuilder(index, type, queryBuilder, null, null, null);
        AbstractAggregationBuilder aggregation = AggregationBuilders.terms("count").field(groupField);
        builder.addAggregation(aggregation);
        SearchResponse response = builder.get();
        Terms terms = response.getAggregations().get("count");
        List<Terms.Bucket> buckets = terms.getBuckets();
        Map<String, Long> groupMap = new HashMap<>();
        for (Terms.Bucket bucket : buckets) {
            //System.out.println(bucket.getKey()+"----"+bucket.getDocCount());
            groupMap.put(bucket.getKey().toString(), bucket.getDocCount());
        }
        return groupMap;
    }
    /**
     * 分组求和
     * @param index
     * @param type
     * @param filters
     * @param sumField
     * @param groupField
     * @return
     */
    public Map<String, Double> sumByGroup(String index, String type, String filters, String sumField, String groupField) {
        QueryBuilder queryBuilder = getQueryBuilder(filters);
        SearchRequestBuilder builder = searchRequestBuilder(index, type, queryBuilder, null, null, null);
        TermsBuilder aggregation = AggregationBuilders.terms("sum_query").field(groupField);
        SumBuilder sumBuilder= AggregationBuilders.sum("sum_row").field(sumField);
        aggregation.subAggregation(sumBuilder);
        builder.addAggregation(aggregation);
        SearchResponse response = builder.get();
        Terms terms = response.getAggregations().get("sum_query");
        List<Terms.Bucket> buckets = terms.getBuckets();
        Map<String, Double> groupMap = new HashMap<>();
        for (Terms.Bucket bucket : buckets){
            Sum sum2 = bucket.getAggregations().get("sum_row");
            groupMap.put(bucket.getKey().toString(), sum2.getValue());
        }
        return groupMap;
    }
    /**
     * 获取基础请求生成器
     * @param index
     * @param type
     * @param queryBuilder
     * @param sortBuilders
     * @return
     */
    public SearchRequestBuilder searchRequestBuilder(String index, String type, QueryBuilder queryBuilder, List<SortBuilder> sortBuilders, Integer from, Integer size) {
        TransportClient transportClient = elasticSearchPool.getClient();
        SearchRequestBuilder builder = transportClient.prepareSearch(index);
        builder.setTypes(type);
        builder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
        builder.setQuery(queryBuilder);
        builder.setExplain(true);
        if (sortBuilders != null) {
            sortBuilders.forEach(item -> builder.addSort(item));
        }
        if (from != null) {
            builder.setFrom(from);
        }
        if (size != null) {
            builder.setSize(size);
        }
        return builder;
    }
    /**
     * 排序语句转换
     * @param sorts
     * @return
     */
    public List<SortBuilder> getSortBuilder(String sorts) {
        List<SortBuilder> sortBuilderList = new ArrayList<>();
        if (StringUtils.isEmpty(sorts)) {
            return sortBuilderList;
        }
        String [] sortArr = sorts.split(";");
        for (String sort : sortArr) {
            String operator = sort.substring(0, 1);
            SortBuilder sortBuilder = new FieldSortBuilder(sort.substring(1));
            if ("-".equalsIgnoreCase(operator.trim())) {
                sortBuilder.order(SortOrder.DESC);
            } else if ("+".equalsIgnoreCase(operator.trim())) {
                sortBuilder.order(SortOrder.ASC);
            } else {
                sortBuilder.order(SortOrder.DESC);
            }
            sortBuilderList.add(sortBuilder);
        }
        return sortBuilderList;
    }
    /**
     * 查询语句转换
     * @param filters
     * @return
     */
    public QueryBuilder getQueryBuilder(String filters) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isEmpty(filters)) {
            return boolQueryBuilder;
        }
        String [] filterArr = filters.split(";");
        for (String filter : filterArr) {
            if (filter.contains("||")){
                String [] fields = filter.split("\\|\\|");
                BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
                for (String filed : fields) {
                    String [] condition = filed.split("=");
                    if ("null".equals(condition[1])) {
                        condition[1] ="";
                    }
                    queryBuilder.should(QueryBuilders.termQuery(condition[0], condition[1]));
                }
                boolQueryBuilder.must(queryBuilder);
            } else if (filter.contains("?")) {
                String [] condition = filter.split("\\?");
                if ("null".equals(condition[1])) {
                    condition[1] ="";
                }
                MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchPhraseQuery(condition[0], condition[1]);
                boolQueryBuilder.must(matchQueryBuilder);
            } else if (filter.contains("<>")) {
                String [] condition = filter.split("<>");
                if (condition[1].contains(",")) {
                    String [] inCondition = condition[1].split(",");
                    TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery(condition[0], inCondition);
                    boolQueryBuilder.mustNot(termsQueryBuilder);
                } else {
                    if ("null".equals(condition[1])) {
                        condition[1] ="";
                    }
                    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(condition[0], condition[1]);
                    boolQueryBuilder.mustNot(termQueryBuilder);
                }
            } else if (filter.contains(">=")) {
                String [] condition = filter.split(">=");
                RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition[0]);
                rangeQueryBuilder.gte(condition[1]);
                boolQueryBuilder.must(rangeQueryBuilder);
            } else if (filter.contains(">")) {
                String [] condition = filter.split(">");
                RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition[0]);
                rangeQueryBuilder.gt(condition[1]);
                boolQueryBuilder.must(rangeQueryBuilder);
            } else if (filter.contains("<=")) {
                String [] condition = filter.split("<=");
                RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition[0]);
                rangeQueryBuilder.lte(condition[1]);
                boolQueryBuilder.must(rangeQueryBuilder);
            } else if (filter.contains("<")) {
                String [] condition = filter.split("<");
                RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition[0]);
                rangeQueryBuilder.lt(condition[1]);
                boolQueryBuilder.must(rangeQueryBuilder);
            } else if (filter.contains("=")) {
                String [] condition = filter.split("=");
                if (condition[1].contains(",")) {
                    String [] inCondition = condition[1].split(",");
                    TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery(condition[0], inCondition);
                    boolQueryBuilder.must(termsQueryBuilder);
                } else {
                    if ("null".equals(condition[1])) {
                        condition[1] = "";
                    }
                    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(condition[0], condition[1]);
                    boolQueryBuilder.must(termQueryBuilder);
                }
            }
        }
        return boolQueryBuilder;
    }
}

+ 45 - 0
common/common-data-elasticsearch/src/main/java/com/yihu/ehr/elasticsearch/config/ElasticSearchConfig.java

@ -0,0 +1,45 @@
package com.yihu.ehr.elasticsearch.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
 * Created by progr1mmer on 2017/12/1.
 */
@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
public class ElasticSearchConfig {
    // 集群名称
    private String clusterName;
    // 节点
    private String clusterNodes;
    public String getClusterName() {
        return clusterName;
    }
    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }
    public String getClusterNodes() {
        return clusterNodes;
    }
    public void setClusterNodes(String clusterNodes) {
        this.clusterNodes = clusterNodes;
    }
    @PostConstruct
    private void configInfo() {
        StringBuilder info = new StringBuilder("{");
        info.append("\n  elasticsearch.cluster-name = " + clusterName);
        info.append("\n  elasticsearch.cluster-nodes = " + clusterNodes);
        info.append("\n}");
        System.out.println("Elasticsearch.configInfo : " + info.toString());
    }
}

+ 46 - 0
common/common-data-hbase/pom.xml

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>com.yihu.jw</groupId>
        <artifactId>wlyy-lib-parent-pom</artifactId>
        <version>2.4.0</version>
        <relativePath>../../wlyy-lib-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>common-data-hbase</artifactId>
    <version>${project.parent.version}</version>
    <dependencies>
        <!-- true -->
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-hadoop-hbase</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-util</artifactId>
        </dependency>
    </dependencies>
</project>

+ 32 - 0
common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/AbstractHBaseClient.java

@ -0,0 +1,32 @@
package com.yihu.ehr.hbase;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
/**
 * AbstractHBaseClient - 基类
 * @author hzp
 * @created 2017.05.03
 */
public abstract class AbstractHBaseClient {
    @Autowired
    protected HbaseTemplate hbaseTemplate;
    /**
     * 创建连接
     */
    protected Connection getConnection() throws Exception {
        return getConnection(hbaseTemplate);
    }
    /**
     * 创建连接
     */
    protected Connection getConnection(HbaseTemplate hbaseTemplate) throws Exception {
        Connection connection = ConnectionFactory.createConnection(hbaseTemplate.getConfiguration());
        return connection;
    }
}

+ 213 - 0
common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/HBaseAdmin.java

@ -0,0 +1,213 @@
package com.yihu.ehr.hbase;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
 * Service - HBase DDL
 * @author hzp && Progr1mmer
 * @created 2017.05.03
 * @modifey 2017/11/23
 */
@Service
public class HBaseAdmin extends AbstractHBaseClient {
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 判断表是否存在
     * @param tableName
     * @return
     * @throws Exception
     */
    public boolean isTableExists(String tableName) throws Exception {
        Connection connection = null;
        Admin admin = null;
        try {
            connection = getConnection();
            admin = connection.getAdmin();
            return admin.tableExists(TableName.valueOf(tableName));
        }finally {
            if(admin != null) {
                admin.close();
            }
            if(connection != null) {
                connection.close();
            }
        }
    }
    /**
     * 新建表
     * @param tableName
     * @param columnFamilies
     * @throws Exception
     */
    public void createTable(String tableName, String... columnFamilies) throws Exception {
        Connection connection = null;
        Admin admin = null;
        try {
            connection = getConnection();
            admin = connection.getAdmin();
            if (!admin.tableExists(TableName.valueOf(tableName))) {
                HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
                for (String fc : columnFamilies) {
                    tableDescriptor.addFamily(new HColumnDescriptor(fc));
                }
                admin.createTable(tableDescriptor);
            }
        }finally {
            if(admin != null) {
                admin.close();
            }
            if(connection != null) {
                connection.close();
            }
        }
    }
    /**
     * 模糊匹配表名
     * @param regex 表达式
     * @param includeSysTables 是否包含系统表
     * @return
     * @throws Exception
     */
    public List<String> getTableList(String regex, boolean includeSysTables) throws Exception {
        Connection connection = null;
        Admin admin = null;
        List<String> tables = new ArrayList<>();
        try {
            connection = getConnection();
            admin = connection.getAdmin();
            TableName[] tableNames;
            if (regex == null || regex.length() == 0) {
                tableNames = admin.listTableNames();
            } else {
                tableNames = admin.listTableNames(regex, includeSysTables);
            }
            for (TableName tableName : tableNames) {
                tables.add(tableName.getNameAsString());
            }
            return tables;
        }finally {
            if(admin != null) {
                admin.close();
            }
            if(connection != null) {
                connection.close();
            }
        }
    }
    /**
     * 批量清空表数据 (直接删除相关表,再新建)
     * @param tables
     * @throws Exception
     */
    public void cleanTable(List<String> tables) throws Exception {
        Connection connection = null;
        Admin admin = null;
        try {
            connection = getConnection();
            admin = connection.getAdmin();
            for (String tableName : tables) {
                TableName tn = TableName.valueOf(tableName);
                if (admin.tableExists(TableName.valueOf(tableName))) {
                    HTableDescriptor descriptor = admin.getTableDescriptor(tn);
                    admin.disableTable(tn);
                    admin.deleteTable(tn);
                    admin.createTable(descriptor);
                }
                else{
                    System.out.print("not exit table "+tableName+".\r\n");
                }
                /*else{
                    HTableDescriptor descriptor = new HTableDescriptor(tableName);
                    descriptor.addFamily(new HColumnDescriptor("basic"));
                    descriptor.addFamily(new HColumnDescriptor("d"));
                    admin.createTable(descriptor);
                }*/
            }
        } finally {
            if(admin != null) {
                admin.close();
            }
            if(connection != null) {
                connection.close();
            }
        }
    }
    /**
     * 删除表
     * @param tableName
     * @throws Exception
     */
    public void dropTable(String tableName) throws Exception {
        Connection connection = null;
        Admin admin = null;
        try {
            connection = getConnection();
            admin = connection.getAdmin();
            admin.disableTable(TableName.valueOf(tableName));
            admin.deleteTable(TableName.valueOf(tableName));
        } finally {
            if(admin != null) {
                admin.close();
            }
            if(connection != null) {
                connection.close();
            }
        }
    }
    /**
     * 获取表结构
     * @param tableName
     * @return
     * @throws Exception
     */
    public ObjectNode getTableMetaData(String tableName) throws Exception{
        Connection connection = null;
        Admin admin = null;
        try {
            connection = getConnection();
            admin = connection.getAdmin();
            TableName tn = TableName.valueOf(tableName);
            if (admin.tableExists(tn)) {
                ObjectNode objectNode = objectMapper.createObjectNode();
                HTableDescriptor tableDescriptor = admin.getTableDescriptor(tn);
                HColumnDescriptor[] columnDescriptors = tableDescriptor.getColumnFamilies();
                for (int i = 0; i < columnDescriptors.length; ++i) {
                    HColumnDescriptor columnDescriptor = columnDescriptors[i];
                    objectNode.put(Integer.toString(i), Bytes.toString(columnDescriptor.getName()));
                }
                return objectNode;
            }
            return null;
        }finally {
            if(admin != null) {
                admin.close();
            }
            if(connection != null) {
                connection.close();
            }
        }
    }
}

+ 395 - 0
common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/HBaseDao.java

@ -0,0 +1,395 @@
package com.yihu.ehr.hbase;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.RegexStringComparator;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.hbase.RowMapper;
import org.springframework.data.hadoop.hbase.TableCallback;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
/**
 * HBase - DML
 * @Author Progr1mmer
 */
@Service
public class HBaseDao extends AbstractHBaseClient {
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 新增数据 - 多列族
     * @param tableName
     * @param rowKey
     * @param family
     * @throws Exception
     */
    public void add(String tableName , String rowKey, Map<String, Map<String, String>> family) {
        hbaseTemplate.execute(tableName, new TableCallback<Void>() {
            @Override
            public Void doInTable(HTableInterface table) throws Throwable {
                Put p = new Put(rowKey.getBytes());
                for (String familyName : family.keySet()) {
                    Map<String, String> map = family.get(familyName);
                    for (String qualifier : map.keySet()) {
                        String value = map.get(qualifier);
                        p.addColumn(familyName.getBytes(), qualifier.getBytes(), value.getBytes());
                    }
                }
                table.put(p);
                return null;
            }
        });
    }
    /**
     * 新增数据 - 单列族
     * @param tableName
     * @param rowKey
     * @param family
     * @param columns
     * @param values
     */
    public void add(String tableName, String rowKey, String family, Object[] columns, Object[] values) {
        hbaseTemplate.execute(tableName, new TableCallback<Void>() {
            @Override
            public Void doInTable(HTableInterface table) throws Throwable {
                Put put = new Put(Bytes.toBytes(rowKey));
                for (int j = 0; j < columns.length; j++) {
                    //为空字段不保存
                    if (values[j] != null) {
                        String column = String.valueOf(columns[j]);
                        String value = String.valueOf(values[j]);
                        put.addColumn(Bytes.toBytes(family), Bytes.toBytes(column), Bytes.toBytes(value));
                    }
                }
                table.put(put);
                return null;
            }
        });
    }
    /**
     * 删除记录
     * @param tableName
     * @param rowKey
     */
    public void delete(String tableName, String rowKey)  {
        hbaseTemplate.execute(tableName, new TableCallback<Void>() {
            @Override
            public Void doInTable(HTableInterface table) throws Throwable {
                Delete d = new Delete(rowKey.getBytes());
                table.delete(d);
                return null;
            }
        });
    }
    /**
     * 批量删除数据
     * @param tableName
     * @param rowKeys
     * @return
     * @throws Exception
     */
    public Object[] deleteBatch(String tableName, String[] rowKeys) {
        return hbaseTemplate.execute(tableName, new TableCallback<Object[]>() {
            @Override
            public Object[] doInTable(HTableInterface table) throws Throwable {
                List<Delete> deletes = new ArrayList<>(rowKeys.length);
                for (String rowKey : rowKeys) {
                    Delete delete = new Delete(Bytes.toBytes(rowKey));
                    deletes.add(delete);
                }
                Object[] results = new Object[deletes.size()];
                table.batch(deletes, results);
                return results;
            }
        });
    }
    /**
     * 删除列族
     * @param tableName
     * @param rowKey
     * @param familyName
     * @throws Exception
     */
    public void deleteFamily(String tableName, String rowKey, String familyName) throws Exception {
        hbaseTemplate.delete(tableName, rowKey, familyName);
    }
    /**
     * 删除某列
     * @param tableName
     * @param rowKey
     * @param familyName
     * @param columnName
     * @throws Exception
     */
    public void deleteColumn(String tableName, String rowKey, String familyName, String columnName) throws Exception {
        hbaseTemplate.delete(tableName, rowKey, familyName, columnName);
    }
    /**
     * 修改某行某列值
     */
    public void put(String tableName, String rowKey, String familyName, String qualifier, String value) throws Exception {
        hbaseTemplate.put(tableName, rowKey, familyName, qualifier, value.getBytes());
    }
    /**
     * 模糊匹配rowKey
     * @param tableName 表名
     * @param rowKeyRegEx 表达式
     * @return
     * @throws Exception
     */
    public String[] findRowKeys(String tableName, String startRow, String stopRow, String rowKeyRegEx) throws Exception {
        Scan scan = new Scan();
        scan.addFamily(Bytes.toBytes("basic"));
        scan.setStartRow(startRow.getBytes());
        scan.setStopRow(stopRow.getBytes());
        scan.setFilter(new RowFilter(CompareFilter.CompareOp.EQUAL, new RegexStringComparator(rowKeyRegEx)));
        List<String> list = new LinkedList<>();
        hbaseTemplate.find(tableName, scan, new RowMapper<Void>() {
            @Override
            public Void mapRow(Result result, int rowNum) throws Exception {
                list.add(Bytes.toString(result.getRow()));
                return null;
            }
        });
        return list.toArray(new String[list.size()]);
    }
    /**
     * 表总条数
     * @param tableName
     * @return
     * @throws Exception
     */
    public Integer count(String tableName) throws Exception {
        Scan scan = new Scan();
        scan.addFamily(Bytes.toBytes("basic"));
        scan.setFilter(new RowFilter(CompareFilter.CompareOp.EQUAL, new RegexStringComparator("^")));
        List<String> list = new LinkedList<>();
        hbaseTemplate.find(tableName, scan, new RowMapper<Void>() {
            @Override
            public Void mapRow(Result result, int rowNum) throws Exception {
                list.add(Bytes.toString(result.getRow()));
                return null;
            }
        });
        return list.size();
    }
    /**
     * 根据rowKey获取一条记录
     * @param tableName
     * @param rowKey
     * @return 字符串
     */
    public String get(String tableName, String rowKey) {
        return hbaseTemplate.get(tableName, rowKey, new RowMapper<String>() {
            @Override
            public String mapRow(Result result, int rowNum) throws Exception {
                if(!result.isEmpty()) {
                    List<Cell> ceList = result.listCells();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("rowkey", rowKey);
                    for (Cell cell : ceList) {
                        // 默认不加列族
                        // Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()) +"_"
                        map.put(Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()),
                                Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
                    }
                    return objectMapper.writeValueAsString(map);
                }
                else{
                    return "";
                }
            }
        });
    }
    /**
     * 通过rowKey获取某行数据
     * @param tableName
     * @param rowKey
     * @return Map
     */
    public Map<String, Object> getResultMap(String tableName, String rowKey) {
        return hbaseTemplate.get(tableName, rowKey, new RowMapper<Map<String, Object>>() {
            @Override
            public Map<String, Object> mapRow(Result result, int rowNum) throws Exception {
                if(!result.isEmpty()) {
                    List<Cell> ceList = result.listCells();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("rowkey", rowKey);
                    for (Cell cell : ceList) {
                        //默认不加列族
                        // Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()) +"_"
                        map.put(Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()),
                                Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
                    }
                    return map;
                }else {
                    return null;
                }
            }
        });
    }
    /**
     * 通过rowKey获取某行数据
     * @param tableName
     * @param rowKey
     * @return
     * @throws Exception
     */
    public Result getResult(String tableName, String rowKey) throws Exception {
        return hbaseTemplate.get(tableName, rowKey, new RowMapper<Result>() {
            @Override
            public Result mapRow(Result result, int rowNum) throws Exception {
                return result;
            }
        });
    }
    /**
     * 通过表名和rowKey获取指定列族下的值
     * @param tableName 表名
     * @param rowKey rowKey
     * @param familyName 列族
     * @return
     */
    public Map<String, String> get(String tableName, String rowKey, String familyName) {
        return hbaseTemplate.get(tableName, rowKey, familyName, new RowMapper<Map<String, String>>(){
            @Override
            public Map<String, String> mapRow(Result result, int rowNum) throws Exception {
                Map<String, String> map = new HashMap<>();
                NavigableMap<byte[], byte[]> navigableMaps = result.getFamilyMap(familyName.getBytes());
                if(null != navigableMaps) {
                    for (byte[] key : navigableMaps.keySet()) {
                        String keys = new String(key);
                        String values = new String(navigableMaps.get(key));
                        map.put(keys, values);
                    }
                }
                return map;
            }
        });
    }
    /**
     * 通过表名和rowKey获取指定列族下的列名的值
     * @param tableName 表名
     * @param rowKey rowKey
     * @param familyName 列族
     * @param qualifier 列名
     * @return
     */
    public String get(String tableName, String rowKey, String familyName, String qualifier) {
        return hbaseTemplate.get(tableName, rowKey, familyName, qualifier, new RowMapper<String>(){
            @Override
            public String mapRow(Result result, int rowNum) throws Exception {
                Cell cell = result.getColumnLatestCell(familyName.getBytes(), qualifier.getBytes());
                return new String(CellUtil.cloneValue(cell));
            }
        });
    }
    /**
     * 通过rowKey集合获取指定列名下的多条数据
     * @param tableName 表名
     * @param rowKeys rowKeys
     * @param basicFl basic列族下的列名
     * @param dFl d列族下的列名
     * @return
     * @throws Exception
     */
    public Result[] getResultList(String tableName, List<String> rowKeys, String basicFl, String dFl) {
        return hbaseTemplate.execute(tableName, new TableCallback<Result[]>() {
            @Override
            public Result[] doInTable(HTableInterface table) throws Throwable {
                List<Get> list = new ArrayList<Get>();
                for (String rowKey : rowKeys) {
                    Get get = new Get(Bytes.toBytes(rowKey));
                    if (!StringUtils.isEmpty(basicFl)) {
                        String[] basicArr = basicFl.split(",");
                        for (String basicStr : basicArr) {
                            get.addColumn(Bytes.toBytes("basic"), Bytes.toBytes(basicStr));
                        }
                    }
                    if (!StringUtils.isEmpty(dFl)) {
                        String[] dArr = dFl.split(",");
                        for (String dStr : dArr) {
                            get.addColumn(Bytes.toBytes("d"), Bytes.toBytes(dStr));
                        }
                    }
                    list.add(get);
                }
                return table.get(list);
            }
        });
    }
    /************************************* Bean使用原型模式 ***************************************************************/
    /**
     * 保存数据 原型模式
     */
    public void save(String tableName, TableBundle tableBundle) {
        hbaseTemplate.execute(tableName, new TableCallback<Void>() {
            @Override
            public Void doInTable(HTableInterface table) throws Throwable {
                List<Put> puts = tableBundle.putOperations();
                Object[] results = new Object[puts.size()];
                table.batch(puts, results);
                return null;
            }
        });
    }
    /**
     * 删除数据 原型模式
     */
    public void delete(String tableName, TableBundle tableBundle) {
        hbaseTemplate.execute(tableName, new TableCallback<Object[]>() {
            @Override
            public Object[] doInTable(HTableInterface table) throws Throwable {
                List<Delete> deletes = tableBundle.deleteOperations();
                Object[] results = new Object[deletes.size()];
                table.batch(deletes, results);
                return null;
            }
        });
    }
    /**
     * 查询数据 原型模式
     */
    public Object[] get(String tableName, TableBundle tableBundle) {
        return hbaseTemplate.execute(tableName, new TableCallback<Object[]>() {
            @Override
            public Object[] doInTable(HTableInterface table) throws Throwable {
                List<Get> gets = tableBundle.getOperations();
                Object[] results = new Object[gets.size()];
                table.batch(gets, results);
                if (results.length > 0 && results[0].toString().equals("keyvalues=NONE")) {
                    return null;
                }
                return results;
            }
        });
    }
}

+ 158 - 0
common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/TableBundle.java

@ -0,0 +1,158 @@
package com.yihu.ehr.hbase;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 将HBase中的行,列族,列捆绑成一束。并一次性生成所需要的Get, Put操作。
 * <p>
 * 仅支持单表操作。
 * <p>
 * 虽然支持多种HBase操作,但请注意,一次只能用于一种操作,如:Get,Put,Delete不能混用,
 * 否则将出现难以预料的后果。
 *
 * @author Sand
 * @created 2016.04.27 14:38
 */
public class TableBundle {
    Map<String, Row> rows = new HashMap<>();
    public void addRows(String... rowKeys) {
        for (String rowKey : rowKeys) {
            rows.put(rowKey, null);
        }
    }
    private Row getRow(String rowKey) {
        Row row = rows.get(rowKey);
        if (row == null) {
            row = new Row();
            rows.put(rowKey, row);
        }
        return row;
    }
    public void addFamily(String rowKey, Object family) {
        Row row = getRow(rowKey);
        row.addFamily(family.toString());
    }
    public void addColumns(String rowKey, Object family, String[] columns) {
        Row row = getRow(rowKey);
        row.addColumns(family.toString(), columns);
    }
    public void addValues(String rowKey, Object family, Map<String, String> values) {
        Row row = getRow(rowKey);
        row.addValues(family.toString(), values);
    }
    public void clear() {
        rows.clear();
    }
    public List<Get> getOperations() {
        List<Get> gets = new ArrayList<>(rows.size());
        for (String rowKey : rows.keySet()) {
            Get get = new Get(Bytes.toBytes(rowKey));
            Row row = rows.get(rowKey);
            if (row != null) {
                for (String family : row.getFamilies()) {
                    Set<Object> columns = row.getCells(family);
                    if (CollectionUtils.isEmpty(columns)) {
                        get.addFamily(Bytes.toBytes(family));
                    }
                    for (Object column : columns) {
                        get.addColumn(Bytes.toBytes(family), Bytes.toBytes((String) column));
                    }
                }
            }
            gets.add(get);
        }
        return gets;
    }
    public List<Put> putOperations() {
        List<Put> puts = new ArrayList<>(rows.values().size());
        for (String rowKey : rows.keySet()) {
            Put put = new Put(Bytes.toBytes(rowKey));
            Row row = rows.get(rowKey);
            for (String family : row.getFamilies()) {
                Set<Object> columns = row.getCells(family);
                for (Object column : columns) {
                    Pair<String, String> pair = (Pair<String, String>) column;
                    if (StringUtils.isNotEmpty(pair.getRight())) {
                        put.addColumn(Bytes.toBytes(family),
                                Bytes.toBytes(pair.getLeft()),
                                Bytes.toBytes(pair.getRight()));
                    }
                }
            }
            puts.add(put);
        }
        return puts;
    }
    public List<Delete> deleteOperations() {
        List<Delete> deletes = new ArrayList<>(rows.values().size());
        for (String rowkey : rows.keySet()) {
            Delete delete = new Delete(Bytes.toBytes(rowkey));
            deletes.add(delete);
        }
        return deletes;
    }
    /**
     * HBase中的一行
     */
    public static class Row {
        private Map<String, Set<Object>> cells = new HashMap<>();   // key为family,value为columns
        public void addFamily(String family) {
            cells.put(family, null);
        }
        public void addColumns(String family, String... columns) {
            Set value = getFamily(family);
            for (String column : columns) {
                value.add(column);
            }
        }
        public void addValues(String family, Map<String, String> values) {
            Set value = getFamily(family);
            value.addAll(values.keySet().stream().map(key -> new ImmutablePair<>(key, values.get(key))).collect(Collectors.toList()));
        }
        public Set<String> getFamilies() {
            return cells.keySet();
        }
        public Set<Object> getCells(String family) {
            return cells.get(family);
        }
        private Set<Object> getFamily(String family) {
            Set value = cells.get(family);
            if (value == null) {
                value = new TreeSet<>();
                cells.put(family, value);
            }
            return value;
        }
    }
}

+ 86 - 0
common/common-data-hbase/src/main/java/com/yihu/ehr/hbase/config/HbaseConfig.java

@ -0,0 +1,86 @@
package com.yihu.ehr.hbase.config;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
import javax.annotation.PostConstruct;
import java.util.*;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.11.28 16:26
 * @modified by Progr1mmer 2017/11/23 注释启动连接代码
 */
@Configuration
@ConfigurationProperties(prefix = "hadoop")
public class HbaseConfig{
    private Map<String, String> hbaseProperties = new HashMap<>();
    private User user = new User();
    public Map<String, String> getHbaseProperties(){
        return this.hbaseProperties;
    }
    public void setHbaseProperties(Map<String, String> hbaseProperties) {
        this.hbaseProperties = hbaseProperties;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public class User {
        private String name;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    @PostConstruct
    private void configInfo() {
        StringBuilder info = new StringBuilder("{");
        hbaseProperties.forEach((key, val) -> info.append("\n  hadoop." + key + " = " + val));
        info.append("\n  hadoop.user.name = " + user.getName());
        info.append("\n}");
        System.out.println("Hbase.configInfo : " + info.toString());
    }
    @Bean
    public org.apache.hadoop.conf.Configuration configuration() {
        Set<String> keys = new HashSet<>(hbaseProperties.keySet());
        for (String key : keys){
            String value = hbaseProperties.remove(key);
            key = key.replaceAll("^\\d{1,2}\\.", "");
            hbaseProperties.put(key, value);
        }
        org.apache.hadoop.conf.Configuration configuration = HBaseConfiguration.create();
        hbaseProperties.keySet().stream().filter(key -> hbaseProperties.get(key) != null).forEach(key -> {
            configuration.set(key, hbaseProperties.get(key));
        });
        return configuration;
    }
    @Bean
    public HbaseTemplate hbaseTemplate(org.apache.hadoop.conf.Configuration configuration){
        System.setProperty("HADOOP_USER_NAME", user.getName() != null ? user.getName() : "root");
        HbaseTemplate hbaseTemplate = new HbaseTemplate();
        hbaseTemplate.setConfiguration(configuration);
        return hbaseTemplate;
    }
}

+ 13 - 0
common/common-data-hbase/src/main/resources/hbase-site.xml

@ -0,0 +1,13 @@
<configuration>
    <property>
        <name>hbase.client.retries.number</name>
        <value>3</value>
    </property>
    <property>
        <name>hbase.cluster.distributed</name>
        <value>true</value>
    </property>
    
</configuration>

+ 163 - 0
common/common-data-hbase/src/main/resources/hbase/core-site.xml

@ -0,0 +1,163 @@
  <configuration>
    
    <property>
      <name>fs.defaultFS</name>
      <value>hdfs://dev</value>
    </property>
    
    <property>
      <name>fs.trash.interval</name>
      <value>360</value>
    </property>
    
    <property>
      <name>ha.failover-controller.active-standby-elector.zk.op.retries</name>
      <value>120</value>
    </property>
    
    <property>
      <name>ha.zookeeper.quorum</name>
      <value>node1.hde.h3c.com:2181,node2.hde.h3c.com:2181,node3.hde.h3c.com:2181</value>
    </property>
    
    <property>
      <name>hadoop.http.authentication.simple.anonymous.allowed</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hbase.groups</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hbase.hosts</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hcat.groups</name>
      <value>users</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hcat.hosts</name>
      <value>node2.hde.h3c.com</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hdfs.groups</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hdfs.hosts</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hive.groups</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hive.hosts</name>
      <value>node2.hde.h3c.com</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.HTTP.groups</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.HTTP.hosts</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hue.groups</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.hue.hosts</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.oozie.groups</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.proxyuser.oozie.hosts</name>
      <value>*</value>
    </property>
    
    <property>
      <name>hadoop.security.auth_to_local</name>
      <value>DEFAULT</value>
    </property>
    
    <property>
      <name>hadoop.security.authentication</name>
      <value>simple</value>
    </property>
    
    <property>
      <name>hadoop.security.authorization</name>
      <value>false</value>
    </property>
    
    <property>
      <name>hadoop.security.key.provider.path</name>
      <value></value>
    </property>
    
    <property>
      <name>io.compression.codecs</name>
      <value>org.apache.hadoop.io.compress.GzipCodec,org.apache.hadoop.io.compress.DefaultCodec,org.apache.hadoop.io.compress.SnappyCodec</value>
    </property>
    
    <property>
      <name>io.file.buffer.size</name>
      <value>131072</value>
    </property>
    
    <property>
      <name>io.serializations</name>
      <value>org.apache.hadoop.io.serializer.WritableSerialization</value>
    </property>
    
    <property>
      <name>ipc.client.connect.max.retries</name>
      <value>50</value>
    </property>
    
    <property>
      <name>ipc.client.connection.maxidletime</name>
      <value>30000</value>
    </property>
    
    <property>
      <name>ipc.client.idlethreshold</name>
      <value>8000</value>
    </property>
    
    <property>
      <name>ipc.server.tcpnodelay</name>
      <value>true</value>
    </property>
    
    <property>
      <name>mapreduce.jobtracker.webinterface.trusted</name>
      <value>false</value>
    </property>
    
    <property>
      <name>net.topology.script.file.name</name>
      <value>/etc/hadoop/conf/topology_script.py</value>
    </property>
    
  </configuration>

+ 243 - 0
common/common-data-hbase/src/main/resources/hbase/hbase-site.xml

@ -0,0 +1,243 @@
  <configuration>
    
    <property>
      <name>dfs.domain.socket.path</name>
      <value>/var/lib/hadoop-hdfs/dn_socket</value>
    </property>
    
    <property>
      <name>hbase.bulkload.staging.dir</name>
      <value>/apps/hbase/staging</value>
    </property>
    
    <property>
      <name>hbase.client.keyvalue.maxsize</name>
      <value>1048576</value>
    </property>
    
    <property>
      <name>hbase.client.retries.number</name>
      <value>35</value>
    </property>
    
    <property>
      <name>hbase.client.scanner.caching</name>
      <value>100</value>
    </property>
    
    <property>
      <name>hbase.cluster.distributed</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hbase.coprocessor.master.classes</name>
      <value>org.apache.hadoop.hbase.security.access.AccessController</value>
    </property>
    
    <property>
      <name>hbase.coprocessor.region.classes</name>
      <value>org.apache.hadoop.hbase.security.access.AccessController,org.apache.hadoop.hbase.security.access.SecureBulkLoadEndpoint</value>
    </property>
    
    <property>
      <name>hbase.coprocessor.regionserver.classes</name>
      <value>org.apache.hadoop.hbase.security.access.AccessController</value>
    </property>
    
    <property>
      <name>hbase.defaults.for.version.skip</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hbase.hregion.majorcompaction</name>
      <value>604800000</value>
    </property>
    
    <property>
      <name>hbase.hregion.majorcompaction.jitter</name>
      <value>0.50</value>
    </property>
    
    <property>
      <name>hbase.hregion.max.filesize</name>
      <value>10737418240</value>
    </property>
    
    <property>
      <name>hbase.hregion.memstore.block.multiplier</name>
      <value>4</value>
    </property>
    
    <property>
      <name>hbase.hregion.memstore.flush.size</name>
      <value>134217728</value>
    </property>
    
    <property>
      <name>hbase.hregion.memstore.mslab.enabled</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hbase.hstore.blockingStoreFiles</name>
      <value>10</value>
    </property>
    
    <property>
      <name>hbase.hstore.compaction.max</name>
      <value>10</value>
    </property>
    
    <property>
      <name>hbase.hstore.compactionThreshold</name>
      <value>3</value>
    </property>
    
    <property>
      <name>hbase.local.dir</name>
      <value>${hbase.tmp.dir}/local</value>
    </property>
    
    <property>
      <name>hbase.master.info.bindAddress</name>
      <value>0.0.0.0</value>
    </property>
    
    <property>
      <name>hbase.master.info.port</name>
      <value>16010</value>
    </property>
    
    <property>
      <name>hbase.master.port</name>
      <value>16000</value>
    </property>
    
    <property>
      <name>hbase.regionserver.global.memstore.size</name>
      <value>0.4</value>
    </property>
    
    <property>
      <name>hbase.regionserver.handler.count</name>
      <value>30</value>
    </property>
    
    <property>
      <name>hbase.regionserver.info.port</name>
      <value>16030</value>
    </property>
    
    <property>
      <name>hbase.regionserver.port</name>
      <value>16020</value>
    </property>
    
    <property>
      <name>hbase.regionserver.thrift.http</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hbase.regionserver.wal.codec</name>
      <value>org.apache.hadoop.hbase.regionserver.wal.WALCellCodec</value>
    </property>
    
    <property>
      <name>hbase.replication</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hbase.rootdir</name>
      <value>hdfs://dev/apps/hbase/data</value>
    </property>
    
    <property>
      <name>hbase.rpc.protection</name>
      <value>authentication</value>
    </property>
    
    <property>
      <name>hbase.rpc.timeout</name>
      <value>90000</value>
    </property>
    
    <property>
      <name>hbase.security.authentication</name>
      <value>simple</value>
    </property>
    
    <property>
      <name>hbase.security.authorization</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hbase.superuser</name>
      <value>hbase</value>
    </property>
    
    <property>
      <name>hbase.thrift.support.proxyuser</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hbase.tmp.dir</name>
      <value>/hadoop/hbase</value>
    </property>
    
    <property>
      <name>hbase.zookeeper.property.clientPort</name>
      <value>2181</value>
    </property>
    
    <property>
      <name>hbase.zookeeper.quorum</name>
      <value>node1.hde.h3c.com,node2.hde.h3c.com,node3.hde.h3c.com</value>
    </property>
    
    <property>
      <name>hbase.zookeeper.useMulti</name>
      <value>true</value>
    </property>
    
    <property>
      <name>hfile.block.cache.size</name>
      <value>0.40</value>
    </property>
    
    <property>
      <name>phoenix.query.timeoutMs</name>
      <value>60000</value>
    </property>
    
    <property>
      <name>replication.replicationsource.implementation</name>
      <value>com.ngdata.sep.impl.SepReplicationSource</value>
    </property>
    
    <property>
      <name>replication.source.nb.capacity</name>
      <value>1000</value>
    </property>
    
    <property>
      <name>replication.source.ratio</name>
      <value>1</value>
    </property>
    
    <property>
      <name>zookeeper.session.timeout</name>
      <value>90000</value>
    </property>
    
    <property>
      <name>zookeeper.znode.parent</name>
      <value>/hbase-unsecure</value>
    </property>
    
  </configuration>

+ 348 - 0
common/common-data-hbase/src/main/resources/hbase/hdfs-site.xml

@ -0,0 +1,348 @@
  <configuration>
    
    <property>
      <name>dfs.block.access.token.enable</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.blockreport.initialDelay</name>
      <value>120</value>
    </property>
    
    <property>
      <name>dfs.blocksize</name>
      <value>134217728</value>
    </property>
    
    <property>
      <name>dfs.client.failover.proxy.provider.dev</name>
      <value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
    </property>
    
    <property>
      <name>dfs.client.read.shortcircuit</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.client.read.shortcircuit.streams.cache.size</name>
      <value>4096</value>
    </property>
    
    <property>
      <name>dfs.client.retry.policy.enabled</name>
      <value>false</value>
    </property>
    
    <property>
      <name>dfs.cluster.administrators</name>
      <value> hdfs</value>
    </property>
    
    <property>
      <name>dfs.content-summary.limit</name>
      <value>5000</value>
    </property>
    
    <property>
      <name>dfs.datanode.address</name>
      <value>0.0.0.0:50010</value>
    </property>
    
    <property>
      <name>dfs.datanode.balance.bandwidthPerSec</name>
      <value>6250000</value>
    </property>
    
    <property>
      <name>dfs.datanode.data.dir</name>
      <value>/opt/hadoop/hdfs/data</value>
    </property>
    
    <property>
      <name>dfs.datanode.data.dir.perm</name>
      <value>750</value>
    </property>
    
    <property>
      <name>dfs.datanode.du.reserved</name>
      <value>1073741824</value>
    </property>
    
    <property>
      <name>dfs.datanode.failed.volumes.tolerated</name>
      <value>0</value>
    </property>
    
    <property>
      <name>dfs.datanode.http.address</name>
      <value>0.0.0.0:50075</value>
    </property>
    
    <property>
      <name>dfs.datanode.https.address</name>
      <value>0.0.0.0:50475</value>
    </property>
    
    <property>
      <name>dfs.datanode.ipc.address</name>
      <value>0.0.0.0:8010</value>
    </property>
    
    <property>
      <name>dfs.datanode.max.transfer.threads</name>
      <value>4096</value>
    </property>
    
    <property>
      <name>dfs.domain.socket.path</name>
      <value>/var/lib/hadoop-hdfs/dn_socket</value>
    </property>
    
    <property>
      <name>dfs.encrypt.data.transfer.cipher.suites</name>
      <value>AES/CTR/NoPadding</value>
    </property>
    
    <property>
      <name>dfs.encryption.key.provider.uri</name>
      <value></value>
    </property>
    
    <property>
      <name>dfs.ha.automatic-failover.enabled</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.ha.fencing.methods</name>
      <value>shell(/bin/true)</value>
    </property>
    
    <property>
      <name>dfs.ha.namenodes.dev</name>
      <value>nn1,nn2</value>
    </property>
    
    <property>
      <name>dfs.heartbeat.interval</name>
      <value>3</value>
    </property>
    
    <property>
      <name>dfs.hosts.exclude</name>
      <value>/etc/hadoop/conf/dfs.exclude</value>
    </property>
    
    <property>
      <name>dfs.http.policy</name>
      <value>HTTP_ONLY</value>
    </property>
    
    <property>
      <name>dfs.https.port</name>
      <value>50470</value>
    </property>
    
    <property>
      <name>dfs.journalnode.edits.dir</name>
      <value>/hadoop/hdfs/journal</value>
    </property>
    
    <property>
      <name>dfs.journalnode.http-address</name>
      <value>0.0.0.0:8480</value>
    </property>
    
    <property>
      <name>dfs.journalnode.https-address</name>
      <value>0.0.0.0:8481</value>
    </property>
    
    <property>
      <name>dfs.namenode.accesstime.precision</name>
      <value>0</value>
    </property>
    
    <property>
      <name>dfs.namenode.audit.log.async</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.namenode.avoid.read.stale.datanode</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.namenode.avoid.write.stale.datanode</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.namenode.checkpoint.dir</name>
      <value>/opt/hadoop/hdfs/namesecondary</value>
    </property>
    
    <property>
      <name>dfs.namenode.checkpoint.edits.dir</name>
      <value>${dfs.namenode.checkpoint.dir}</value>
    </property>
    
    <property>
      <name>dfs.namenode.checkpoint.period</name>
      <value>21600</value>
    </property>
    
    <property>
      <name>dfs.namenode.checkpoint.txns</name>
      <value>1000000</value>
    </property>
    
    <property>
      <name>dfs.namenode.fslock.fair</name>
      <value>false</value>
    </property>
    
    <property>
      <name>dfs.namenode.handler.count</name>
      <value>100</value>
    </property>
    
    <property>
      <name>dfs.namenode.http-address</name>
      <value>node1.hde.h3c.com:50070</value>
    </property>
    
    <property>
      <name>dfs.namenode.http-address.dev.nn1</name>
      <value>node1.hde.h3c.com:50070</value>
    </property>
    
    <property>
      <name>dfs.namenode.http-address.dev.nn2</name>
      <value>node2.hde.h3c.com:50070</value>
    </property>
    
    <property>
      <name>dfs.namenode.https-address</name>
      <value>node1.hde.h3c.com:50470</value>
    </property>
    
    <property>
      <name>dfs.namenode.https-address.dev.nn1</name>
      <value>node1.hde.h3c.com:50470</value>
    </property>
    
    <property>
      <name>dfs.namenode.https-address.dev.nn2</name>
      <value>node2.hde.h3c.com:50470</value>
    </property>
    
    <property>
      <name>dfs.namenode.name.dir</name>
      <value>/opt/hadoop/hdfs/namenode</value>
    </property>
    
    <property>
      <name>dfs.namenode.name.dir.restore</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.namenode.rpc-address</name>
      <value>node1.hde.h3c.com:8020</value>
    </property>
    
    <property>
      <name>dfs.namenode.rpc-address.dev.nn1</name>
      <value>node1.hde.h3c.com:8020</value>
    </property>
    
    <property>
      <name>dfs.namenode.rpc-address.dev.nn2</name>
      <value>node2.hde.h3c.com:8020</value>
    </property>
    
    <property>
      <name>dfs.namenode.safemode.threshold-pct</name>
      <value>0.99</value>
    </property>
    
    <property>
      <name>dfs.namenode.secondary.http-address</name>
      <value>localhost:50090</value>
    </property>
    
    <property>
      <name>dfs.namenode.shared.edits.dir</name>
      <value>qjournal://node1.hde.h3c.com:8485;node2.hde.h3c.com:8485;node3.hde.h3c.com:8485/dev</value>
    </property>
    
    <property>
      <name>dfs.namenode.stale.datanode.interval</name>
      <value>30000</value>
    </property>
    
    <property>
      <name>dfs.namenode.startup.delay.block.deletion.sec</name>
      <value>3600</value>
    </property>
    
    <property>
      <name>dfs.namenode.write.stale.datanode.ratio</name>
      <value>1.0f</value>
    </property>
    
    <property>
      <name>dfs.nameservices</name>
      <value>dev</value>
    </property>
    
    <property>
      <name>dfs.permissions.enabled</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.permissions.superusergroup</name>
      <value>hdfs</value>
    </property>
    
    <property>
      <name>dfs.replication</name>
      <value>3</value>
    </property>
    
    <property>
      <name>dfs.replication.max</name>
      <value>50</value>
    </property>
    
    <property>
      <name>dfs.support.append</name>
      <value>true</value>
    </property>
    
    <property>
      <name>dfs.webhdfs.enabled</name>
      <value>true</value>
    </property>
    
    <property>
      <name>fs.permissions.umask-mode</name>
      <value>022</value>
    </property>
    
    <property>
      <name>nfs.exports.allowed.hosts</name>
      <value>* rw</value>
    </property>
    
    <property>
      <name>nfs.file.dump.dir</name>
      <value>/tmp/.hdfs-nfs</value>
    </property>
    
  </configuration>

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/interfacemg/BaseThirdUserDO.java

@ -11,7 +11,7 @@ import javax.persistence.Table;
 */
@Entity
@Table(name = "base_third_user")
public class BaseThirdUserDO extends UuidIdentityEntityWithOperator {
public class BaseThirdUserDO extends UuidIdentityEntityWithOperator implements java.io.Serializable {
    private String appId; //appid
    private String appKey;//appkey
    private String url;//请求地址

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/interfacemg/BaseThirdUserInterfaceDO.java

@ -11,7 +11,7 @@ import javax.persistence.Table;
 */
@Entity
@Table(name = "base_third_user_interface")
public class BaseThirdUserInterfaceDO extends UuidIdentityEntityWithOperator {
public class BaseThirdUserInterfaceDO extends UuidIdentityEntityWithOperator implements java.io.Serializable {
    private String userId; //第三方用户配置id
    private String code;//接口编码

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/interfacemg/BaseThirdUserInterfaceLogDO.java

@ -11,7 +11,7 @@ import javax.persistence.Table;
 */
@Entity
@Table(name = "base_third_user_interface_log")
public class BaseThirdUserInterfaceLogDO extends UuidIdentityEntityWithOperator {
public class BaseThirdUserInterfaceLogDO extends UuidIdentityEntityWithOperator implements java.io.Serializable{
    private String userInterfaceId;//接口id
    private String url;//请求地址
    private String request;//请求参数

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/interfacemg/BaseThirdUserInterfaceStandardDO.java

@ -11,7 +11,7 @@ import javax.persistence.Table;
 */
@Entity
@Table(name = "base_third_user_interface_standard")
public class BaseThirdUserInterfaceStandardDO extends UuidIdentityEntityWithOperator {
public class BaseThirdUserInterfaceStandardDO extends UuidIdentityEntityWithOperator implements java.io.Serializable {
    private String userInterfaceId;//接口id
    private String stdDatasetId;//数据集id
    private String stdMetadataId;//数据元id

+ 8 - 5
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/interfacemg/BaseUserInterfaceEndpoint.java

@ -1,11 +1,13 @@
package com.yihu.jw.base.endpoint.interfacemg;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.service.interfacemg.BaseUserInterfaceService;
import com.yihu.jw.entity.interfacemg.BaseThirdUserDO;
import com.yihu.jw.entity.interfacemg.BaseThirdUserInterfaceDO;
import com.yihu.jw.entity.interfacemg.BaseThirdUserInterfaceLogDO;
import com.yihu.jw.entity.interfacemg.BaseThirdUserInterfaceStandardDO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
@ -69,7 +71,8 @@ public class BaseUserInterfaceEndpoint extends EnvelopRestEndpoint {
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "size", value = "页码", required = false)
            @RequestParam(value = "size", required = false) Integer size) throws Exception {
        return success(baseUserInterfaceService.selectUserByCondition(condition,page,size));
        JSONObject jsonObject = baseUserInterfaceService.selectUserByCondition(condition,page,size);
        return success(jsonObject);
    }
    @GetMapping(value = BaseRequestMapping.UserInterface.selectUserInterfaceByCondition)
@ -116,7 +119,7 @@ public class BaseUserInterfaceEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = BaseRequestMapping.UserInterface.findUserById)
    @ApiOperation(value = "根据某个用户配置id查询详情")
    public Envelop findUserById (
    public ObjEnvelop findUserById (
            @ApiParam(name = "id", value = "详情id", required = false)
            @RequestParam(value = "id", required = false) String id) throws Exception {
        return success(baseUserInterfaceService.findUserById(id));
@ -124,7 +127,7 @@ public class BaseUserInterfaceEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = BaseRequestMapping.UserInterface.findUserInterfaceById)
    @ApiOperation(value = "根据某个接口配置id查询详情")
    public Envelop findUserInterfaceById (
    public ObjEnvelop findUserInterfaceById (
            @ApiParam(name = "id", value = "详情id", required = false)
            @RequestParam(value = "id", required = false) String id) throws Exception {
        return success(baseUserInterfaceService.findUserInterfaceById(id));
@ -132,7 +135,7 @@ public class BaseUserInterfaceEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = BaseRequestMapping.UserInterface.findUserInterfaceStandardById)
    @ApiOperation(value = "根据某个接口标准配置id查询详情")
    public Envelop findUserInterfaceStandardById (
    public ObjEnvelop findUserInterfaceStandardById (
            @ApiParam(name = "id", value = "详情id", required = false)
            @RequestParam(value = "id", required = false) String id) throws Exception {
        return success(baseUserInterfaceService.findUserInterfaceStandardById(id));
@ -140,7 +143,7 @@ public class BaseUserInterfaceEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = BaseRequestMapping.UserInterface.findUserInterfaceLogById)
    @ApiOperation(value = "根据某个接口调用日志id查询详情")
    public Envelop findUserInterfaceLogById (
    public ObjEnvelop findUserInterfaceLogById (
            @ApiParam(name = "id", value = "详情id", required = false)
            @RequestParam(value = "id", required = false) String id) throws Exception {
        return success(baseUserInterfaceService.findUserInterfaceLogById(id));

+ 5 - 5
svr/svr-base/src/main/java/com/yihu/jw/base/service/interfacemg/BaseUserInterfaceService.java

@ -1,6 +1,7 @@
package com.yihu.jw.base.service.interfacemg;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.dao.interfacemg.BaseThirdUserDao;
import com.yihu.jw.base.dao.interfacemg.BaseThirdUserInterfaceDao;
import com.yihu.jw.base.dao.interfacemg.BaseThirdUserInterfaceLogDao;
@ -12,7 +13,6 @@ import com.yihu.jw.entity.interfacemg.BaseThirdUserInterfaceStandardDO;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -101,7 +101,7 @@ public class BaseUserInterfaceService extends BaseJpaService<BaseThirdUserInterf
        if (StringUtils.isNoneBlank(condition)){
            conditionSql = " and name like '%"+condition+"%' ";
        }
        String sqlCount = "select count as \"total\" from base_third_user where 1=1  ";
        String sqlCount = "select count(1) as \"total\" from base_third_user where 1=1  ";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql+conditionSql,page,size);
        List<Map<String,Object>> totalMapList = hibenateUtils.createSQLQuery(sqlCount+conditionSql);
@ -158,7 +158,7 @@ public class BaseUserInterfaceService extends BaseJpaService<BaseThirdUserInterf
        if (StringUtils.isNoneBlank(userId)){
            conditionSql += " and user_id = '"+userId+"' ";
        }
        String sqlCount = "select count as \"total\" from base_third_user_interface where 1=1  ";
        String sqlCount = "select count(1) as \"total\" from base_third_user_interface where 1=1  ";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql+conditionSql,page,size);
        List<Map<String,Object>> totalMapList = hibenateUtils.createSQLQuery(sqlCount+conditionSql);
@ -215,7 +215,7 @@ public class BaseUserInterfaceService extends BaseJpaService<BaseThirdUserInterf
        if (StringUtils.isNoneBlank(userInterfaceId)){
            conditionSql += " and user_interface_id = '"+userInterfaceId+"' ";
        }
        String sqlCount = "select count as \"total\" from base_third_user_interface_standard where 1=1  ";
        String sqlCount = "select count(1) as \"total\" from base_third_user_interface_standard where 1=1  ";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql+conditionSql,page,size);
        List<Map<String,Object>> totalMapList = hibenateUtils.createSQLQuery(sqlCount+conditionSql);
@ -268,7 +268,7 @@ public class BaseUserInterfaceService extends BaseJpaService<BaseThirdUserInterf
        if (StringUtils.isNoneBlank(userInterfaceId)){
            conditionSql += " and user_interface_id = '"+userInterfaceId+"' ";
        }
        String sqlCount = "select count as \"total\" from base_third_user_interface_log where 1=1  ";
        String sqlCount = "select count(1) as \"total\" from base_third_user_interface_log where 1=1  ";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql+conditionSql,page,size);
        List<Map<String,Object>> totalMapList = hibenateUtils.createSQLQuery(sqlCount+conditionSql);

+ 1 - 1
svr/svr-base/src/main/resources/bootstrap.yml

@ -1,6 +1,6 @@
spring:
  application:
    name: svr-base
    name: svr-base-wangzhinan
  cloud:
    config:
      failFast: true

+ 1 - 1
svr/svr-internet-hospital-job/src/main/java/com/yihu/Application.java

@ -3,7 +3,7 @@ package com.yihu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;

+ 42 - 0
svr/svr-quota/.gitignore

@ -0,0 +1,42 @@
#project files
ehr.ipr
ehr.iws
ehr.ids
*.html
*.iml
*/target/*
*/*/target/*
.idea/*
# ---> Java
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*#
# thrift generate code
commons-thrift-services/src/main/java/com/yihu/ehr/adaption
commons-thrift-services/src/main/java/com/yihu/ehr/app
commons-thrift-services/src/main/java/com/yihu/ehr/browser
commons-thrift-services/src/main/java/com/yihu/ehr/data/domain
commons-thrift-services/src/main/java/com/yihu/ehr/dict
commons-thrift-services/src/main/java/com/yihu/ehr/geography
commons-thrift-services/src/main/java/com/yihu/ehr/hadoop
commons-thrift-services/src/main/java/com/yihu/ehr/lang
commons-thrift-services/src/main/java/com/yihu/ehr/org
commons-thrift-services/src/main/java/com/yihu/ehr/pack
commons-thrift-services/src/main/java/com/yihu/ehr/patient
commons-thrift-services/src/main/java/com/yihu/ehr/profile
commons-thrift-services/src/main/java/com/yihu/ehr/resolve
commons-thrift-services/src/main/java/com/yihu/ehr/resource
commons-thrift-services/src/main/java/com/yihu/ehr/security
commons-thrift-services/src/main/java/com/yihu/ehr/std
commons-thrift-services/src/main/java/com/yihu/ehr/user

BIN
svr/svr-quota/doc/统计架构.png


+ 267 - 0
svr/svr-quota/pom.xml

@ -0,0 +1,267 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>com.yihu.jw</groupId>
        <artifactId>wlyy-parent-pom</artifactId>
        <version>2.4.0</version>
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>svr-quota</artifactId>
    <packaging>jar</packaging>
    <version>${project.parent.version}</version>
    <dependencies>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <!-- true1 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>${version.jest}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${version.druid}</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.abel533</groupId>
            <artifactId>ECharts</artifactId>
            <version>2.2.6</version>
        </dependency>
        <!--      <dependency>
                  <groupId>com.yihu.jw</groupId>
                  <artifactId>commons-ui-swagger</artifactId>
              </dependency>-->
        <!--       <dependency>
                   <groupId>com.yihu.jw</groupId>
                   <artifactId>commons-data-solr</artifactId>
               </dependency>-->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>mysql-starter</artifactId>
            <version>${version.wlyy-common}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--     <dependency>
                 <groupId>com.yihu.jw</groupId>
                 <artifactId>common-data-hbase</artifactId>
                 <scope>compile</scope>
             </dependency>-->
 <!--       <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>commons-profile-core</artifactId>
            <scope>compile</scope>
        </dependency>-->
        <!--        <dependency>
                    <groupId>com.yihu.jw</groupId>
                    <artifactId>common-data-query</artifactId>
                    <scope>compile</scope>
                </dependency>-->
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-rest-model</artifactId>
            <scope>compile</scope>
        </dependency>
   <!--     <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>commons-ehr-constants</artifactId>
            <scope>compile</scope>
        </dependency>-->
<!--        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>commons-data-redis</artifactId>
            <scope>compile</scope>
        </dependency>-->
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-util</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <!--<dependency>
            <groupId>com.yihu.ehr</groupId>
            <artifactId>commons-cat</artifactId>
        </dependency>-->
    </dependencies>
    <build>
        <finalName>svr-quota</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <!-- 生成的jar中,不要包含pom.xml和pom.properties这两个文件 -->
                        <addMavenDescriptor>false</addMavenDescriptor>
                        <manifest>
                            <!-- 是否要把第三方jar加入到类构建路径 -->
                            <addClasspath>true</addClasspath>
                            <!-- 外部依赖jar包的最终位置 -->
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.yihu.SvrInternetHospitalApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <!--拷贝依赖到jar外面的lib目录-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-lib</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <!-- 依赖包输出目录,将来不打进jar包里 -->
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <excludeTransitive>false</excludeTransitive>
                            <stripVersion>false</stripVersion>
                            <includeScope>runtime</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!--指定配置文件,将resources打成外部resource-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <!-- 指定配置文件目录,这样jar运行时会去找到同目录下的resources文件夹下查找 -->
                        <manifestEntries>
                            <Class-Path>resources/</Class-Path>
                        </manifestEntries>
                    </archive>
                    <!-- 打包时忽略的文件(也就是不打进jar包里的文件) -->
                    <excludes>
                        <exclude>**/*.yml</exclude>
                        <exclude>**/*.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!-- 拷贝资源文件 外面的resource目录-->
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <!-- 资源文件输出目录 -->
                            <outputDirectory>${project.build.directory}/resources</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/resources</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

+ 14 - 0
svr/svr-quota/readme.MD

@ -0,0 +1,14 @@
包结构:
    config:配置
    controller:控制器
    dao.jpa:dao层
    etl:etl相关
    job:执行的job
    model.jpa:数据库的映射
    service:服务层
    util:工具类
    vo:modelvo
    
    
相关资料
    powerdesign:https://192.168.1.103:888/svn/outwindow/基础开发部/doc/i健康2.0

+ 23 - 0
svr/svr-quota/src/main/java/com/yihu/quota/SvrQuotaApplication.java

@ -0,0 +1,23 @@
package com.yihu.quota;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableAsync;
/**
 * Created by janseny on 2017/06/16.
 */
@EnableJpaRepositories(basePackages="com.yihu.quota.dao.jpa")
@SpringBootApplication
@EnableJpaAuditing
@EnableAsync
@ComponentScan("com.yihu")
public class SvrQuotaApplication {
    public static void main(String[] args) {
        SpringApplication.run(SvrQuotaApplication.class, args);
    }
}

+ 50 - 0
svr/svr-quota/src/main/java/com/yihu/quota/config/AsyncConfig.java

@ -0,0 +1,50 @@
package com.yihu.quota.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
 * Created by Administrator on 2016.10.18.
 * 启用多綫程
 */
@Configuration
@EnableAsync
public class AsyncConfig {
    /** 如果池中的实际线程数小于corePoolSize,无论是否其中有空闲的线程,都会给新的任务产生新的线程 */
    private int corePoolSize = 5;
    /** 如果池中的线程数=maximumPoolSize,则有空闲线程使用空闲线程,否则新任务放入queueCapacity. */
    private int maxPoolSize = 20;
    /** 缓冲队列. */
    private int queueCapacity = 10;
    @Bean
    public Executor dbExtractExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    @Bean
    public Executor dbStorageExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

+ 25 - 0
svr/svr-quota/src/main/java/com/yihu/quota/config/quota/JobFactory.java

@ -0,0 +1,25 @@
package com.yihu.quota.config.quota;//package com.yihu.jw.config.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
/**
 * Created by Administrator on 2016.10.12.
 * 為了讓quartz種可以使用Spring的注入
 */
@Component("jobFactory")
public class JobFactory extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
       // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

+ 52 - 0
svr/svr-quota/src/main/java/com/yihu/quota/config/quota/SchedulerConfig.java

@ -0,0 +1,52 @@
package com.yihu.quota.config.quota;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
/**
 * Created by chenweida on 2016/2/3.
 */
@Configuration
public class SchedulerConfig {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private JobFactory jobFactory;
    @Autowired
    private DataSource dataSource;
    @Bean
    SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setJobFactory(jobFactory);
        bean.setApplicationContext(this.applicationContext);
        bean.setOverwriteExistingJobs(true);
        bean.setStartupDelay(20);// 延时启动
        bean.setSchedulerName("schedulerFactoryBeanCWD");
        bean.setAutoStartup(true);
        bean.setDataSource(dataSource);
        bean.setQuartzProperties(quartzProperties());
        return bean;
    }
    /**
     * quartz配置文件
     * @return
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
}

+ 1801 - 0
svr/svr-quota/src/main/java/com/yihu/quota/constants/ServiceApi.java

@ -0,0 +1,1801 @@
package com.yihu.quota.constants;
/**
 * 微服务REST API. 此处定义的URL可用于服务对外提供的地址及HTTP客户端请求地址.
 * URL定义遵循健康档案平台REST规范.
 *
 * @author Sand
 * @version 1.0
 * @created 2015.09.09 15:04
 */
public class ServiceApi {
    public static class GateWay {
        public static final String admin = "/admin";
        public static final String FzGateway = "/admin/gateway/fz";
    }
    public static class Adaptions {
        //public static final String Cache = "/adaptions/{id}/cache";
        //public static final String CacheGet = "/adaptions/{key}/cache";
        public static final String Scheme = "/adaptions/schemas/{id}";
        public static final String Schemes = "/adaptions/schemas";
        public static final String SchemaMetadataList = "/adaptions/schema/metadata";
        public static final String SchemaMetadata = "/adaptions/schema/metadata/{id}";
        public static final String SchemaMetadataBatch = "/adaptions/schema/metadata/batch";
        public static final String RsAdapterDictionaries = "/adaptions/adapter/dictionaries";
        //public static final String RsAdapterDictionariesCache = "/adaptions/adapter/dictionaries/{schemaId}/cache";
        public static final String RsAdapterDictionary = "/adaptions/adapter/dictionaries/{id}";
    }
    /**
     * 资源管理中心接口
     */
    public static class Resources {
        //资源查询接口(命名先按原有路径,不规范)
        public static final String ResourceViewMetadata = "/resources/query/getResourceMetadata"; //资源浏览获取结构
        public static final String ResourceViewData = "/resources/query/getResourceData"; //资源浏览获取数据
        public static final String ResourceViewSubData = "/resources/query/getResourceSubData";
        public static final String ResourceQuery = "/resources/query"; //资源查询接口
        //public static final String ResourceSubQuery = "/resources/sub_query"; //详细资源查询接口
        public static final String ResourceQueryTransform = "/resources/query/transform"; //资源查询接口+转译
        public static final String ResourceQueryAllTransform = "/resources/queryAll/transform"; //资源查询接口获取所有数据集相关+转译
        public static final String ResourceQueryByDataSets = "/resources/query/dataSets"; //资源查询接口获取数据集相关的数据+转译
        public static final String ResourceRawFiles = "/resources/query/raw_files"; //非结构资源查询接口
        public static final String ResourceRawFilesList = "/resources/query/raw_files_list"; //非结构资源List查询接口
        public static final String ResourceMasterData = "/resources/query/master_data"; //主表资源查询接口
        public static final String ResourceSubData = "/resources/query/sub_data"; //细表资源查询接口
        public static final String ResourceMasterStat = "/resources/query/master_stat"; //主表资源统计接口
        public static final String ResourceSubStat = "/resources/query/sub_stat"; //细表资源查询接口
        public static final String ResourceHealthFile = "/resources/query/health_file"; //细表资源查询接口
        public static final String ResourceMysql = "/resources/query/mysql"; //mysql资源查询接口
        public static final String SolrIndexData = "/resources/query/solrIndex"; //solr索引列表查询接口
        //资源浏览
        public static final String ResourceBrowseCategories = "/resources/ResourceBrowses/categories";
        public static final String ResourceBrowseResourceData = "/resources/ResourceBrowses/getResourceData";
        public static final String ResourceBrowseResourceSubData = "/resources/ResourceBrowses/getResourceSubData";//根据主表查询词表数据接口
        public static final String ResourceBrowseQuotaResourceData = "/resources/ResourceBrowses/getQuotaResourceData";
        public static final String ResourceBrowseQuotaResourceParam = "/resources/ResourceBrowses/getQuotaResourceParam";
        public static final String ResourceBrowseResourceMetadata = "/resources/ResourceBrowses/getResourceMetadata";
        public static final String ResourceBrowseTree = "/resourceBrowseTree";
        public static final String ResourceBrowseGetRsByCategoryId = "/getResourceByCategoryId";
        //资源视图
        public static final String Resources = "/resources";
        public static final String Resource = "/resources/{id}";
        public static final String ResourceByCode = "/resources/byCode";
        public static final String ResourceTree = "/resources/tree";
        public static final String ResourcePage = "/resources/page";
        public static final String NoPageResources = "/NoPageResources";
        public static final String IsExistName = "/resources/isExistName";
        public static final String IsExistCode = "/resources/isExistCode/{code}";
        public static final String GetQuotaList = "/resources/getQuotaList";
        public static final String GetRsQuotaPreview = "/resources/getRsQuotaPreview";
        public static final String SearchInfo = "/resourceQuota/searchInfo";
        public static final String BatchAddResourceQuota = "/resourceQuota/batchAddResourceQuota";
        public static final String SearchByQuotaId = "/resourceQuota/searchByQuotaId";
        public static final String GetByResourceId = "/resourceQuota/getByResourceId";
        public static final String GetQuotaChartByQuotaId = "/resourceQuota/getQuotaChartByQuotaId";
        public static final String GetRQNameByResourceId = "/resourceQuota/getRQNameByResourceId";
        public static final String DelRQNameByResourceId = "/resourceQuota/delRQNameByResourceId";
        public static final String SearchQuotaByResourceId = "/resourceQuota/getQuotaByResourceId";
        public static final String SearchTreeByResourceId = "/resourceQuota/searchTreeByResourceId";
        public static final String UpdateResourceQuota = "/resourceQuota/updateResourceQuota";
        public static final String ResourceMetadataList = "/resources/rs_metadata";
        public static final String ResourceMetadataBatch = "/resources/rs_metadata/batch";
        public static final String ResourceMetadataBatchByResourceId = "/resources/rs_metadata/resource_ids/batch";
        public static final String ResourceMetadata = "/resources/rs_metadata/{id}";
        public static final String ResourceGrant = "/resources/grants/{id}";
        public static final String ResourceGrants = "/resources/grants";
        public static final String ResourceGrantsNoPage = "/resources/grants/no_paging";
        public static final String AppsGrantResources = "/resources/apps/{appId}/grant";
        public static final String ResourceGrantApps = "/resources/{resourceId}/grant";
        public static final String AppsGrantResourcesByCategoryId = "/resources/appsAppId/grantByCategoryId";
        public static final String DeleteAppsGrantResourcesByCategoryId = "/resources/appsAppId/deleteGrantByCategoryId";
        public static final String ResourceMetadatasValid = "/resources/metadatas/valid";
        public static final String ResourceMetadataGrants = "/resources/metadata/grants";
        public static final String ResourceMetadataGrant = "/resources/metadata/grants/{id}";
        public static final String ResourceMetadataGrantApp = "/resources/app_resource/{appResourceId}/grant/metadata/{metadataId}";
        public static final String ResourceMetadataListGrantApp = "/resources/metadata/grant/{appResourceId}";
        public static final String ResourceAppMetadataGrants = "/resources/app_resource/{app_res_id}/metadata";
        public static final String ResourceAppMetadataGrant = "/resources/app_resource/metadata/grant";
        public static final String ResourceAppMetadataGrantExistence = "/resources/app_resource/metadata/grant/existence";
        public static final String MetadataList = "/resources/metadata";
        public static final String MetadataBatch = "/resources/metadata/batch";
        public static final String Metadata = "/resources/metadata/{id}";
        public static final String MetadataExistence = "/resources/metadata/existence";
        public static final String MetadataStdCodeExistence = "/resources/metadata/std_code/existence";
        public static final String MetadataIdExistence = "/resources/metadata/id/existence";
        public static final String MetadataMaxId = "/resources/metadata/metadataMaxId";
        public static final String DictList = "/resources/dict";
        public static final String DictBatch = "/resources/dict/batch";
        public static final String Dict = "/resources/dict/{id}";
        public static final String DictCode = "/resources/dict/code";
        public static final String DictExistence = "/resources/dict/existence";
        public static final String DictEntryBatch = "/resources/dict/entry/batch";
        public static final String DictCodesExistence = "/resources/dict/codes/existence";
        public static final String Params = "/resources/params";
        public static final String ParamsNoPage = "/resources/params/no_paging";
        public static final String Param = "/resources/param";
        public static final String ParamById = "/resources/param/{id}";
        public static final String ParamKeyValueExistence = "/resources/param/key_value_existence";
        //固化视图筛选条件
        public static final String QueryByResourceId = "/resources/query/QueryByResourceId";
        public static final String DictEntries = "/resources/dict_entries";
        public static final String NoPageDictEntries = "/resources/noPage_dict_entries";
        public static final String DictEntry = "/resources/dict_entries/{id}";
        public static final String DictEntriesByDictCode = "/resources/dict/code/dict_entries";
        public static final String DictEntriesExistence = "/resources/dict_entries/existence";
        public static final String SystemDictList = "/resources/system_dict";
        public static final String SystemDict = "/resources/system_dict/{id}";
        public static final String SystemDictEntries = "/resources/system_dict_entries";
        public static final String SystemDictEntry = "/resources/system_dict_entries/{id}";
        //资源接口
        public static final String Interfaces = "/resources/interfaces";
        public static final String InterfaceById = "/resources/interfaces/{id}";
        public static final String Interface = "/resources/interface";
        public static final String InterfaceNameExistence = "/resources/existence/name";
        //资源分类
        public static final String CategoryUpdate = "/resources/category/update";
        public static final String Category = "/resources/category/{id}";
        public static final String CategoriesByPid = "/resources/categories/pid";
        public static final String CategoriesByCodeAndPid = "/resources/categories/codeAndPid";
        public static final String CategoryTree = "/resources/categories/tree";
        public static final String CategoryExitSelfAndParent = "/resources/categories/selfAndParent";
        public static final String CategoriesAll = "/resources/categories/all";
        public static final String CategoriesSearch = "/resources/categories/search";
        //综合查询服务
        public static final String IntMetadataList = "/resources/integrated/metadata_list";
        public static final String IntMetadataData = "/resources/integrated/metadata_data";
        public static final String IntQuotaList = "/resources/integrated/quota_list";
        public static final String IntQuotaData = "/resources/integrated/quota_data";
        public static final String IntQuotaParam = "/resources/integrated/quota_param";
        public static final String IntResourceUpdate = "/resources/integrated/resource_update";
        public static final String IntResourceQueryUpdate = "/resources/integrated/resource_query_update";
        //获取分类
        public static final String IntCategory = "/resources/integrated/category";
        public static final String IntMetadata = "/resources/integrated/metadata";
        //貌似没用了
        public static final String AdapterDicts = "/resources/adapter/dict";
        public static final String AdapterDictsBatch = "/resources/adapter/dict/batch";
        public static final String AdapterDict = "/resources/adapter/dict/{id}";
        //应用角色资源授权
        public static final String ResourceRolesGrants = "/resources/rolesGrants";
        public static final String ResourceRolesGrant = "/resources/rolesGrants/{id}";
        public static final String ResourceRolesMetadatasValid = "/resources/relosMetadatas/valid";
        public static final String ResourceRolesMetadataGrants = "/resources/relosMetadatas/grants";
        public static final String RolesGrantResources = "/resources/roles/{rolesId}/grant";
        public static final String GetRolesGrantResources = "/resources/getRolesGrantResources";
        //public static final String ResourceGrantApps = "/resources/{resourceId}/grant";
        public static final String ResourceRolesMetadataGrant = "/resources/rolesMetadata/grants/{id}";
        public static final String ResourceRolesGrantsNoPage = "/resources/rolesGrants/no_paging";
        public static final String ResourceRolesResMetadataGrants = "/resources/roles_resource/{roles_res_id}/metadata";
        public static final String RolesGrantResourcesByCategoryId = "/resources/rolesRolesId/grantByCategoryId";
        public static final String DeleteRolesGrantResourcesByCategoryId = "/resources/rolesRolesId/deleteGrantByCategoryId";
        /**
         * 机构-资源授权
         */
        public static final String ResourceOrgGrants = "/resources/OrgGrants";
        public static final String ResourceOrgGrant = "/resources/OrgGrants/{id}";
        public static final String ResourceOrgMetadatasValid = "/resources/OrgMetadatas/valid";
        public static final String ResourceOrgMetadataGrants = "/resources/OrgMetadatas/grants";
        public static final String OrgGrantResources = "/resources/Org/{orgCode}/grant";
        //public static final String ResourceGrantApps = "/resources/{resourceId}/grant";
        public static final String ResourceOrgMetadataGrant = "/resources/OrgMetadata/grants/{id}";
        public static final String ResourceOrgGrantsNoPage = "/resources/OrgGrants/no_paging";
        public static final String ResourceOrgResMetadataGrants = "/resources/Org_resource/{Org_res_id}/metadata";
        public static final String ResourceOrgRsMetadataGrant = "/resources/Org_resource/metadata/grant";
        /**
         * 资源报表分类
         */
        public static final String RsReportCategoryPrefix = "/resources/reportCategory/";
        public static final String RsReportCategory = "/resources/reportCategory/{id}";
        public static final String RsReportCategoryChildrenByPid = "/resources/reportCategory/getChildrenByPid";
        public static final String RsReportCategoryTree = "/resources/reportCategoryTree";
        public static final String RsReportCategoryComboTree = "/resources/reportCategoryComboTree";
        public static final String RsReportCategories = "/resources/reportCategories";
        public static final String RsReportCategorySave = "/resources/reportCategory/save";
        public static final String RsReportCategoryDelete = "/resources/reportCategory/delete";
        public static final String RsReportCategoryIsUniqueCode = "/resources/reportCategory/isUniqueCode";
        public static final String RsReportCategoryIsUniqueName = "/resources/reportCategory/isUniqueName";
        public static final String RsReportCategoryNoPageCategories = "/resources/reportCategory/getAllCategories";
        public static final String RsReportCategoryByApp = "/resources/reportCategory/getAllCategoryByApp";
        public static final String RsReportCategoryByIds = "/resources/reportCategory/getAllCategoryByIds";
        public static final String RsReportCategoryIdsByCode = "/resources/reportCategory/getCategoryIdsByCode";
        /**
         * 资源报表分类和应用
         */
        public static final String RsReportCategoryAppDelete = "/resources/reportCategory/deleteCategoryApp";
        public static final String RsReportCategoryAppSave = "/resources/reportCategory/saveCategoryApp";
        public static final String GetRsReportCategoryApps = "/resources/reportCategory/getRsReportCategoryApps";
        /**
         * 资源报表监测分类
         */
        public static final String RsReportMonitorType = "/resources/rsReportMonitorType/{id}";
        public static final String RsReportMonitorTypeSave = "/resources/rsReportMonitorType/save";
        public static final String RsReportMonitorTypeDelete = "/resources/rsReportMonitorType/delete";
        public static final String RsReportMonitorTypeIsUniqueName = "/resources/rsReportMonitorType/isUniqueName";
        public static final String RsReportMonitorTypes = "/resources/rsReportMonitorType/getRsReportMonitorTypePage";
        public static final String RsReportMonitorTypesNoPage = "/resources/rsReportMonitorType/getRsReportMonitorTypeNoPage";
        public static final String RsReportMonitorTypesById = "/resources/rsReportMonitorType/getRsReportMonitorTypeById";
        public static final String RsReportByMonitorTypeId = "/resources/rsReportMonitorType/getRsReportByMonitorTypeId";
        /**
         * 资源报表监测类型配置报表
         */
        public static final String RsMonitorTypeReport = "/resources/monitorTypeReport";
        public static final String RsMonitorTypeReportByUserId = "/resources/monitorTypeReport/{user_id}";
        public static final String RsMonitorTypeReports = "/resources/monitorTypeReport";
        public static final String RsMonitorTypeReportsNoPage = "/resources/monitorTypeReport/noPage";
        /**
         * 资源报表
         */
        public static final String RsReportPrefix = "/resources/report/";
        public static final String RsReport = "/resources/report/{id}";
        public static final String RsReportFindByCode = "/resources/report/findByCode";
        public static final String RsReports = "/resources/reports";
        public static final String RsReportViewsTreeData = "/resources/report/viewsTreeData";
        public static final String RsReportSelectedViews = "/resources/report/selectedViews";
        public static final String RsReportSave = "/resources/report/save";
        public static final String RsReportDelete = "/resources/report/delete";
        public static final String RsReportIsUniqueCode = "/resources/report/isUniqueCode";
        public static final String RsReportIsUniqueName = "/resources/report/isUniqueName";
        public static final String RsReportNoPage = "/resources/report/getReportNoPage";
        public static final String RsReportTemplateContent = "/resources/report/getTemplateContent";
        public static final String RsReportIsCategoryApplied = "/resources/report/isCategoryApplied";
        public static final String RsReportByCategoryId = "/resources/report/getByCategoryId";
        public static final String GetPositionMapByCode = "/resources/report/getPositionMapByCode";
        public static final String GetRsReportByParam = "/resources/report/getRsReportByParam";
        public static final String QueryByUserId = "/open/resources/report/queryByUserId";
        public static final String QueryOtherReportByUserId = "/open/resources/report/queryOtherReportByUserId";
        public static final String SaveByUserId = "/open/resources/report/saveByUserId";
        /**
         * 资源报表视图配置
         */
        public static final String RsReportViews = "/resources/reportViews";
        public static final String RsReportViewSave = "/resources/reportView/save";
        public static final String RsReportViewExist = "/resources/reportView/exist";
        public static final String RsReportViewExistByResourceId = "/resources/reportView/existByResourceId";
        public static final String RsReportViewExistReport = "/resources/reportView/existReport";
        public static final String StatisticsGetDoctorsGroupByTown = "/resources/statistics/getDoctorsGroupByTown";
        //资源中心 - 统计相关
        public static final String GetPatientArchiveCount = "/resource/center/getPatientArchiveCount";
        public static final String GetMedicalResourcesCount = "/resource/center/getMedicalResourcesCount";
        public static final String GetHealthArchiveCount = "/resource/center/getHealthArchiveCount";
        public static final String GetElectronicCasesCount = "/resource/center/getElectronicCasesCount";
        public static final String GetHealthCardBindingAmount = "/resource/center/getHealthCardBindingAmount";
        public static final String GetInfoDistribution = "/resource/center/getInfoDistribution";
        public static final String GetNewSituation = "/resource/center/getNewSituation";
        public static final String GetOrgArchives = "/resource/center/getOrgArchives";
        public static final String GetMedicalStaffDistribution = "/resource/center/getMedicalStaffDistribution";
        public static final String GetMedicalStaffRatio = "/resource/center/getMedicalStaffRatio";
        public static final String GetCumulativeIntegration = "/resource/center/getCumulativeIntegration";
        public static final String GteTotallyToBeIntegrated = "resource/center/gteTotallyToBeIntegrated";
        public static final String GetArchiveSource = "/resource/center/getArchiveSource";
        public static final String GetArchiveDistribution = "/resource/center/getArchiveDistribution";
        public static final String GetStorageAnalysis = "/resource/center/getStorageAnalysis";
        public static final String GetElectronicMedicalSource = "/resource/center/getElectronicMedicalSource";
        public static final String GetElectronicMedicalOrgDistributed = "/resource/center/getElectronicMedicalOrgDistributed";
        public static final String GetElectronicMedicalDeptDistributed = "/resource/center/getElectronicMedicalDeptDistributed";
        public static final String GetElectronicMedicalAcquisitionSituation = "/resource/center/getElectronicMedicalAcquisitionSituation";
        //资源中心 - 大数据展示相关
        public static final String Achievements = "/resource/center/achievements";
        public static final String Visualization = "/resource/center/visualization";
        public static final String DataAnalysis = "/resource/center/dataAnalysis";
        public static final String HierarchicalManagement = "/resource/center/hierarchicalManagement";
    }
    /**
     * 档案查询接口
     */
    public static class Profiles {
        public static final String ProfileInfo = "/profile/baseInfo"; //基本信息
        public static final String PastHistory = "/profile/pastHistory"; //既往史 - mobile居民端
        public static final String PersonHistory = "/profile/personHistory"; //个人史
        public static final String AllergensHistory = "/profile/allergensHistory"; //过敏史
        public static final String FamilyHistory = "/profile/familyHistory"; //家族史
        public static final String HealthProblem = "/profile/healthProblem"; //主要健康问题
        public static final String HealthCondition = "/profile/healthCondition"; //历史健康情况
        public static final String MedicalEvents = "/profile/medicalEvents"; //门诊/住院事件(时间轴)
        public static final String RecentMedicalEvents = "/profile/recentMedicalEvents"; //最近就诊记录
        public static final String RecentVisits = "/profile/recentVisits"; //近期就诊
        public static final String RecentVisitsSub = "/profile/recentVisitsSub"; //近期就诊详情
        public static final String CDAClass = "/profile/cdaClass"; //cda分类
        public static final String CDAData = "/profile/cdaData"; //cda数据
        public static final String MedicationRecords = "/profile/medicationRecords"; //患者用药清单
        public static final String MedicationRecordsPage = "/profile/medicationRecordsPage"; //患者用药清单
        public static final String MedicationRanking = "/profile/medicationRanking"; //患者用药排行
        public static final String MedicationRankingWithTable = "/profile/medicationRankingWithTable"; //患者用药排行
        public static final String RecentMedicationSub = "/profile/recentMedicationSub"; //患者用药详情
        public static final String InspectionRecords = "/profile/inspectionRecords"; //检查检验记录
        public static final String InspectionStatistics = "/profile/inspectionStatistics"; //检查检验记录统计
        public static final String InspectionStatisticsOneSub = "/profile/inspectionStatisticsOneSub"; //检查检验记录子项详情(某次检验记录)
        public static final String InspectionStatisticsAllSub = "/profile/inspectionStatisticsAllSub"; //检查检验记录子项详情(相关检验全部记录)
        public static final String MotherhoodOverview = "/profile/motherhoodOverview"; //孕产概况
        // ------------------------------ 以上为已对接接口 ------------------------------
        public static final String ProfileLucene = "/profile/lucene"; //全文检索
        public static final String MedicalDisease = "/{demographic_id}/profile/medical_disease"; //就诊过疾病
        public static final String MedicalArea = "/{demographic_id}/profile/medical_area"; //就诊过区域
        public static final String MedicalYear = "/{demographic_id}/profile/medical_year"; //就诊过年份
        public static final String MedicationUsed = "/{demographic_id}/profile/medication_used"; //患者常用药(按次数)
        public static final String MedicalEvent = "/{event_no}/info"; //某次住院/门诊事件信息
        public static final String MedicationMaster = "/profile/medication/master"; //处方主表
        public static final String MedicationPrescription = "/profile/medication/prescription"; //处方笺
        public static final String MedicationDetail = "/profile/medication/detail/{prescription_no}"; //处方细表
        public static final String MedicationDetailChinese = "/profile/medication/detail/chinese"; //中药处方
        public static final String MedicationDetailWestern = "/profile/medication/detail/western"; //西药处方
        public static final String OutpatientDiagnosis = "/{demographic_id}/outpatient/diagnosis"; //门诊诊断
        public static final String OutpatientSymptom = "/{demographic_id}/outpatient/symptom"; //门诊症状
        public static final String OutpatientCostMaster = "/{demographic_id}/outpatient/cost/master"; //门诊费用汇总
        public static final String OutpatientCostDetail = "/{demographic_id}/outpatient/cost/detail"; //门诊费用明细
        public static final String HospitalizedDiagnosis = "/{demographic_id}/hospitalized/diagnosis"; //住院诊断
        public static final String HospitalizedSymptom = "/{demographic_id}/hospitalized/symptom"; //住院症状
        public static final String HospitalizedCostMaster = "/{demographic_id}/hospitalized/cost/master"; //住院费用汇总
        public static final String HospitalizedCostDetail = "/{demographic_id}/hospitalized/cost/detail"; //住院费用明细
        public static final String HospitalizedOrdersTemporary = "/{demographic_id}/hospitalized/orders/temporary"; //住院临时医嘱
        public static final String HospitalizedOrdersLongtime = "/{demographic_id}/hospitalized/orders/longtime"; //住院长期医嘱
        public static final String HospitalizedDeath = "/{demographic_id}/hospitalized/death"; //住院死因链情况
        public static final String CDADocumentId = "/profile/cda/document_id"; //cda模板(通过event_no + cda_type)
        public static final String CDADocument = "/{profile_id}/cda_document"; //完整CDA文档
        public static final String ExaminationReport = "/{demographic_id}/examination"; //检查报告单
        public static final String ExaminationImg = "/{demographic_id}/examination/img"; //检查报告单图片
        public static final String LaboratoryReport = "/{demographic_id}/laboratory"; //检验报告单
        public static final String LaboratoryImg = "/{demographic_id}/laboratory/img"; //检验报告单图片
        public static final String LaboratoryProject = "/{demographic_id}/laboratory/project"; //检验报告单项目
        public static final String LaboratoryAllergy = "/{demographic_id}/laboratory/allergy"; //检验药敏
        public static final String Surgery = "/{demographic_id}/surgery";//手术-手术记录
        public static final String IndicatorsClass = "/{demographic_id}/indicators/class"; //获取某个健康问题指标
        public static final String IndicatorsData = "/{demographic_id}/indicators/data"; //获取指标数据
    }
    public static class Families {
        public static final String Families = "/families";
        public static final String Family = "/families/{id}";
        public static final String FamiliesMembers = "/families/members";
        public static final String FamilyMembers = "/families/{families_id}/members";
        public static final String FamilyMember = "/families/{families_id}/members/{id_card_no}";
    }
    public static class Cipher {
        public static final String Encryption = "/cipher/encryption/{type}";
        public static final String Decryption = "/cipher/decryption/{type}";
    }
    public static class Apps {
        public static final String Apps = "/apps";
        public static final String AppsNoPage = "/apps/no_paging";
        public static final String getApp = "/app";
        public static final String App = "/apps/{app_id}";
        public static final String AppExistence = "/apps/{app_id}/existence";
        public static final String AppStatus = "/apps/{app_id}/status";
        public static final String AppNameExistence = "/app/{app_name}/existence";
        public static final String FilterList = "/apps/filterList";
        public static final String getAppTypeAndApps = "/getAppTypeAndApps";
        public static final String getApps = "/getApps";
        public static final String getDoctorAppsByType = "/getDoctorAppsByType";
        public static final String createAppRolesByAppId = "/createAppRolesByAppId";
        // ---------------- 开放平台 ----------------
        public static final String CheckField = "/app/checkField";
        public static final String CheckName = "/app/checkName";
        public static final String AppAuthClient = "/app/authClient";
        public static final String SimpleUpdate = "/app/simpleUpdate";
        //--------------- 医生工作平台 ---------------
        public static final String GetAppsRelationByUserIdAndParentAppId = "/app/getAppsByUserId";
        public static final String GetAppsRelationByUserJson = "/app/getAppsByUserJson";
        //--------------- 总支撑平台 ---------------
        public static final String SaveAppsRelation = "/app/saveAppsRelation";
        public static final String GetUserApp = "/app/role/get";
    }
    public static class AppApi {
        public static final String AppApis = "/appApi";
        public static final String AppApi = "/appApi/{id}";
        public static final String AppApisNoPage = "/appApiNoPage";
        public static final String AppApiSearch = "/appApi/search";
        public static final String AppApiAuth = "/appApiAuth";
        public static final String Save = "/appApi/save";
        public static final String Delete = "/appApi/delete";
        public static final String Update = "/appApi/update";
        public static final String Page = "/appApi/page";
        public static final String AuthList = "/appApi/authList";
        public static final String AuthApi = "/appApi/authApi";
        public static final String CheckName = "/appApi/checkName";
    }
    public static class AppApiCategory {
        public static final String Base = "/appApiCategory";
        public static final String Check = "/appApiCategory/check";
    }
    public static class AppApiErrorCode {
        public static final String Base = "/appApiErrorCode";
        public static final String CheckCode = "/appApiErrorCode/checkCode";
    }
    public static class AppFeature {
        public static final String AppFeatures = "/appFeature";
        public static final String FilterFeatureList = "/filterFeatureList";
        public static final String FilterFeatureNoPage = "/filterFeatureNoPage";
        public static final String FilterFeatureNoPageSorts = "/filterFeatureNoPageSorts";
        public static final String AppFeature = "/appFeature/{id}";
        public static final String FindAppMenus = "/appFeature/findAppMenus";
    }
    public static class AppVersion {
        public static final String FindAppVersion = "/appVersion/getAppVersion";
    }
    public static class AppApiParameter {
        public static final String AppApiParameters = "/appApiParameter";
        public static final String AppApiParameter = "/appApiParameter/{id}";
    }
    public static class AppApiResponse {
        public static final String AppApiResponses = "/appApiResponse";
        public static final String AppApiResponse = "/appApiResponse/{id}";
    }
    public static class UserApp {
        public static final String UserAppList = "/userAppList";
        public static final String UserAppShow = "/userApp/show";
        public static final String GetUserAppListById = "/userApp/getUserAppByAppId";
        public static final String CreateUserApp = "/userApp/createUserApp";
    }
    public static class Packages {
        public static final String Packages = "/packages";
        public static final String PackagesByFilter = "/packagesByFilter";
        public static final String Package = "/packages/{id}";
        public static final String Analyze = "/packages/analyze/{id}";
        public static final String Resolve = "/packages/resolve/{id}";
        public static final String Analyzes = "/packages/analyze";
        public static final String Resolves = "/packages/resolve";
        public static final String Status = "/packages/status";
        public static final String Search = "/packages/search";
        public static final String Download = "/packages/download/{id}";
        public static final String PackageCrypto = "/packages/crypto";
        public static final String Queue = "/packages/queue";
        public static final String UploadProvincialQueueSize = "/packages/queueSize/UploadProvincial";//上传省平台队列
        public static final String Migrate = "/packages/migrate";
    }
    //非病人维度
    public static class DatasetPackages {
        public static final String Packages = "/datasetPackages";
        public static final String AcquirePackage = "/datasetPackages/acquire";
        public static final String Package = "/datasetPackages/{id}";
        public static final String PackageResolve = "/datasetPackages/resolve";
        public static final String PackageSearch = "/datasetPackages/search";
        public static final String PackageDownloads = "/datasetPackages/{id}/downloads";
        public static final String ResolveMessage = "/datasetPackages/message/resolve";
        public static final String MessageTimer = "/datasetPackages/message/timer";
    }
    public static class PackageAnalyzer {
        public static final String Scheduler = "/packAnalyzer/scheduler";
        public static final String Status = "/packAnalyzer/status/{id}";
        public static final String DailyReport = "/packAnalyzer/dailyReport";
        public static final String List = "/packAnalyzer/list";
        public static final String FindByField = "/packAnalyzer/findByField";
        public static final String FindBySql = "/packAnalyzer/findBySql";
        public static final String EsSaveData = "/packAnalyzer/esSaveData";
        public static final String QcEmpty = "/packAnalyzer/qc/check/empty";
        public static final String QcType = "/packAnalyzer/qc/check/type";
        public static final String QcFormat = "/packAnalyzer/qc/check/format";
        public static final String QcValue = "/packAnalyzer/qc/check/value";
        public static final String UpdateStatus = "/packAnalyzer/updateStatus";
        public static final String Analyzer = "/packAnalyzer/analyzer";
    }
    public static class PackageResolve {
        public static final String Scheduler = "/resolve/scheduler";
        public static final String Resolve = "/resolve/{id}";
        public static final String Local = "/resolve/local/{id}";
        public static final String Fetch = "/resolve/fetch/{id}";
        public static final String Immediate = "/resolve/immediate";
        public static final String ArchiveRelation = "/resolve/archiveRelation"; //档案关联
    }
    public static class Patients {
        public static final String GetUserCards = "/getUserCards";// 就诊卡列表
        public static final String CardApply = "/patientCards/apply";     //卡认证申请
        public static final String CardList = "/patientCards/list";  //	个人账号列表
        public static final String CardApplyListManager = "/patientCards/manager/applyList";//	管理员--卡认证列表
        public static final String CardVerifyManager = "/patientCards/manager/verify";//	管理员--卡认证审核操作
        public static final String CardBindManager = "/patientCards/manager/bind";//	管理员--后台绑卡操作
        public static final String ArchiveRelationManager = "/patientCards/manager/archiveRelation";//	管理员--卡档案关联审核
        public static final String ArchiveApply = "/patientArchive/apply";//	档案认领申请(临时卡)
        public static final String ArchiveApplyList = "/patientArchive/applyList";//	个人档案认领列表
        public static final String ArchiveList = "/patientArchive/list";//个人档案列表
        public static final String ArchiveUnbind = "/patientArchive/unbind";//	管理员--通过卡号获取未认领档案
        public static final String ArchiveApplyListManager = "/patientArchive/manager/applyList";//	管理员--档案认领列表
        public static final String ArchiveVerifyManager = "/patientArchive/manager/verify";//	管理员--档案认领审核操作
        public static final String ArchiveRelation = "/patientArchive/archiveRelation";//新建档案关联
        public static final String GetArchiveList = "/patientArchive/getApplyList";//根据查询条件查询个人档案申请列表
        public static final String GetArchiveRelationList = "/patientArchive/getArRelationList";//根据查询条件查询个人档案申请列表
        public static final String GetArchiveRelation = "/patientArchive/{applyId}/getArRelation";//根据查询条件查询个人档案申请列表
        public static final String FindArchiveRelation = "/patient/findArchiveRelation";
        public static final String UpdateArchiveRelation = "/patient/updateArchiveRelation";
        public static final String DelArchiveRelation = "/patient/delArchiveRelation";
        public static final String MCardSave = "/medicalCards/save";// 就诊卡新增&保存
        public static final String MCardDel = "/medicalCards/del";//	就诊卡删除
        public static final String GetMCard = "/medicalCards/get";//就诊卡详情
        public static final String GetMCards = "/getMedicalCards";//	就诊卡列表
        public static final String MCardCheckCardNo = "/medicalCards/checkCardNo";//	校验卡是否唯一
        public static final String MCardGetMutiCardNo = "/medicalCards/getMutiCard";//	获取重复的卡列表
        public static final String MCarddataBatch = "/medicalCards/batch";//	批量添加
        public static final String Authentications = "/patient/authentications";
        public static final String Authentication = "/patient/Authentication/{id}";
        /******************************* 旧接口 **********************************************************/
        public static final String ArApplications = "/archive/applications";
        public static final String ArApplication = "/archive/applications/{id}";
        public static final String ArRelations = "/archive/relations";
        public static final String ArRelation = "/archive/relation/{id}";
        public static final String ArRelationsExistence = "/archive/relations/existence";
        /******************************* 旧接口 **********************************************************/
    }
    public static class Authentication {
        public static final String AccessToken = "/oauth/accessToken";
        public static final String ValidToken = "/oauth/validToken";
        public static final String Login = "/oauth/login";
        public static final String Logout = "/oauth/logout";
        public static final String VerifyCode = "/oauth/verifyCode";
        public static final String VerifyCodeExpire = "/oauth/verifyCodeExpire";
        public static final String VerifyCodeValidate = "/oauth/verifyCodeValidate";
    }
    public static class MessageRemind {
        public static final String MessageRemind = "/messageRemind";
        public static final String MessageRemindTop = "/messageRemindTop";
        public static final String MessageRemindCount = "/messageRemindCount";
        public static final String MessageRemindAdmin = "/messageRemind/admin/{messageRemind_id}";
        public static final String MessageRemindReaded = "/messageRemind/readed/{remindId}";
        public static final String MessageRemindByType = "/MessageRemindByType";
        public static final String MessageReminInfodByType = "/MessageRemindInfoInfoByType";
        public static final String MessageRemindByNotifie = "/MessageRemindByNotifie";
        public static final String UpdateMessageRemindByNotifie = "/UpdateMessageRemindByNotifie";
        public static final String MessageRemindSatisfactionSurvey = "/MessageRemind/SatisfactionSurvey";
    }
    public static class Portal {
        public static final String Login = "/portal/login";
        public static final String UserAppList = "/portal/userApp/list";
        public static final String UserAppShow = "/portal/userApp/show";
        public static final String MessageRemind = "/portal/messageRemind";
        public static final String MessageRemindCount = "/portal/messageRemind/count";
        public static final String MessageRemindRead = "/portal/messageRemind/read/{remindId}";
        public static final String NoticesTop = "/portal/notices/top";
        public static final String Feedback = "/portal/feedback";
        public static final String ResourceTop = "/portal/resource/top";
        public static final String QuotaCategoryOfChild = "/portal/quotaCategoryOfChild";
        public static final String TjQuotaWarn = "/portal/tj/tjQuotaWarn";
        public static final String Setting = "/portal/setting";
    }
    public static class PortalNotices {
        public static final String PortalNotices = "/portalNotices";
        public static final String PortalNoticesTop = "/portalNoticesTop";
        public static final String PortalNoticeAdmin = "/portalNotices/admin/{portalNotice_id}";
    }
    public static class PortalResources {
        public static final String PortalResources = "/portalResources";
        public static final String PortalResourcesTop = "/portalResourcesTop";
        public static final String PortalResourcesAdmin = "/portalResources/admin/{portalResources_id}";
    }
    public static class PortalFeedback {
        public static final String PortalFeedback = "/portalFeedback";
        public static final String PortalFeedbackAdmin = "/portalFeedback/admin/{portalFeedback_id}";
        public static final String PortalFeedBackByUserId = "/protalFeedback/findByUserId";
        public static final String pagePortalFeedback = "/pagePortalFeedback";
    }
    public static class PortalLogin {
        public static final String PortalLogin = "/login";
    }
    public static class PortalSetting {
        public static final String PortalSetting = "/portalSetting";
        public static final String PortalSettingTop = "/portalSettingTop";
        public static final String PortalSettingAdmin = "/portalSetting/admin/{portalSetting_id}";
    }
    public static class PortalStandards {
        public static final String PortalStandards = "/portalStandards";
        public static final String PortalStandardsAdmin = "/portalStandards/admin/{portalStandard_id}";
    }
    public static class Securities {
        public static final String UserKey = "/securities/users/{user_id}/key";
        public static final String UserKeyId = "/securities/users/{user_id}/key/id";
        public static final String UserPublicKey = "/securities/users/{user_id}/key/public";
        public static final String UserTokens = "/securities/users/{user_id}/tokens";
        public static final String UserToken = "/securities/users/{user_id}/tokens/{token_id}";
        public static final String OrganizationKey = "/securities/organizations/{org_code}/key";
        public static final String OrganizationPublicKey = "/securities/organizations/{org_code}/key/public";
        public static final String ClientTokens = "/securities/clients/{client_id}/tokens";
        public static final String Keys = "/securities/keys/{id}";
        public static final String deleteOrgKey = "/securities/org/keys/{org_code}";
        public static final String deleteUserKey = "/securities/user/keys/{user_id}";
        public static final String Tokens = "/securities/tokens/{id}";
    }
    public static class Standards {
        public static final String Caches = "/std/caches";
        public static final String Cache = "/std/caches/{version}";
        public static final String Sources = "/std/sources";
        public static final String NoPageSources = "/std/sources/no_paging";
        public static final String Source = "/std/sources/{id}";
        public static final String IsSourceCodeExist = "/std/sources/code_is_exist";
        public static final String NoPageTypes = "/std/types/no_paging";
        public static final String Types = "/std/types";
        public static final String Type = "/std/types/{id}";
        public static final String TypesCodeExistence = "/std/type/code/existence";
        public static final String TypeChildren = "/std/types/parent_id/childrens";
        public static final String TypesChildren = "/std/types/childrens";
        public static final String TypeList = "/cda_types/code_name";
        public static final String TypeParent = "/std/types/parent";
        public static final String TypeOther = "/std/types/{id}/other";
        public static final String Versions = "/std/versions";
        public static final String Version = "/std/versions/{version}";
        public static final String VersionInStageExist = "/std/versions/in_stage/existence";
        public static final String VersionCache = "/std/versions/{version}/cache";
        public static final String VersionNameExistence = "/std/version/name/existence";
        public static final String VersionBackStage = "/std/versions/{version}/back";
        public static final String VersionCommit = "/std/versions/{version}/commit";
        public static final String VersionRevert = "/std/versions/{version}/revert";
        public static final String VersionLatest = "/std/versions/latest";
        public static final String VersionLatestExistence = "/std/versions/{version}/latest/existence";
        public static final String Documents = "/std/documents";
        public static final String DocumentNoPage = "/std/document/noPage";
        public static final String Document = "/std/documents/{id}";
        public static final String DocumentList = "/std/documentsList";
        public static final String DocumentFileExistence = "/std/documents/{id}/file/existence";
        public static final String DocumentCreateFile = "/std/documents/{id}/file/create";
        public static final String DocumentGetFile = "/std/documents/{id}/file";
        public static final String DocumentDataSet = "/std/documents/data_set";
        public static final String DocumentDataSetList = "/std/documents/data_set_list";
        public static final String DataSetRelationships = "/std/documents/data_set_relationships";
        public static final String DataSetRelationshipsNoPage = "/std/documents/data_set_relationships/noPage";
        public static final String DataSetRelationship = "/std/documents/data_set_relationships/{id}";
        public static final String Dictionaries = "/std/dictionaries";
        public static final String NoPageDictionaries = "/std/dictionaries/no_paging";
        public static final String Dictionary = "/std/dictionaries/{id}";
        public static final String DictionaryCode = "/std/dictionaries/code";
        public static final String MetaDataWithDict = "/std/data_set/{data_set_id}/meta_datas/{meta_data_id}/dictionaries";
        public static final String DictCodeIsExist = "/std/dictionaries/is_exist/code";
        public static final String DictOther = "/std/dictionaries/{id}/other";
        public static final String DictParent = "/std/dictionaries/{id}/parent";
        public static final String DictCodesExistence = "/dict/codes/existence";
        public static final String DictEntryBatch = "/dict/entry/batch";
        public static final String Entry = "/std/dictionaries/entries/{id}";
        public static final String Entries = "/std/dictionaries/entries";
        public static final String EntriesWithDictionary = "/std/dictionary/{dict_id}/entries";
        public static final String EntryCodeIsExist = "/std/dictionaries/entries/is_exist/code";
        public static final String DataSets = "/std/data_sets";
        public static final String NoPageDataSets = "/std/data_sets/no_paging";
        public static final String DataSet = "/std/data_sets/{id}";
        public static final String DataSetsName = "/std/data_sets/name";
        public static final String DataSetCodeIsExist = "/std/data_set/is_exist/code";
        public static final String DataSetsIds = "/std/{ids}data_sets";
        public static final String DataSetsBatch = "/std/data_set/bacth";
        public static final String GetDataSetByCode = "/std/data_set/getDataSetByCode";
        public static final String MetaDatas = "/std/data_sets/meta_datas";
        public static final String MetaData = "/std/data_sets/meta_datas/{id}";
        public static final String MetaDataCodeExistence = "/std/data_sets/{data_set_id}/meta_data/inner_code/existence";
        public static final String MetaDataNameExistence = "/std/data_sets/{data_set_id}/meta_data/name/existence";
        public static final String MetaDatasName = "/std/data_sets/meta_datas/name";
        public static final String MetaDatasWithDataSet = "/std/data_sets/{data_set_id}/meta_datas";
        public static final String DispatchLogs = "/std/dispatches/logs";
        public static final String Dispatch = "/std/dispatches/{id}";
        public static final String Dispatches = "/std/dispatches";
        public static final String AdaptMeta = "/std/adapt/meta";
        public static final String AdaptDict = "/std/adapt/dict";
    }
    public static class Doctors {
        public static final String Doctors = "/doctors";
        public static final String DoctorsExistence = "/doctors/{doctor_code}/existence";
        public static final String DoctorAdmin = "/doctors/admin/{doctor_id}";
        public static final String DoctorByIdCardNo = "/doctor/{idCardNo}";
        public static final String DoctorPhoneExistence = "/doctor/phone/existence";
        public static final String DoctorBatch = "/doctor/batch";
        public static final String DoctorOnePhoneExistence = "/doctor/onePhone/existence";
        public static final String DoctorEmailExistence = "/doctor/email/existence";
        public static final String DoctorsIdCardNoExistence = "/doctors/{doctor_idCardNo}/CardNoExist";
        public static final String DoctoridCardNoExistence = "/doctor/idCardNo/existence";
        public static final String DoctorOnlyUpdateD = "/doctors/updateOnlyDoctor";
    }
    public static class Users {
        public static final String Users = "/users";
        public static final String UsersOfApp = "/usersOfApp";
        public static final String User = "/users/{user_name}";
        public static final String UserExistence = "/users/{user_name}/existence";
        public static final String UserVerification = "/users/verification";
        public static final String UserAdmin = "/users/admin/{user_id}";
        public static final String UserAdminPassword = "/users/admin/{user_id}/password";
        public static final String UserAdminPasswordReset = "/users/admin/{user_id}/password_reset";
        public static final String UserAdminKey = "/users/admin/{user_id}/key";
        public static final String UserAdminContact = "/users/admin/{user_id}/contact";
        public static final String UserIdCardNoExistence = "/user/id_card_no/existence";
        public static final String UserEmailNoExistence = "/user/email/existence";
        public static final String UserTelephoneNoExistence = "/user/telephone/existence";
        public static final String UserPhoneExistence = "/user/phone/existence";
        public static final String UserOnePhoneExistence = "/user/onePhone/existence";
        public static final String UserEmailExistence = "/user/email/existence";
        public static final String UseridCardNoExistence = "/user/idCardNo/existence";
        public static final String UserByIdCardNo = "/user/idCardNo/userByIdCardNo";
        public static final String UpdateSystemUser = "/updateSystemUser";
        public static final String GetOrgAndDeptRelation = "/users/getOrgAndDeptRelation";
        public static final String InitializeSystemUser = "/users/initialize";
        public static final String UsersByTel = "/users/tel";
        public static final String H5Handshake = "/users/h5/handshake";
        public static final String UsersOfAppPhoneExistence = "/usersOfApp/user/onePhone/existence";
        public static final String GetUserOfUsersOfApp = "/usersOfApp/users/getUserOfUsersOfApp";
        public static final String GetUserInfoAndRolesByUserIdOrCode = "/users/orgDeptMember/getUserInfoAndRolesByUserIdOrCode";
        public static final String Save = "/users/save";
        public static final String Update = "/users/update";
        public static final String Check = "/users/check";
        public static final String ChangePassword = "/users/changePassword";
        public static final String DistributeSecurityKey = "/users/distributeSecurityKey";
        public static final String GetSecurityKey = "/users/getSecurityKey";
        public static final String changePasswordByTelephone = "/usersOfApp/users/changePasswordByTelephone";
        public static final String changePasswordByOldPassword = "/users/changePasswordByOldPassword";
        public static final String updateUserTelePhone = "/users/updateTelephone";
        public static final String initializationAuthorization = "/users/initializationAuthorization";
    }
    public static class TelVerification {
        public static final String TelVerificationMsgSendMsg = "/usersOfApp/msg/sendMsg";
        public static final String TelVerificationMsgValidate = "/usersOfApp/msg/validate";
    }
    public static class Roles {
        public static final String Role = "/roles/role";
        public static final String RoleId = "/roles/role/{id}";
        public static final String Roles = "/roles/roles";
        public static final String RolesNoPage = "/roles/roles/no_page";
        public static final String RoleNameExistence = "/roles/name/existence";
        public static final String RoleCodeExistence = "/roles/code/existence";
        public static final String RoleBatchAdd = "/roles/roleBatchAdd";
        public static final String RoleFindByField = "/roles/findByField";
        public static final String RoleFindByUserId = "/roles/findByUserId";
        public static final String RoleFindByUserIdAndAppId = "/roles/findByUserIdAndAppId";
        public static final String RoleUser = "/roles/role_user";
        public static final String RoleUserByUserId = "/roles/role_user/{user_id}";
        public static final String RoleUsers = "/roles/role_users";
        public static final String RoleUsersNoPage = "/roles/role_users/no_page";
        public static final String NoPageCategoriesAndReport = "/roles/report/getCategoryAndReportNoPage";
        public static final String RoleOrg = "/roles/role_org";
        public static final String RoleOrgs = "/roles/role_orgs";
        public static final String RoleOrgsNoPage = "/roles/role_orgs/no_page";
        public static final String RoleFeature = "/roles/role_feature";
        public static final String RoleFeatureId = "/roles/role_feature/{id}";
        public static final String RoleFeatureByRoleId = "/roles/role_feature/role_id";
        public static final String RoleFeatures = "/roles/role_features";
        public static final String RoleFeaturesNoPage = "/roles/role_features/no_page";
        public static final String RoleFeatureExistence = "/roles/role_feature/existence";
        public static final String HasPermission = "/roles/role_feature/hasPermission";
        public static final String RoleApp = "/roles/role_app";
        public static final String RoleAppId = "/roles/role_app/{id}";
        public static final String RoleApps = "/roles/role_apps";
        public static final String RoleAppsNoPage = "/roles/role_apps/no_paging";
        public static final String RoleApi = "/roles/role_api";
        public static final String RoleApiId = "/roles/role_api/{id}";
        public static final String RoleApiByRoleId = "/roles/role_api/role_id";
        public static final String RoleApis = "/roles/role_apis";
        public static final String RoleApisNoPage = "/roles/role_apis/no_paging";
        public static final String RoleApisExistence = "/roles/role_api/existence";
        public static final String BatchAddRoleReportRelation = "/roles/role_report/batchAddRoleReportRelation";
        public static final String DeleteRoleReportRelationByRoleId = "/roles/role_report/deleteByRoleId";
        public static final String SearchRoleReportRelation = "/roles/role_report/search";
        public static final String SearchRoleReportRelationNoPage = "/roles/role_report/searchNoPage";
        public static final String SearchRoleReportRelationIsReportAccredited = "/roles/role_report/isReportAccredited";
        public static final String ClientRole = "/roles/clientRole";
        public static final String RoleUserTypeInit = "/roles/usertype/init";
        public static final String RoleUserTypeUpdate = "/roles/usertype/update";
        public static final String UserOrgRela = "/user/org/relation";
        public static final String CreateUserType = "/user/usertype";
        public static final String SearchUserType = "/user/searchUserType";
        public static final String UpdateUserType = "/user/updateUserType";
        public static final String GetUserTypeRoles = "/user/usertype/roles";
        public static final String GetUserTypeById = "/user/getUserTypeById";
        public static final String SaveUserTypeRoles = "/user/saveUserTypeRoles";
        public static final String ValidateUserType = "/user/validateUserType";
    }
    public static class HealthProfile {
        public static final String Profiles = "/health_profiles";
        public static final String ProfileSearch = "/health_profiles/search";
        public static final String Profile = "/health_profiles/{profile_id}";
        public static final String ProfileDocument = "/health_profiles/{profile_id}/documents/{document_id}";
        public static final String Diagnosis = "/health_profile/disease/diagnosis";
        public static final String MajorIssues = "/health_profile/disease/major_issues";
        public static final String Prescriptions = "/health_profile/prescriptions";
        public static final String Drugs = "/health_profile/drugs";
        public static final String Lis = "/health_profile/lis";
        public static final String PhysicalExam = "/health_profile/physical_examinations";
        public static final String PastHistories = "/health_profile/past_histories";
    }
    public static class ProfileTemplate {
        public static final String Templates = "/templates";
        public static final String TemplatesDownloads = "/templates/downloads";
        public static final String Template = "/templates/{id}";
        public static final String TemplateCtn = "/templates/{id}/content";
        public static final String TemplateTitleExistence = "/template/title/existence";
    }
    public static class SanofiSupport {
        public static final String PhysicSigns = "/sanofi/physic_signs";
    }
    public static class ArchiveSecurity {
        public static final String ArchivePrivate = "/archiveprivate/{userId}";
        public static final String ArchivePrivateRowKey = "/archiveprivate/{userId}/{rowKey}";
        public static final String ArchiveSecuritySetting = "/archivesecurity";
        public static final String ArchiveSecuritySettingUser = "/archivesecurity/{user_id}";
        public static final String ArchiveSecuritySettingKeyAuthen = "/archivesecurity/{user_id}/securitykey/authentication";
        public static final String ArchiveLogs = "/archivelogs";
        public static final String AuthorizeApps = "/authorizeapps";
        public static final String AuthorizeAppsId = "/authorizeapps/{id}";
        public static final String AuthorizeAppsSubjects = "/authorizeapps/subjects";
        public static final String AuthorizeAppsSubjectsId = "/authorizeapps/subjects/{id}";
        public static final String AuthorizeSubjects = "/authorizesubjects";
        public static final String AuthorizeSubjectsResources = "/authorizesubjects/{subjectId}/resources";
        public static final String AuthorizeDoctors = "/authorizedoctors";
        public static final String AuthorizeDoctorsId = "/authorizedoctors/{id}";
        public static final String AuthorizeDoctorsIdAlteration = "/authorizedoctors/{id}/alteration";
        public static final String AuthorizeDoctorsIdAuthorization = "/authorizedoctors/{id}/authorization";
        public static final String MessageReplyTempates = "/messagereplytemplates";
        public static final String MessageTempates = "/messagetemplates";
        public static final String MessageTempatesCode = "/messagetemplates/{messageTempCode}";
        public static final String MessageSend = "/messagesend";
        public static final String MessageSendId = "/messagesend/{id}";
        public static final String MessageReply = "/messagereply";
    }
    /**
     * 病历夹接口
     */
    public static class MedicalRecords {
        //公用接口
        public static final String SystemAccess = "/medicalRecords/systemAccess"; //系统接入接口,通过单点登录获取最新病历
        public static final String SystemDict = "/medicalRecords/systemDict";
        public static final String SystemDictEntry = "/medicalRecords/systemDictEntry"; //获取系统字典项
        public static final String ICD10Dict = "/medicalRecords/icd10Dict"; //获取ICD10字典
        public static final String ImgList = "/medicalRecords/imgList"; //图片列表
        //病历接口
        public static final String AddRecord = "/medicalRecords/record/addRecord"; //新增病历
        public static final String MedicalRecordRelated = "/medicalRecords/record/related"; //	病历关联记录
        public static final String MedicalRecord = "/medicalRecords/record/{record_id}"; //	病历信息管理
        public static final String MedicalInfo = "/medicalRecords/record/{record_id}/medicalInfo"; //	病情信息管理
        public static final String MedicalLabel = "/medicalRecords/record/{record_id}/label"; //获取病历标签/批量保存病历标签
        public static final String MedicalReport = "/medicalRecords/record/{record_id}/report/{report_id}"; //获取某病历某报告
        public static final String MedicalReports = "/medicalRecords/record/{record_id}/reports"; //获取某病历某报告
        public static final String MedicalReportManage = "/medicalRecords/record/{record_id}/report"; //新增/修改/导入报告/删除报告
        public static final String ImportMedicalPrescription = "/medicalRecords/record/{record_id}/drug/import"; //导入处方
        public static final String MedicalDrug = "/medicalRecords/record/{record_id}/drug"; //新增/修改病历用药记录/删除病历用药记录/获取病历用药记录
        public static final String MedicalShare = "/medicalRecords/record/{record_id}/share"; //病历分享
        public static final String MedicalDiagnosis = "/medicalRecords/record/{record_id}/diagnosis";//病历诊断
        //医生接口
        public static final String DoctorInfo = "/medicalRecords/doctor/{doctor_id}"; //获取医生信息
        public static final String DoctorLabelClass = "/medicalRecords/doctor/{doctor_id}/labelClass"; //获取全部医生标签类别
        public static final String DoctorLabel = "/medicalRecords/doctor/{doctor_id}/label"; //获取医生标签
        public static final String DoctorTemplate = "/medicalRecords/doctor/{doctor_id}/template"; //获取医生模板/批量保存医生模板
        public static final String DoctorRecords = "/medicalRecords/doctor/{doctor_id}/records"; //获取医生病历
        public static final String DoctorText = "/medicalRecords/doctor/{doctor_id}/text"; //上传医生文本素材/获取医生文本素材
        public static final String DoctorTextDialog = "/medicalRecords/doctor/{doctor_id}/textDialog"; //获取医生文本对话
        public static final String DoctorImg = "/medicalRecords/doctor/{doctor_id}/img"; //上传医生图片素材/获取医生图片素材
        public static final String DoctorICD10 = "/medicalRecords/doctor/{doctor_id}/icd10"; //	获取医生ICD10
        public static final String DoctorInfoManage = "/medicalRecords/doctor/info"; //	新增医生信息/修改医生信息
        public static final String DoctorLabelClassManage = "/medicalRecords/doctor/labelClass"; //	新增医生标签类别/修改医生标签类别/删除医生标签类别
        //患者接口
        public static final String PatientInfo = "/medicalRecords/patient/{patient_id}/info"; //	获取患者基本信息
        public static final String PatientInfoManage = "/medicalRecords/patient/info"; //	新增患者信息/修改患者信息
        public static final String PatientRecords = "/medicalRecords/patient/{patient_id}/records"; //	获取患者病历
        public static final String PatientICD10 = "/medicalRecords/patient/{patient_id}/icd10"; //	获取患者ICD10
    }
    public static class DailyStatistics {
        //日常监测
        public static final String StatisticsProfile = "/statistics/profiles";
        public static final String StatisticsOutpatientHospital = "/statistics/outpatientHospital";
        public static final String StatisticsDailyReport = "/statistics/dailyReport";
        public static final String StatisticsDailyReportFiles = "/statistics/dailyReportFiles";
        //住院
        public static final String StatisticsHospitalization = "/statistics/hospitalization/{orgCode}";
        public static final String StatisticsHospitalizationDept = "/statistics/hospitalization/{orgCode}/dept";
        public static final String StatisticsHospitalizationSex = "/statistics/hospitalization/{orgCode}/sex";
        public static final String StatisticsHospitalizationDisease = "/statistics/hospitalization/{orgCode}/disease";
        //门诊
        public static final String StatisticsOutpatient = "/statistics/outpatient/{orgCode}";
        public static final String StatisticsOutpatientDept = "/statistics/outpatient/{orgCode}/dept";
        public static final String StatisticsOutpatientSex = "/statistics/outpatient/{orgCode}/sex";
        //入库统计
        public static final String StatisticsProfileCreateDate = "/statistics/profiles/createDate";
        public static final String StatisticsProfileEventDate = "/statistics/profiles/eventDate";
        public static final String StatisticsProfileIdNotNull = "/statistics/profiles/idNotNull";
        public static final String StatisticsProfileEventDateGroup = "/statistics/profiles/eventDateGroup";
    }
    /**
     * Redis服务
     */
    public static class Redis {
        //初始化缓存
        public static final String InitHealthProblem = "/redis/init/healthProblem";
        public static final String InitIcd10 = "/redis/init/icd10";
        public static final String InitOrgName = "/redis/init/orgName";
        public static final String InitOrgArea = "/redis/init/orgArea";
        public static final String InitOrgSaasArea = "/redis/init/orgSaasArea";
        public static final String InitOrgSaasOrg = "/redis/init/orgSaasOrg";
        public static final String InitRsAdapterMeta = "/redis/init/rsAdapterMeta/{id}";
        public static final String InitRsMetadataDict = "/redis/init/rsMetadataDict";
        public static final String InitAreaName = "/redis/init/areaName";
        //清除缓存
        public static final String Delete = "/redis/delete";
        //更新缓存
        public static final String UpdateOrgName = "/redis/update/orgName";
        public static final String UpdateOrgArea = "/redis/update/orgArea";
        public static final String UpdateOrgSaasArea = "/redis/update/orgSaasArea";
        public static final String UpdateOrgSaasOrg = "/redis/update/orgSaasOrg";
        //获取缓存数据
        public static final String HealthProblem = "/redis/healthProblem";
        public static final String Icd10Name = "/redis/icd10Name";
        public static final String Icd10ChronicInfo = "/redis/icd10ChronicInfo";
        public static final String Icd10HpCode = "/redis/icd10HpCode";
        public static final String OrgName = "/redis/orgName";
        public static final String OrgArea = "/redis/orgArea";
        public static final String OrgSaasArea = "/redis/orgSaasArea";
        public static final String OrgSaasOrg = "/redis/orgSaasOrg";
        //App前端Redis
        public static final String AppGetRedisValue = "/redis/getAppClientValue";
        public static final String AppSetRedisValue = "/redis/setAppClientValue";
        public static final String AppSetRedisJsonValue = "/redis/setAppClientJsonValue";
        public static final String AppDeleteRedisValue = "/redis/deleteAppClientValue";
        //资源化相关Redis
        public static final String RsAdapterMetadata = "/redis/rsAdapterMetaData";
        public static final String RsMetadataDict = "/redis/rsMetadataDict";
        //标准相关Redis
        public static final String StdVersion = "/redis/stdVersion";
        public static final String StdDataSetCode = "/redis/stdDataSetCode";
        public static final String StdDataSetName = "/redis/stdDataSetName";
        public static final String StdDataSetNameByCode = "/redis/stdDataSetNameByCode";
        public static final String StdDataSetMultiRecord = "/redis/stdDataSetMultiRecord";
        public static final String StdMetadataCodes = "/redis/stdMetadataCodes";
        public static final String StdMetadataType = "/redis/stdMetaDataType";
        public static final String StdMetadataFormat = "/redis/stdMetaData/format";
        public static final String StdMetadataNullable = "/redis/stdMetaData/nullable";
        public static final String StdMetadataDict = "/redis/stdMetaDataDict";
        public static final String StdDictEntryValue = "/redis/stdDictEntryValue";
        public static final String StdDictEntryValueExist = "/redis/stdDictEntry/ValueExist";
        public static final String StdDictEntryCodeExist = "/redis/stdDictEntry/CodeExist";
        // Redis消息队列
        public static class MqChannel {
            public static final String Prefix = "/redis/mq/channel/";
            public static final String GetById = "/redis/mq/channel/{id}";
            public static final String Search = "/redis/mq/channel/search";
            public static final String Save = "/redis/mq/channel/save";
            public static final String Delete = "/redis/mq/channel/delete";
            public static final String IsUniqueChannel = "/redis/mq/channel/isUniqueChannel";
            public static final String IsUniqueChannelName = "/redis/mq/channel/isUniqueChannelName";
            public static final String IsExist = "/redis/mq/channel/isExist";
            public static final String SendMessage = "/redis/mq/channel/sendMessage";
        }
        // Redis消息订阅者
        public static class MqSubscriber {
            public static final String Prefix = "/redis/mq/subscriber/";
            public static final String GetById = "/redis/mq/subscriber/{id}";
            public static final String Search = "/redis/mq/subscriber/search";
            public static final String Save = "/redis/mq/subscriber/save";
            public static final String Delete = "/redis/mq/subscriber/delete";
            public static final String IsUniqueAppId = "/redis/mq/subscriber/isUniqueAppId";
            public static final String IsUniqueSubscribedUrl = "/redis/mq/subscriber/isUniqueSubscribedUrl";
            public static final String IsExist = "/redis/mq/subscriber/isExist";
            public static final String Unsubscribe = "/redis/mq/subscriber/unsubscribe";
        }
        // Redis消息发布者
        public static class MqPublisher {
            public static final String Prefix = "/redis/mq/publisher/";
            public static final String GetById = "/redis/mq/publisher/{id}";
            public static final String Search = "/redis/mq/publisher/search";
            public static final String Save = "/redis/mq/publisher/save";
            public static final String Delete = "/redis/mq/publisher/delete";
            public static final String IsUniqueAppId = "/redis/mq/publisher/isUniqueAppId";
        }
        // 缓存分类
        public static class CacheCategory {
            public static final String Prefix = "/redis/cache/category/";
            public static final String GetById = "/redis/cache/category/{id}";
            public static final String Search = "/redis/cache/category/search";
            public static final String SearchNoPage = "/redis/cache/category/searchNoPage";
            public static final String Save = "/redis/cache/category/save";
            public static final String Delete = "/redis/cache/category/delete";
            public static final String IsUniqueName = "/redis/cache/category/isUniqueName";
            public static final String IsUniqueCode = "/redis/cache/category/isUniqueCode";
        }
        // 缓存授权
        public static class CacheAuthorization {
            public static final String Prefix = "/redis/cache/authorization/";
            public static final String GetById = "/redis/cache/authorization/{id}";
            public static final String Search = "/redis/cache/authorization/search";
            public static final String Save = "/redis/cache/authorization/save";
            public static final String Delete = "/redis/cache/authorization/delete";
            public static final String IsUniqueAppId = "/redis/cache/authorization/isUniqueAppId";
        }
        // 缓存Key规则
        public static class CacheKeyRule {
            public static final String Prefix = "/redis/cache/keyRule/";
            public static final String GetById = "/redis/cache/keyRule/{id}";
            public static final String Search = "/redis/cache/keyRule/search";
            public static final String Save = "/redis/cache/keyRule/save";
            public static final String Delete = "/redis/cache/keyRule/delete";
            public static final String IsUniqueName = "/redis/cache/keyRule/isUniqueName";
            public static final String IsUniqueCode = "/redis/cache/keyRule/isUniqueCode";
            public static final String IsUniqueExpression = "/redis/cache/keyRule/isUniqueExpression";
        }
        // 缓存操作
        public static class CacheOperation {
            public static final String Get = "/redis/cache/operation/get";
            public static final String Set = "/redis/cache/operation/set";
            public static final String Remove = "/redis/cache/operation/remove";
        }
        // 缓存操作
        public static class CacheStatistics {
            public static final String GetCategoryKeys = "/redis/cache/statistics/getCategoryKeys";
            public static final String GetCategoryMemory = "/redis/cache/statistics/getCategoryMemory";
        }
        // 接收订阅消息
        public static class SubscribeMessage {
            public static final String ReceiveResponseTime = "/redis/subscribeMessage/receiveResponseTime";
        }
    }
    /**
     * 行政区划服务
     */
    public static class Geography {
        public static final String Address = "/geographies/{id}";//根据地址编号查询地址
        public static final String AddressCanonical = "geographies/{id}/canonical";//根据地址编号获取地址中文字符串全拼
        public static final String Geographies = "/geographies"; //地址增改查
        public static final String GeographiesDelete = "geographies/{id}";
        public static final String GeographiesNull = "/geographies/is_null";//判断是否是个空地址
        public static final String AddressDictByLevel = "/geography_entries/level/{level}";//根据等级查询行政区划地址
        public static final String AddressDictByPid = "/geography_entries/pid/{pid}";//根据上级编号查询行政区划地址
        public static final String AddressDict = "/geography_entries/{id}";//根据id查询行政区划地址
        public static final String AddressDictList = "/geography_entries_list";  //获取多条行政区划地址
        public static final String AddressDictAll = "/geography_entries/all";    //获取全部行政区划地址
        public static final String AddressDictByFields = "/geography_entries/getAddressDict";     //根据地址中文名 查询地址编号
        public static final String GetAddressNameByCode = "/geography/GetAddressNameByCode";     //根据地址中文名 查询地址编号
    }
    public static class Report {
        public static final String GetQcDailyReportList = "/report/getQcDailyReportList";
        public static final String QcDailyReport = "/report/qcDailyReport";
        public static final String GetEventDataReport = "/report/getEventDataReport";
        public static final String AddQcDailyReportDetailList = "/report/addQcDailyReportDetailList";
        public static final String AddOrUpdateQcDailyReportDetail = "/report/addorUpdateQcDailyReportDetail";
        public static final String GetQcDailyReportDetail = "/report/getQcDailyReportDetail";
        public static final String GetQcDailyReportPageList = "/report/getQcDailyReportPageList";
        public static final String GetJsonArchives = "/report/getGetJsonArchives";
        public static final String GetArchivesInfo = "/report/getArchivesInfo";
        public static final String GetQcDailyReportDatasetsList = "/report/getQcDailyReportDatasetsList";
        public static final String QcDailyReportDatasets = "/report/qcDailyReportDatasets";
        public static final String GetQcDailyReportDatasetList = "/report/getQcDailyReportDatasetList";
        public static final String QcDailyReportDataset = "/report/qcDailyReportDataset";
        public static final String AddQcDailyDatasetDetailList = "/report/addQcDailyDatasetDetailList";
        public static final String GetQcDailyReportMetadataList = "/report/getQcDailyReportMetadataList";
        public static final String QcDailyReportMetadata = "/report/qcDailyReportMetadata";
        public static final String AddQcDailyMetadataDetailList = "/report/addQcDailyMetadataDetailList";
        public static final String GetQcQuotaDictList = "/report/getQcQuotaDictList";
        public static final String QcQuotaDict = "/report/qcQuotaDict";
        public static final String GetQcQuotaResultList = "/report/getQcQuotaResultList";
        public static final String QcQuotaResult = "/report/qcQuotaResult";
        public static final String QcDailyReportReolve = "/report/qcDailyReportReolve";
        public static final String GetQcQuotaOrgIntegrity = "/report/getQcQuotaOrgIntegrity";
        public static final String GetQcQuotaIntegrity = "/report/getQcQuotaIntegrity";
        public static final String QcQuotaList = "/report/qcQuotaList";
        public static final String GetQcDailyIntegrity = "/report/getQcDailyIntegrity";
        public static final String GetQcOverAllIntegrity = "/report/getQcOverAllIntegrity";
        public static final String GetQcOverAllOrgIntegrity = "/report/getQcOverAllOrgIntegrity";
        public static final String GetQcQuotaDailyIntegrity = "/report/getQcQuotaDailyIntegrity";
        public static final String GetQcQuotaByLocation = "/report/getQcQuotaByLocation";
        public static final String QcDailyStatisticsStorage = "/report/qcDailyStatisticsStorage";
        public static final String QcDailyStatisticsStorageByDate = "/report/qcDailyStatisticsStorageByDate";
        public static final String QcDailyStatisticsIdentify = "/report/qcDailyStatisticsIdentify";
    }
    public static class TJ {
        public static final String GetTjDimensionMainList = "/tj/getTjDimensionMainList";
        public static final String TjDimensionMain = "/tj/tjDimensionMain";
        public static final String TjDimensionMainId = "/tj/tjDimensionMainId/{id}";
        public static final String TjDimensionMainCode = "/tj/tjDimensionMainCode";
        public static final String TjDimensionMainName = "/tj/tjDimensionMainName";
        public static final String GetTjDimensionMainInfoList = "/tj/getTjDimensionMainInfoList";
        public static final String GetTjDimensionSlaveList = "/tj/getTjDimensionSlaveList";
        public static final String TjDimensionSlaveId = "/tj/tjDimensionSlaveId/{id}";
        public static final String TjDimensionSlave = "/tj/tjDimensionSlave";
        public static final String TjDimensionSlaveCode = "/tj/tjDimensionSlaveCode";
        public static final String TjDimensionSlaveName = "/tj/tjDimensionSlaveName";
        public static final String GetTjDimensionSlaveInfoList = "/tj/getTjDimensionSlaveInfoList";
        public static final String GetTjDimensionSlaveByCode = "/tj/getTjDimensionSlaveByCode";
        public static final String GetTjQuotaDimensionMainList = "/tj/getTjQuotaDimensionMainList";
        public static final String TjQuotaDimensionMain = "/tj/tjQuotaDimensionMain";
        public static final String AddTjQuotaDimensionMain = "/tj/addTjQuotaDimensionMain";
        public static final String GetTjQuotaDimensionMainAll = "/tj/getTjQuotaDimensionMainAll";
        public static final String GetTjQuotaDimensionSlaveList = "/tj/getTjQuotaDimensionSlaveList";
        public static final String TjQuotaDimensionSlave = "/tj/tjQuotaDimensionSlave";
        public static final String AddTjQuotaDimensionSlave = "/tj/addTjQuotaDimensionSlave";
        public static final String GetTjQuotaDimensionSlaveAll = "/tj/getTjQuotaDimensionSlaveAll";
        public static final String DeleteSlaveByQuotaCode = "/tj/deleteSlaveByQuotaCode";
        public static final String GetDimensionSlaveByQuotaCode = "/tj/getDimensionSlaveByQuotaCode";
        public static final String GetTjQuotaSynthesiseDimension = "/tj/getTjQuotaSynthesiseDimension";
        public static final String GetTjQuotaSynthesiseDimensionKeyVal = "/tj/getTjQuotaSynthesiseDimensionKeyVal";
        public static final String GetTjQuotaChartList = "/tj/getTjQuotaChartList";
        public static final String GetTjQuotaLogList = "/tj/getTjQuotaLogList";
        public static final String GetTjQuotaLogRecentRecord = "/tj/getTjQuotaLogRecentRecord";
        public static final String GetTjDataSaveList = "/tj/getTjDataSaveList";
        public static final String AddTjDataSave = "/tj/addTjDataSave";
        public static final String DeleteTjDataSave = "/tj/deleteTjDataSave";
        public static final String GetTjDataSaveById = "/tj/getTjDataSaveById/{id}";
        public static final String GetTjDataSourceList = "/tj/getTjDataSourceList";
        public static final String AddTjDataSource = "/tj/addTjDataSource";
        public static final String DeleteTjDataSource = "/tj/deletetTjDataSource";
        public static final String GetTjDataSourceById = "/tj/getTjDataSourceById/{id}";
        public static final String TjDataSourceExistsName = "/tj/tjDataSourceExistsName/{name}";
        public static final String TjDataSourceExistsCode = "/tj/tjDataSourceExistsCode/{code}";
        public static final String GetTjQuotaDataSaveList = "tj/getTjQuotaDataSaveList";
        public static final String AddTjQuotaDataSave = "tj/addTjQuotaDataSave";
        public static final String DeleteTjQuotaDataSave = "tj/deleteTjQuotaDataSave";
        public static final String GetTjQuotaDataSourceList = "tj/getTjQuotaDataSourceList";
        public static final String AddTjQuotaDataSource = "tj/addTjQuotaDataSource";
        public static final String DeleteTjQuotaDataSource = "tj/deleteTjQuotaDataSource";
        public static final String GetTjQuotaList = "tj/getTjQuotaList";
        public static final String AddTjQuota = "tj/addTjQuota";
        public static final String UpdateTjQuota = "tj/updateTjQuota";
        public static final String DeleteTjQuota = "tj/deleteTjQuota";
        public static final String GetTjQuotaById = "tj/getTjQuotaById/{id}";
        public static final String TjQuotaExistsName = "/tj/tjQuotaExistsName/{name}";
        public static final String TjQuotaExistsCode = "/tj/tjQuotaExistsCode/{code}";
        public static final String GetTjQuotaByCode = "/tj/getTjQuotaByCode";
        public static final String TjQuotaConfigInfo = "/tj/quotaConfigInfo";
        public static final String TjHasConfigDimension = "/tj/hasConfigDimension";
        public static final String TjQuotaTypeIsExist = "/quota/type_isExist";
        public static final String TjDimensionMainIsExist = "/quota/TjDimensionMainIsExist";
        public static final String TjDimensionSlaveIsExist = "/quota/TjDimensionSlaveIsExist";
        public static final String TjQuotaBatch = "/tjQuota/batch";
        public static final String TjGetQuotaResult = "/tj/tjGetQuotaResult";
        public static final String TjGetOrgHealthCategoryQuotaResult = "/tj/tjGetOrgHealthCategoryQuotaResult";
        public static final String TjGetReportQuotaResult = "/tj/tjGetReportQuotaResult";
        public static final String TjQuotaExecute = "/job/execuJob";
        public static final String FirstExecuteQuota = "/job/firstExecuteQuota";
        public static final String FindByQuotaCodes = "/quota/findByQuotaCodes";
        public static final String TjQuotaRemove = "/job/removeJob";
        public static final String GetTjQuotaWarn = "tj/getTjQuotaWarn";
        public static final String GetQuotaReport = "tj/getQuotaReport";
        public static final String GetQuotaGraphicReportPreview = "tj/getQuotaGraphicReportPreview";
        public static final String GetMoreQuotaGraphicReportPreviews = "tj/getMoreQuotaGraphicReportPreviews";
        public static final String GetQuotaRadarGraphicReportPreviews = "tj/getQuotaRadarGraphicReportPreviews";
        public static final String GetQuotaNestedPieReportPreviews = "tj/getQuotaNestedPieReportPreviews";
        public static final String GetQuotaTotalCount = "tj/getQuotaTotalCount";
        public static final String GetQuotaGroupBy = "tj/getQuotaGroupBy";
        public static final String GetQuotaReportTwoDimensionalTable = "/tj/getQuotaReportTwoDimensionalTable";
        public static final String GetCostComposeReports = "/tj/getCostComposeReports";
        public static final String GetDeviceReports = "/tj/getDeviceReports";
        public static final String TjQuotaChart = "/tj/tjQuotaChart";
        public static final String BatchTjQuotaChart = "/tj/batchTjQuotaChart";
        public static final String TjQuotaChartId = "/tj/tjQuotaChart/{id}";
        public static final String GetAllTjQuotaChart = "/tj/getAllTjQuotaChart";
        public static final String getQuotaCategoryByName = "/quotaCategory/getQuotaCategoryByName";
        public static final String GetHeatMap = "/tj/getHeatMap";
        public static final String GetNumberOfDiabetes = "/tj/getNumberOfDiabetes";
        public static final String GetPieData = "/tj/getPieData";
        public static final String GetLineData = "/tj/getLineData";
        public static final String GetBarData = "/tj/getBarData";
        public static final String GetDiseaseTypeAnalysisInfo = "/tj/getDiseaseTypeAnalysisInfo";
        public static final String GetSexAnalysisInfo = "/tj/getSexAnalysisInfo";
        public static final String GetAgeAnalysisInfo = "/tj/getAgeAnalysisInfo";
        public static final String GetArchiveCount = "/tj/getArchiveCount";
        public static final String GetArchiveManCount = "/tj/getArchiveManCount";
        public static final String GetYearDropdownList = "/tj/getYearDropdownList";
        public static final String GetOftenIllList = "/tj/getOftenIllList";
        public static final String GetHighCostList = "/tj/getHighCostList";
        public static final String GetRepeateInspectList = "/tj/getRepeateInspectList";
        public static final String DrugAnalysis = "/tj/drugAnalysis";
        public static class Scheduler {
            public static final String ExtractMedicineExpense = "/tj/scheduler/extractMedicineExpense";
            public static final String ExtractChronicDisease = "/tj/scheduler/extractChronicDisease";
            public static final String ExtractPregnantWoman = "/tj/scheduler/extractPregnantWoman";
        }
    }
    public static class StasticReport {
        public static final String GetStatisticsElectronicMedicalCount = "/stasticReport/getStatisticsElectronicMedicalCount";
        public static final String GetStatisticsMedicalEventTypeCount = "/stasticReport/getStatisticsMedicalEventTypeCount";
        public static final String GetStatisticsDemographicsAgeCount = "/stasticReport/getStatisticsDemographicsAgeCount";
        public static final String GetArchiveReportInfo = "/stasticReport/getArchiveReportInfo";
        public static final String GetArchiveIdentifyReportInfo = "/stasticReport/getArchiveIdentifyReportInfo";
        public static final String GetArchiveHospitalReportInfo = "/stasticReport/getArchiveHospitalReportInfo";
        public static final String GetArchiveStatisticalReportInfo = "/stasticReport/getArchiveStatisticalReportInfo";
        public static final String GetArchiveTotalVisitReportInfo = "stasticReport/getArchiveTotalVisitReportInfo";
        public static final String getStatisticsUserCards = "/tj/getStatisticsUserCards";
        public static final String getStatisticsUserAgeByIdCardNo = "/tj/getStatisticsUserAgeByIdCardNo";
        public static final String getStatisticsDoctorByRoleType = "/tj/getStatisticsDoctorByRoleType";
        public static final String getStatisticsCityDoctorByRoleType = "/tj/getStatisticsCityDoctorByRoleType";
        public static final String GetArchiveReportAll = "/stasticReport/getArchiveReportAll";
        public static final String GetRecieveOrgCount = "/stasticReport/getRecieveOrgCount";
        public static final String GetArchivesInc = "/stasticReport/getArchivesInc";
        public static final String GetArchivesFull = "/stasticReport/getArchivesFull";
        public static final String GetArchivesTime = "/stasticReport/getArchivesTime";
        public static final String GetDataSetCount = "/stasticReport/getDataSetCount";
        public static final String GetArchivesRight = "/stasticReport/getArchivesRight";
        public static final String GetStasticByDay = "/stasticReport/getStasticByDay";
        public static final String GetErrorCodeList = "/stasticReport/getErrorCodeList";
    }
    public static class Org {
        public static final String getUserOrglistByUserId = "/org/getUserOrglistByUserId/";
        public static final String getUserOrgSaasByUserOrgCode = "/org/getUserOrgSaasByUserOrgCode/";
        public static final String GetOrgDeptsDate = "/org/getOrgDeptsDate";
        public static final String GetOrgDeptInfoList = "/org/userId/getOrgDeptInfoList";
        public static final String getseaOrgsByOrgCode = "/organizations/seaOrgsByOrgCode";
        public static final String ChildOrgSaasByAreaCode = "/org/childOrgSaasByAreaCode";
        public static final String getOrgCodeAndFullName = "/org/getOrgCodeAndFullName";
        public static final String getUserOrgCodelistByUserId = "/org/getUserOrgCodelistByUserId";
        // 卫生机构类别
        public static class HealthCategory {
            public static final String Prefix = "/org/healthCategory/";
            public static final String GetById = "/org/healthCategory/{id}";
            public static final String FindAll = "/org/healthCategory/findAll";
            public static final String Search = "/org/healthCategory/search";
            public static final String Save = "/org/healthCategory/save";
            public static final String Delete = "/org/healthCategory/delete";
            public static final String IsUniqueCode = "/org/healthCategory/isUniqueCode";
            public static final String IsUniqueName = "/org/healthCategory/isUniqueName";
        }
    }
    public static class GetInfo {
        public static final String GetAppIdsByUserId = "/BasicInfo/getAppIdsByUserId";
        public static final String GetIdCardNoByOrgCode = "/BasicInfo/getIdCardNoByOrgCode";
    }
    public static class Government {
        public static final String SearchGovernmentMenu = "/government/searchGovernmentMenu";
        public static final String GovernmentMenuCheckName = "/government/checkName";
        public static final String GovernmentMenuCheckCode = "/government/checkCode";
        public static final String GovernmentMenuById = "/government/detailById";
        public static final String AddGovernmentMenu = "/government/save";
        public static final String UpdateGovernmentMenu = "/government/update";
        public static final String AddGovernmentBrowseLog = "/governmentBrowseLog/save";
        public static final String searchGovernmentBrowseLog = "/governmentBrowseLog/searchByUserId";
        public static final String searchHotBrowseLog = "/governmentBrowseLog/searchHotBrowseLog";
        public static final String GovernmentMenuReportMonitorTypeSave = "/governmentMenuReportMonitorType/save";
        public static final String GovernmentMenuReportMonitorTypeDelete = "/governmentMenuReportMonitorType/delete";
        public static final String MonitorTypeList = "/governmentMenuReportMonitorType/MonitorTypeList";
        public static final String GetReportByMenuCode = "/governmentMenuReportMonitorType/getReportByMenuCode";
        //政府服务平台-门诊仪表盘-start
        public static final String OutpatientsBoardCount = "/government/outpatientsBoardCount";
        public static final String GetMonthDistribution = "/statistics/monthDistribution";
        public static final String GetRescue = "/statistics/rescue";
        //政府服务平台-门诊仪表盘-end
    }
    /**
     * 系统字典
     */
    public static class SystemDict {
        public static final String getDictEntryByDictId = "/systemDict/getDictEntryByDictId/{dictId}";
        public static final String Crud = "/dictionaries";
        public static final String FindById = "/dictionaries/{id}";
        public static final String FindByPhoneticCode = "/dictionary/{phoneticCode}";
        public static final String DeleteById = "/dictionaries/{id}";
        public static final String CheckName = "/dictionaries/existence";
        public static final String CheckCode = "/dictionaries/checkCode";
        public static final String GetDictEntryByDictIdAndEntryCode = "/open/dictionaries/getDictEntryByDictIdAndEntryCode";
        public static final String getDictEntryCodeAndValueByDictId = "/dictionaries/getDictEntryCodeAndValueByDictId";
    }
    /**
     * 应急指挥中心
     */
    public static class Emergency {
        // 救护车
        public static final String Ambulance = "/ambulance/findById";
        public static final String AmbulanceList = "/ambulance/list";
        public static final String AmbulanceSearch = "/ambulance/search";
        public static final String AmbulanceUpdateStatus = "/ambulance/updateStatus";
        public static final String AmbulanceSave = "/ambulance/save";
        public static final String AmbulanceUpdate = "/ambulance/update";
        public static final String AmbulanceDelete = "/ambulance/delete";
        public static final String AmbulanceIdOrPhoneExistence = "/ambulance/idOrPhoneExistence";
        public static final String AmbulancesBatch = "/ambulances/batch";
        // 出勤记录
        public static final String AttendanceSave = "/attendance/save";
        public static final String AttendanceUpdate = "/attendance/update";
        public static final String AttendanceEdit = "/attendance/edit";
        public static final String AttendanceList = "/attendance/list";
        public static final String AttendanceDelete = "/attendance/delete";
        public static final String AttendanceDetail = "/attendance/detail";
        public static final String AttendanceAnalysis = "/attendance/analysis";
        // 排班
        public static final String ScheduleList = "/schedule/list";
        public static final String ScheduleLevel = "/schedule/level";
        public static final String ScheduleSave = "/schedule/save";
        public static final String ScheduleUpdate = "/schedule/update";
        public static final String ScheduleBathUpdate = "/schedule/bathUpdate";
        public static final String ScheduleCleanData = "/schedule/cleanData";
        public static final String ScheduleBatch = "/schedules/batch";
        // 待命地点
        public static final String LocationList = "/location/list";
        public static final String LocationSave = "/location/save";
        public static final String LocationUpdate = "/location/update";
        public static final String LocationDelete = "/location/delete";
    }
    /**
     * 设备管理
     */
    public static class Device {
        public static final String FindById = "/device/findById";
        public static final String DeviceList = "/device/list";
        public static final String DeviceSave = "/device/save";
        public static final String DeviceUpdate = "/device/update";
        public static final String DeviceDelete = "/device/delete";
        public static final String DeviceBatch = "/device/batch";
    }
    public static class FastDFS {
        public static final String Upload = "/fastDfs/upload";
        public static final String OpenUpload = "/open/fastDfs/upload";
        public static final String OldUpload = "/fastDfs/oldUpload";
        public static final String OpenOldUpload = "/open/fastDfs/oldUpload";
        public static final String DeleteById = "/fastDfs/deleteById";
        public static final String DeleteByPath = "/fastDfs/deleteByPath";
        public static final String DeleteByObjectId = "/fastDfs/deleteByObjectId";
        public static final String FileInfo = "/fastDfs/fileInfo";
        public static final String DownloadById = "/fastDfs/downloadById";
        public static final String DownloadByPath = "/fastDfs/downloadByPath";
        public static final String DownloadByObjectId = "/fastDfs/downloadByObjectId";
        public static final String DownloadToLocal = "/fastDfs/downloadToLocal";
        public static final String GetFilePath = "/fastDfs/getFilePath";
        public static final String GetFileByDictEntry = "/open/fastDfs/getFileByDictEntry";
        public static final String Page = "/fastDfs/page";
        public static final String Status = "/fastDfs/status";
        public static final String GetPublicUrl = "/fastDfs/getPublicUrl";
        public static final String SetPublicUrl = "/fastDfs/setPublicUrl";
    }
    public static class ElasticSearch {
        public static final String Mapping = "/elasticSearch/mapping";
        public static final String Index = "/elasticSearch/index";
        public static final String Delete = "/elasticSearch/delete";
        public static final String DeleteByField = "/elasticSearch/deleteByField";
        public static final String Update = "/elasticSearch/update";
        public static final String FindById = "/elasticSearch/{id}";
        public static final String FindByField = "/elasticSearch/findByField";
        public static final String Page = "/elasticSearch/page";
        public static final String FindBySql = "/elasticSearch/findBySql";
        public static final String DateHistogram = "/elasticSearch/dateHistogram";
    }
    public static class OutpatientServiceStatistic {
        public static final String StatisticDeptOutpatientSum = "/outpatientServiceStatistic/statisticDeptOutpatientSum";
        public static final String StatisticDeptTransferTreatmentSum = "/outpatientServiceStatistic/statisticDeptTransferTreatmentSum";
    }
    public static class SingleDisease {
        public static final String GetDropdownList = "/singleDisease/getDropdownList";
        public static final String GetSymptomDetailData = "/singleDisease/getSymptomDetailData";
        public static final String GetMedicineDetailData = "/singleDisease/getMedicineDetailData";
    }
    /**
     * 后台配置问卷/满意度问题和选项
     */
    public static class SurveyAdminManage {
        public static final String GetSurveyTemplateList = "/admin/surveyTemplate/list";
        public static final String GetSurveyTemplateOptionsList = "/admin/surveyTemplate/options/list";
        public static final String SaveLabelInfo = "/admin/surveyTemplate/saveLabelInfo";
        public static final String SaveTemplate = "/admin/surveyTemplate/saveTemplate";
        public static final String GetTemplateLabel = "/admin/surveyTemplate/getTemplateLabel/{phoneticCode}";
        public static final String GetTemplateById = "/admin/surveyTemplate/getTemplateById";
        public static final String DelTemplate = "/admin/surveyTemplate/delTemplate";
        public static final String GetSurveyQuestionList = "/admin/surveyQuestion/list";
        public static final String SaveSurveyQuestion = "/admin/surveyQuestion/save";
        public static final String GetQuestionById = "/admin/surveyQuestion/getById";
        public static final String GetQuestionsByIds = "/admin/surveyQuestion/getByIds";
        public static final String DelQuestion = "/admin/surveyQuestion/delQuestion";
        public static final String DelQuestions = "/admin/surveyQuestion/delQuestions";
        public static final String updateQuestion = "/admin/surveyQuestion/update";
    }
    /**
     * 居民填写满意度
     */
    public static class Questionnaire {
        public static final String GetAllQuestionsByTemplateCode = "/questionnaire/getAllQuestionsByTemplateCode";
        public static final String SaveAnswer = "/questionnaire/saveAnswer";
    }
    /**
     * 转发福州总部开放平台接口相关
     */
    public static class Fz {
        public static final String OpenApi = "/fz/open/api";
        public static final String InnerApi = "/fz/inner/api";
    }
    /**
     * APP消息推送接口
     */
    public static class AppPushMessage {
        public static final String single = "/AppPushMessage/single";
        public static final String list = "/AppPushMessage/list";
        public static final String app = "/AppPushMessage/app";
        public static final String tarns = "/AppPushMessage/tarnsmission";
        public static final String findClientId = "/AppPushMessage/findClientId";
        public static final String findClientIdList = "/AppPushMessage/findClientIdList";
        public static final String updateClientId = "/AppPushMessage/updateClientId";
    }
    /**
     * 预约-挂号单
     */
    public static class Registration {
        public static final String Prefix = "/appointment/registration/";
        public static final String GetById = "/appointment/registration/{id}";
        public static final String GetByOrderId = "/appointment/registration/orderId/{orderId}";
        public static final String Search = "/appointment/registration/search";
        public static final String Save = "/appointment/registration/save";
        public static final String Update = "/appointment/registration/update";
        public static final String Delete = "/appointment/registration/delete";
        public static final String UpdateState = "/appointment/registration/updateState";
        public static final String IsSuccessfullyRegister = "/appointment/registration/isSuccessfullyRegister";
    }
    /**
     * 组合福州总部的预约挂号接口为我方需要的数据结构
     */
    public static class FzCombination {
        public static final String FindHospitalList = "/open/appointment/combination/findHospitalList";
        public static final String FindDoctorList = "/open/appointment/combination/findDoctorList";
    }
    /**
     * 账号相关
     */
    public static class AccountRepresentation {
        public static final String SaveAccontRepresenetation = "/account/save";
        public static final String GetRandomImageCode = "/account/getRandomImageCode";
        public static final String CheckRandomImageCode = "/account/checkRandomImageCode";
        public static final String findUserByPhoneOrName = "/account/findUserByPhoneOrName";
        public static final String ChangePassWord = "/account/changePassWord";
    }
    public class MessageTemplate {
        public static final String MessageTemplateAdmin = "/messageTemplate/admin/{messageTemplateId}";
        public static final String MessageTemplate = "/messageTemplate";
        public static final String MyMessageList = "/messageTemplate/MyMessageList";
        public static final String MyMessage = "/messageTemplate/MyMessage/admin/{messageId}";
        public static final String MessageOrderPush = "/messageTemplate/messageOrderPush";
    }
    /**
     * 数据质量监控
     */
    public static class DataQuality{
        public static final String PaltformReceiveWarningList = "/dataQuality/warningSetting/receiveWarningList";
        public static final String PaltformReceiveWarningAdd = "/dataQuality/warningSetting/receiveWarningAdd";
        public static final String PaltformReceiveWarningDel = "/dataQuality/warningSetting/receiveWarningDel";
        public static final String PaltformReceiveWarningUpd = "/dataQuality/warningSetting/receiveWarningUpd";
        public static final String PaltformReceiveWarning =    "/dataQuality/warningSetting/receiveWarning/{id}";
        public static final String PaltformReceiveWarningIsExist =    "/dataQuality/warningSetting/receiveWarningIsExist";
        public static final String PaltformReceiveWarningDefault =    "/dataQuality/warningSetting/receiveWarningDefault";
        public static final String PaltformResourceWarningList = "/dataQuality/warningSetting/resourceWarningList";
        public static final String PaltformResourceWarningAdd = "/dataQuality/warningSetting/resourceWarningAdd";
        public static final String PaltformResourceWarningDel = "/dataQuality/warningSetting/resourceWarningDel";
        public static final String PaltformResourceWarningUpd = "/dataQuality/warningSetting/resourceWarningUpd";
        public static final String PaltformResourceWarning =    "/dataQuality/warningSetting/resourceWarning/{id}";
        public static final String PaltformUploadWarningList = "/dataQuality/warningSetting/uploadWarningList";
        public static final String PaltformUploadWarningAdd = "/dataQuality/warningSetting/uploadWarningAdd";
        public static final String PaltformUploadWarningDel = "/dataQuality/warningSetting/uploadWarningDel";
        public static final String PaltformUploadWarningUpd = "/dataQuality/warningSetting/uploadWarningUpd";
        public static final String PaltformUploadWarningIsExist =    "/dataQuality/warningSetting/uploadWarningIsExist";
        public static final String PaltformUploadWarning =    "/dataQuality/warningSetting/uploadWarning/{id}";
        public static final String DatasetWarningList = "/dataQuality/warningSetting/datasetWarningList";
        public static final String ImportDatasetExcel = "/dataQuality/warningSetting/importDatasetExcel";
        public static final String DatasetWarningListNoPage = "/dataQuality/warningSetting/datasetWarningListNoPage";
        public static final String DatasetWarningAdd = "/dataQuality/warningSetting/datasetWarningAdd";
        public static final String DatasetWarningDel = "/dataQuality/warningSetting/datasetWarningDel";
        public static final String DatasetList = "/dataQuality/warningSetting/datasetList";
        public static final String Meta_datas = "/dataQuality/warningSetting/meta_datas";
        public static final String ReceivedPacketNumList = "/dataQuality/receivedPacket/packetNumList";
        public static final String ReceivedPacketReportData = "/dataQuality/receivedPacket/packetReportData";
        public static final String QualityMonitoringList = "/dataQuality/quality/qualityMonitoringList";
        public static final String ReceptionList = "/dataQuality/quality/receptionList";
        public static final String ReceiveDataset = "/dataQuality/quality/receiveDataset";
        public static final String QualityMonitorProvincePlatform = "/dataQuality/quality/platform";
        public static final String uploadRecordDetail = "/dataQuality/quality/uploadRecord";
        public static final String uploadRecordDetailPage = "/dataQuality/quality/uploadRecordPage";
        public static final String UploadDataSetList = "/dataQuality/quality/uploadDataSets";
        public static final String UploadDataSetListPage = "/dataQuality/quality/uploadDataSetsPage";
        public static final String UploadErrorList = "/dataQuality/quality/uploadError";
        public static final String UploadErrorListPage = "/dataQuality/quality/uploadErrorPage";
        public static final String WarningRecordList = "/dataQuality/warningRecord/warningRecordList";
        public static final String RealTimeMonitorList = "/dataQuality/warningRecord/realTimeMonitorList";
        public static final String WarningRecord =  "/dataQuality/warningRecord/warningRecord/{id}";
        public static final String WarningRecordUpd = "/dataQuality/warningRecord/warningRecordUpd";
        public static final String WarningQuestionAnalyze = "/dataQuality/warningRecord/warningQuestionAnalyze";
        public static final String WarningQuestionJob = "/dataQuality/warningRecord/WarningQuestionJob";
        public static final String ExportWarningRecordToExcel = "/dataQuality/export/exportWarningRecordToExcel";
        public static final String ExportQualityMonitoring = "/dataQuality/export/exportQualityMonitoring";
        public static final String ExportReceptionList = "/dataQuality/export/exportReceptionList";
        public static final String ExportAnalyzeErrorList = "/dataQuality/export/exportAnalyzeErrorList";
        public static final String ExportMetadataErrorList = "/dataQuality/export/exportMetadataErrorList";
        public static final String ExportArchiveList = "/dataQuality/export/exportArchiveList";
        public static final String ExportUploadRecordList = "/dataQuality/export/exportUploadRecordList";
        public static final String ExportQualityMonitoringListToExcel = "/dataQuality/export/exportQualityMonitoringListToExcel";
        public static final String ExportQualityUpload = "/dataQuality/export/exportQualityUpload";
        //首页相关
        public static final String  HomeSummary= "/dataQuality/home/recordList";
        public static final String  HomeAreaDataList= "/dataQuality/home/areaDataList";
        public static final String  HomeOrgDataList= "/dataQuality/home/orgDataList";
        public static final String  HomeDatasetError= "/dataQuality/home/datasetError";
        public static final String  HomeMetadataError= "/dataQuality/home/metadataError";
        public static final String  HomeCompleteAnalyze= "/dataQuality/home/completeAnalyze";
        public static final String  HomeCorrectAnalyze= "/dataQuality/home/correctAnalyze";
        public static final String  HomeInTimeAnalyze= "/dataQuality/home/inTimeAnalyze";
        public static final String  HomeTrend= "/dataQuality/home/trend";
        //app端相关
        public static final String  HomeHealthArchiveTrend= "/dataQuality/home/healthArchiveTrend";
    }
    /**
     * 质控相关
     */
    public class PackQcReport {
        public static final String dailyReport = "/packQcReport/dailyReport";
        public static final String datasetWarningList = "/packQcReport/datasetWarningList";
        public static final String resourceSuccess = "/packQcReport/resourceSuccess";
        public static final String resourceSuccessPage = "/packQcReport/resourceSuccessPage";
        public static final String archiveReport= "/packQcReport/archiveReport";
        public static final String dataSetList= "/packQcReport/dataSetList";
        public static final String dataSetListPage= "/packQcReport/dataSetListPage";
        public static final String archiveFailed= "/packQcReport/archiveFailed";
        public static final String archiveFailedPage= "/packQcReport/archiveFailedPage";
        public static final String metadataError= "/packQcReport/metadataError";
        public static final String metadataErrorPage= "/packQcReport/metadataErrorPage";
        public static final String analyzeErrorList= "/packQcReport/analyzeErrorList";
        public static final String metadataErrorList= "/packQcReport/metadataErrorList";
        public static final String metadataErrorDetail= "/packQcReport/metadataErrorDetail";
        public static final String archiveList= "/packQcReport/archiveList";
        public static final String archiveDetail= "/packQcReport/archiveDetail";
        public static final String uploadRecordList= "/packQcReport/uploadRecordList";
        public static final String uploadRecordDetail= "/packQcReport/uploadRecordDetail";
    }
    // 政府服务平台首页
    public static class GovFirsPage {
        // 政府服务平台首页 - 指标分类
        public static class QuotaCategory {
            public static final String Prefix = "/govFirstPage/quotaCategory";
            public static final String GetById = "/govFirstPage/quotaCategory/{id}";
            public static final String Search = "/govFirstPage/quotaCategory/search";
            public static final String Save = "/govFirstPage/quotaCategory/save";
            public static final String Delete = "/govFirstPage/quotaCategory/delete";
            public static final String IsUniqueCode = "/govFirstPage/quotaCategory/isUniqueCode";
            public static final String IsUniqueName = "/govFirstPage/quotaCategory/isUniqueName";
        }
        // 政府服务平台首页 - 指标展示管理
        public static class QuotaVisibility {
            public static final String Prefix = "/govFirstPage/quotaVisibility";
            public static final String GetById = "/govFirstPage/quotaVisibility/{id}";
            public static final String Search = "/govFirstPage/quotaVisibility/search";
            public static final String Save = "/govFirstPage/quotaVisibility/save";
            public static final String Delete = "/govFirstPage/quotaVisibility/delete";
            public static final String IsUniqueCode = "/govFirstPage/quotaVisibility/isUniqueCode";
            public static final String IsUniqueName = "/govFirstPage/quotaVisibility/isUniqueName";
            public static final String UpdateStatus = "/govFirstPage/quotaVisibility/updateStatus";
            public static final String GetCategoryQuotaList = "/govFirstPage/quotaVisibility/getCategoryQuotaList";
        }
        // 政府服务平台首页 - 报表接口
        public static class Report {
            public static final String CountEmergencyAttendance = "/govFirstPage/report/countEmergencyAttendance";
            public static final String CountHospitalizationAttendance = "/govFirstPage/report/countHospitalizationAttendance";
            public static final String StatEmergencyExpense = "/govFirstPage/report/statEmergencyExpense";
            public static final String StatHospitalizationExpense = "/govFirstPage/report/statHospitalizationExpense";
            public static final String StatEmergencyMedicineExpense = "/govFirstPage/report/statEmergencyMedicineExpense";
            public static final String StatHospitalizationMedicineExpense = "/govFirstPage/report/statHospitalizationMedicineExpense";
            public static final String StatAttendanceTrend = "/govFirstPage/report/statAttendanceTrend";
            public static final String StatExpenseTrend = "/govFirstPage/report/statExpenseTrend";
        }
    }
}

+ 436 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/BaseController.java

@ -0,0 +1,436 @@
package com.yihu.quota.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseController {
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);
	@Autowired
	protected HttpServletRequest request;
	/**
	 * 獲取髮送請求用戶的uid
	 * @return
	 */
	public String getUID() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("uid");
			
		} catch (Exception e) {
			return null;
		}
	}
	public String getOpenid() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("openid");
			
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 获取用户ID
	 * @return
	 */
	public long getId() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getLong("id");
		} catch (Exception e) {
			return 0;
		}
	}
	public String getIMEI() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("imei");
		} catch (Exception e) {
			return null;
		}
	}
	
	public String getToken() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("token");
		} catch (Exception e) {
			return null;
		}
	}
	public void error(Exception e) {
		logger.error(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	public void warn(Exception e) {
		logger.warn(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	/**
	 * 返回接口处理结果
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String error(int code, String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	/**
	 * 接口处理成功
	 * @param msg
	 * @return
	 */
	public String success(String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", 200);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	public String write(int code, String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String write(int code, String msg, String key, List<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, list);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, JSONObject value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, JSONArray value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param total 总数
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, int total, String key, JSONArray value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put("total", total);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Object value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String write(int code, String msg, String key, Page<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			// 是否为第一页
			map.put("isFirst", list.isFirst());
			// 是否为最后一页
			map.put("isLast", list.isLast());
			// 总条数
			map.put("total", list.getTotalElements());
			// 总页数
			map.put("totalPages", list.getTotalPages());
			map.put(key, list.getContent());
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 *
	 *
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			// 是否为第一页
			json.put("isFirst", page.isFirst());
			// 是否为最后一页
			json.put("isLast", page.isLast());
			// 总条数
			json.put("total", page.getTotalElements());
			// 总页数
			json.put("totalPages", page.getTotalPages());
			json.put(key, array);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Map<?, ?> value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	* 返回接口处理结果
	*
	* @param code 结果码,成功为200
	* @param msg 结果提示信息
	* @param value 结果数据
	* @return
	*/
	public String write(int code, String msg, String key, String value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			// 是否为第一页
			json.put("isFirst", isFirst);
			// 是否为最后一页
			json.put("isLast", isLast);
			// 总条数
			json.put("total", total);
			// 总页数
			json.put("totalPages", totalPages);
			json.put(key, values);
			return json.toString();
		} catch (Exception e) {
			logger.error("BaseController:", e.getMessage());
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	public String trimEnd(String param, String trimChars) {
		if (param.endsWith(trimChars)) {
			param = param.substring(0, param.length() - trimChars.length());
		}
		return param;
	}
	/**
	 * 无效用户消息返回
	 * @param e
	 * @param defaultCode
	 * @param defaultMsg
	 * @return
	 */
	public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
		try {
			// if (e instanceof UndeclaredThrowableException) {
			// UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
			// InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
			// if (iue != null) {
			// return error(iue.getCode(), iue.getMsg());
			// }
			// }
			return error(defaultCode, defaultMsg);
		} catch (Exception e2) {
			return null;
		}
	}
}

+ 436 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/ElasticSearchController.java

@ -0,0 +1,436 @@
package com.yihu.quota.controller;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.elasticsearch.ElasticSearchUtil;
import com.yihu.ehr.elasticsearch.config.ElasticSearchConfig;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.quota.etl.util.ElasticsearchUtil;
import com.yihu.quota.etl.util.EsClientUtil;
import com.yihu.quota.vo.PersonalInfoModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by lyr on 2016/7/26.
 */
@RestController
@RequestMapping(value = "/api/v1.0")
@Api(value = "elasticSearch", description = "es库数据处理工具")
public class ElasticSearchController extends BaseController {
    @Autowired
    private  ObjectMapper objectMapper;
    @Autowired
    private EsClientUtil esClientUtil;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private ElasticSearchConfig elasticSearchConfig;
    @Autowired
    private ElasticSearchUtil elasticSearchUtil;
    @ApiOperation("sql查询es")
    @RequestMapping(value = "/open/getEsInfoBySql", method = RequestMethod.GET)
    public MixEnvelop getEsInfoBySql(
            @ApiParam(value = "sql", name = "查询的SQL")
            @RequestParam(value = "sql") String sql) {
        MixEnvelop envelop = new MixEnvelop();
        if (StringUtils.isEmpty(sql)) {
            envelop.setMessage("sql为空");
            return envelop;
        }
        try {
            List<Map<String, Object>> listData = elasticsearchUtil.excuteDataModel(sql);
            envelop.setDetailModelList(listData);
            envelop.setObj(listData.size());
            envelop.setStatus(200);
        } catch (Exception e) {
            envelop.setMessage("sql执行出错");
        }
        return envelop;
    }
    @ApiOperation("根据index查询es")
    @RequestMapping(value = "/open/getEsInfoByIndexAndParam", method = RequestMethod.GET)
    public MixEnvelop getEsInfoByIndexAndParam(
            @ApiParam(value = "index", name = "es索引")
            @RequestParam(value = "index") String index,
            @ApiParam(value = "whereCondition", name = "where 条件")
            @RequestParam(value = "whereCondition", required = false) String whereCondition) {
        MixEnvelop envelop = new MixEnvelop();
        if (StringUtils.isEmpty(index)) {
            envelop.setMessage("es索引为空");
            return envelop;
        }
        try {
            StringBuffer sb = new StringBuffer("select * from ");
            sb.append(index);
            if (StringUtils.isNotEmpty(whereCondition)) {
                sb.append(" where ").append(whereCondition).append(" limit 10000");
            }
            List<Map<String, Object>> listData = elasticsearchUtil.excuteDataModel(sb.toString());
            envelop.setDetailModelList(listData);
            envelop.setObj(listData.size());
            envelop.setStatus(200);
        } catch (Exception e) {
            envelop.setMessage("sql执行出错");
        }
        return envelop;
    }
//    @RequestMapping(value = "/getSolrData", method = RequestMethod.GET)
//    @ApiOperation("根据条件获取solr 数据,结果不超过5万条")
//    public void getSolrData(
//            @ApiParam(value = "core 表名,如 HealthProfile")
//            @RequestParam(value = "core", required = true) String core,
//            @ApiParam(name = "q", value = "查询条件 多个用  AND 拼接")
//            @RequestParam(name = "q",required = true) String q,
//            @ApiParam(name = "fl", value = "展示字段 多个用  , 拼接 如 org_area,org_code,EHR_000081")
//            @RequestParam(name = "fl",required = true) String fl,HttpServletResponse response
//    ){
//        long rows = 0;
//        List<Map<String, Object>> list = new ArrayList<>();
//        try {
//            HSSFWorkbook workbook = new HSSFWorkbook();
//            //建立新的sheet对象(excel的表单)
//            HSSFSheet sheet = workbook.createSheet("solr 数据");
//            if(StringUtils.isEmpty(fl)){
//                HSSFRow row0 = sheet.createRow(0);
//                row0.createCell(0).setCellValue("展示字段 不能为空");
//            }else {
//                fl += ",rowkey";
//            }
//            String [] fields = fl.split(",");
//            rows = solrQuery.count(core,q,null);
//            if(rows > 50000){
//                HSSFRow row0 = sheet.createRow(0);
//                row0.createCell(0).setCellValue("数据超过五万条,数据量过大");
//            }else {
//                list =  solrQuery.queryReturnFieldList(core, q, null, null, 0, rows,fields);
//                HSSFRow row0 = sheet.createRow(0);
//                for(int j = 0;j < fields.length ;j++){
//                    row0.createCell(j).setCellValue(fields[j]);
//                }
//
//                for(int i = 0;i < list.size() ;i++){
//                    Map<String, Object> map = list.get(i);
//                    HSSFRow row = sheet.createRow(i+1);
//                    for(int j = 0;j < fields.length ;j++){
//                        if(map.get(fields[j]) != null){
//                            row.createCell(j).setCellValue(map.get(fields[j]).toString());
//                        }
//                    }
//                }
//            }
//            OutputStream output=response.getOutputStream();
//            response.reset();
//            response.setHeader("Content-disposition", "attachment; filename=details.xls");
//            response.setContentType("application/msexcel");
//            workbook.write(output);
//            output.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
////        FileOutputStream output = new FileOutputStream("E:\\solr"+ String.valueOf(System.currentTimeMillis()) +".xls");
//    }
    @RequestMapping(value = "/saveElasticsearchDocument", method = RequestMethod.POST)
    @ApiOperation("添加elasticsearch文档")
    public String saveDocument(
            @ApiParam(value = "json串")
            @RequestParam(value = "jsonString", required = true) String jsonString,
            @ApiParam(name = "index", value = "索引名称")
            @RequestParam(name = "index",required = true) String index,
            @ApiParam(name = "type", value = "类型(表)名称")
            @RequestParam(name = "type",required = true) String type
    ){
        boolean f = false;
        try {
           String clusterName = elasticSearchConfig.getClusterName();
           String nodeStr = elasticSearchConfig.getClusterNodes();
            if(StringUtils.isNotEmpty(nodeStr)){
                String [] nodes = nodeStr.split(",");
                if(nodes.length > 1){
                    String ip = nodes[0].substring(0,nodes[0].indexOf(":")-1);
                    Client client = esClientUtil.getClient(ip, 9300, clusterName);
                    f = elasticsearchUtil.save(client,index,type,jsonString);
                    client.close();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return  String.valueOf(f);
    }
    @RequestMapping(value = "/impFileDocument", method = RequestMethod.POST)
    @ApiOperation("文件导入elasticsearch文档数据")
    public String fileImpDocument(
            @ApiParam(name = "file", value = "file文件")
            @RequestParam(name = "file",required = true) String file,
            @ApiParam(name = "index", value = "索引名称")
            @RequestParam(name = "index",required = true) String index,
            @ApiParam(name = "type", value = "类型(表)名称")
            @RequestParam(name = "type",required = true) String type
    )throws Exception {
        boolean f = false;
        try {
            Client client = null ;
            String clusterName = elasticSearchConfig.getClusterName();
            String nodeStr = elasticSearchConfig.getClusterNodes();
            if(StringUtils.isNotEmpty(nodeStr)){
                String [] nodes = nodeStr.split(",");
                if(nodes.length > 1){
                    String ip = nodes[0].substring(0,nodes[0].indexOf(":")-1);
                    client = esClientUtil.getClient(ip, 9300, clusterName);
                }
            }
            if( !file.isEmpty()){
                FileInputStream fis = null;
                InputStreamReader isr = null;
                BufferedReader br = null; //用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。
                try {
                    String str = "";
                    String jsonString = "";
                    fis = new FileInputStream(file);// FileInputStream
                    // 从文件系统中的某个文件中获取字节
                    isr = new InputStreamReader(fis);// InputStreamReader 是字节流通向字符流的桥梁,
                    br = new BufferedReader(isr);// 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
                    while ((str = br.readLine()) != null) {
                        jsonString = str;
                        System.out.println(jsonString);// 打印
                        //添加到es库
                        f = elasticsearchUtil.save(client,index,type,jsonString);
                    }
                } catch (FileNotFoundException e) {
                    System.out.println("找不到指定文件");
                } catch (IOException e) {
                    System.out.println("读取文件失败");
                } finally {
                    try {
                        br.close();
                        isr.close();
                        fis.close();
                        client.close();
                        // 关闭的时候最好按照先后顺序关闭最后开的先关闭所以先关s,再关n,最后关m
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return  String.valueOf(f);
    }
    @RequestMapping(value = "/expDocument", method = RequestMethod.POST)
    @ApiOperation("文件导出elasticsearch文档数据")
    public String fileExpDocument(
            @ApiParam(name = "index", value = "索引名称")
            @RequestParam(name = "index",required = true) String index,
            @ApiParam(name = "type", value = "类型(表)名称")
            @RequestParam(name = "type",required = true) String type
    )throws Exception {
        boolean f = false;
        try {
            Client client = null ;
            String clusterName = elasticSearchConfig.getClusterName();
            String nodeStr = elasticSearchConfig.getClusterNodes();
            if(StringUtils.isNotEmpty(nodeStr)){
                String [] nodes = nodeStr.split(",");
                if(nodes.length > 1){
                    String ip = nodes[0].substring(0,nodes[0].indexOf(":")-1);
                    client = esClientUtil.getClient(ip, 9300, clusterName);
                }
            }
            List<Map<String, Object>> list = elasticsearchUtil.queryList(client,index,type, null, null, 10000);
            byte[] buff = new byte[]{};
            StringBuffer docmBuff = new StringBuffer();
            for(Map<String, Object> map:list){
//                String title = "\n{”index”:{”_index”:”quota”,”_type”:”quota_test”}}";
                String document = "\n{";
                for(String key : map.keySet()){
                    if( !key.equals("id")){
                        document = document +"”" + key + "”:”" + map.get(key) +"”,";
                    }
                }
                document = document.substring(0,document.length()-1)+ "}";
//                title = title.replaceAll("”","\"");
                document = document.replaceAll("”","\"");
//                System.out.println(title);
//                System.out.println(document);
                docmBuff = docmBuff.append(document);
            }
            buff = docmBuff.toString().getBytes();
            FileOutputStream out=new FileOutputStream("E://quota.json");
            out.write(buff,0,buff.length);
            out.close();
            client.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return  String.valueOf(f);
    }
    @RequestMapping(value = "/getElasticsearchDocument", method = RequestMethod.POST)
    @ApiOperation("查询elasticsearch文档")
    public List<Map<String, Object>> getElasticsearchDocument(
            @ApiParam(value = "term")
            @RequestParam(value = "term", required = true) String term,
            @ApiParam(value = "value")
            @RequestParam(value = "value", required = true) String value,
            @ApiParam(name = "index", value = "索引名称")
            @RequestParam(name = "index",required = true) String index,
            @ApiParam(name = "type", value = "类型(表)名称")
            @RequestParam(name = "type",required = true) String type
    ){
        List<Map<String, Object>> list = null;
        try {
            Client client = null ;
            String clusterName = elasticSearchConfig.getClusterName();
            String nodeStr = elasticSearchConfig.getClusterNodes();
            if(StringUtils.isNotEmpty(nodeStr)){
                String [] nodes = nodeStr.split(",");
                if(nodes.length > 1){
                    String ip = nodes[0].substring(0,nodes[0].indexOf(":")-1);
                    client = esClientUtil.getClient(ip, 9300, clusterName);
                }
            }
            BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
            TermQueryBuilder termQueryQuotaCode = QueryBuilders.termQuery(term, value);
            boolQueryBuilder.must(termQueryQuotaCode);
            list = elasticsearchUtil.queryList(client,index,type, boolQueryBuilder, null, 200);
            client.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return  list;
    }
    @RequestMapping(value = "/elasticSearch/addElasticSearch", method = RequestMethod.POST)
    @ApiOperation("elasticsearch文档数据")
    public Boolean addElasticSearch(
            @ApiParam(name = "index", value = "索引名称")
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型")
            @RequestParam(value = "type") String type,
            @ApiParam(name = "sourceList", value = "值")
            @RequestParam(value = "sourceList") String sourceList) throws Exception {
        boolean f = false;
        try {
            Client client = null ;
            String clusterName = elasticSearchConfig.getClusterName();
            String nodeStr = elasticSearchConfig.getClusterNodes();
            if(StringUtils.isNotEmpty(nodeStr)){
                String [] nodes = nodeStr.split(",");
                if(nodes.length > 1){
                    String ip = nodes[0].substring(0,nodes[0].indexOf(":")-1);
                    client = esClientUtil.getClient(ip, 9300, clusterName);
                }
            }
            InputStream fis = null;
            InputStreamReader isr = null;
            BufferedReader br = null; //用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。
            try {
                String str = "";
                String jsonString = "";
                sourceList = URLDecoder.decode(sourceList, "UTF-8");
                fis = new ByteArrayInputStream(sourceList.getBytes("UTF-8"));
                // 从文件系统中的某个文件中获取字节
                isr = new InputStreamReader(fis);// InputStreamReader 是字节流通向字符流的桥梁,
                br = new BufferedReader(isr);// 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
                while ((str = br.readLine()) != null) {
                    jsonString = str;
                    System.out.println(jsonString);// 打印
                    //添加到es库
                    f = elasticsearchUtil.save(client,index,type,jsonString);
                }
            } catch (FileNotFoundException e) {
                System.out.println("找不到指定文件");
            } catch (IOException e) {
                System.out.println("读取文件失败");
            } finally {
                try {
                    br.close();
                    isr.close();
                    fis.close();
                    client.close();
                    // 关闭的时候最好按照先后顺序关闭最后开的先关闭所以先关s,再关n,最后关m
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return  f;
    }
    @RequestMapping(value = "/elasticSearch/testQueryElasticSearch", method = RequestMethod.POST)
    @ApiOperation("测试查询数据")
    public void addElasticSearch(
            @ApiParam(name = "data", value = "参数")
            @RequestParam(value = "data") String data
    ){
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String index = "singleDiseasePersonal";
        String type = "personal_info";
        int i =0;
        while(i<2){
            PersonalInfoModel personalInfo = new PersonalInfoModel();
            personalInfo.setDisease("HP0047");
            personalInfo.setDiseaseName("糖尿病");
            personalInfo.setDemographicId(data);
            try {
                String sql = "SELECT count(demographicId) FROM singleDiseasePersonal where demographicId ="+data+" group by demographicId ";
                long count2 = elasticsearchUtil.getCountBySql(sql);
                System.out.println("结果条数 count2="+count2);
//                List<Map<String, Object>> relist = elasticSearchUtil.findByField(index, type, "demographicId", data);
//                List<Map<String, Object>> filter = new ArrayList<>();
//                Map<String,Object> paramMap = new HashMap<>();
//                paramMap.put("demographicId",data);
//                filter.add(paramMap);
//               long count = elasticSearchUtil.count(index, type,filter);
//                System.out.println("结果条数 count="+count);
//                System.out.println("结果条数="+ relist.size());
//                if(relist== null || relist.size() ==0){
                if(count2 == 0){
                    Map<String, Object> source = new HashMap<>();
                    String jsonPer = objectMapper.writeValueAsString(personalInfo);
                    source = objectMapper.readValue(jsonPer, Map.class);
                    elasticSearchUtil.index(index,type, source);
                }
                i++;
            }catch (Exception e){
                e.getMessage();
            }
        }
    }
}

+ 198 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/ElasticSearchEndPoint.java

@ -0,0 +1,198 @@
package com.yihu.quota.controller;
import com.yihu.ehr.elasticsearch.ElasticSearchUtil;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.quota.constants.ServiceApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * EndPoint - Es搜索服务
 * Created by progr1mmer on 2017/12/2.
 */
@RestController
@RequestMapping("/api/v1.0")
@Api(value = "ElasticSearchEndPoint", description = "Es搜索服务", tags = {"分布式综合服务-Es搜索服务"})
public class ElasticSearchEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private ElasticSearchUtil elasticSearchUtil;
    @RequestMapping(value = ServiceApi.ElasticSearch.Mapping, method = RequestMethod.POST)
    @ApiOperation(value = "建立映射")
    public Envelop mapping(
            @ApiParam(name = "index", value = "索引名称", required = true)
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型", required = true)
            @RequestParam(value = "type") String type,
            @ApiParam(name = "source", value = "Json串值{\"field\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}", required = true)
            @RequestParam(value = "source") String source,
            @ApiParam(name = "setting", value = "Json串值{\"key\":\"value\"}")
            @RequestParam(value = "setting", required = false) String setting) throws Exception {
        Map<String, Map<String, String>> _mapping = objectMapper.readValue(source, Map.class);
        Map<String, Object> _setting = new HashMap<>();
        if (setting != null) {
            _setting = objectMapper.readValue(setting, Map.class);
        }
        elasticSearchUtil.mapping(index, type, _mapping, _setting);
        return success(true);
    }
    @RequestMapping(value = ServiceApi.ElasticSearch.Index, method = RequestMethod.POST)
    @ApiOperation(value = "添加数据")
    public Envelop index(
            @ApiParam(name = "index", value = "索引名称", required = true)
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型", required = true)
            @RequestParam(value = "type") String type,
            @ApiParam(name = "source", value = "值", required = true)
            @RequestParam(value = "source") String source) throws Exception {
        Map<String, Object> result;
        Map<String, Object> sourceMap = objectMapper.readValue(source, Map.class);
        result = elasticSearchUtil.index(index, type, sourceMap);
        return success(result);
    }
    @RequestMapping(value = ServiceApi.ElasticSearch.Delete, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除数据")
    public Envelop delete(
            @ApiParam(name = "index", value = "索引名称", required = true)
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型", required = true)
            @RequestParam(value = "type") String type,
            @ApiParam(name = "id", value = "id(多个id值以,分隔)", required = true)
            @RequestParam(value = "id") String id) {
        elasticSearchUtil.bulkDelete(index, type, id.split(","));
        return success(true);
    }
    @RequestMapping(value = ServiceApi.ElasticSearch.DeleteByField, method = RequestMethod.GET)
    @ApiOperation(value = "删除数据(单次不能超过10000条)")
    public Envelop deleteByField(
            @ApiParam(name = "index", value = "索引名称", required = true)
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型", required = true)
            @RequestParam(value = "type") String type,
            @ApiParam(name = "field", value = "字段", required = true)
            @RequestParam(value = "field") String field,
            @ApiParam(name = "value", value = "字段值", required = true)
            @RequestParam(value = "value") String value,
            @ApiParam(name = "field2", value = "字段2", required = false)
            @RequestParam(value = "field2", required = false) String field2,
            @ApiParam(name = "value2", value = "字段值", required = false)
            @RequestParam(value = "value2", required = false) String value2,
            @ApiParam(name = "dateField", value = "时间字段", required = false)
            @RequestParam(value = "dateField" , required = false) String dateField,
            @ApiParam(name = "startDate", value = "时间字段开始时间,时间格式如:2018-01-12", required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "时间字段结束时间,时间格式如:2018-01-12", required = false)
            @RequestParam(value = "endDate", required = false) String endDate) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery(field, value);
        boolQueryBuilder.must(termsQueryBuilder);
        if(StringUtils.isNotEmpty(field2) && StringUtils.isNotEmpty(value2)){
            TermsQueryBuilder termsQueryBuilder2 = QueryBuilders.termsQuery(field2, value2);
            boolQueryBuilder.must(termsQueryBuilder2);
        }
        if(StringUtils.isNotEmpty(dateField) && startDate != null && endDate != null){
            RangeQueryBuilder rangeQueryStartTime = QueryBuilders.rangeQuery(dateField).gte(startDate);
            boolQueryBuilder.must(rangeQueryStartTime);
            RangeQueryBuilder rangeQueryEndTime = QueryBuilders.rangeQuery(dateField).lte(endDate);
            boolQueryBuilder.must(rangeQueryEndTime);
        }
        elasticSearchUtil.deleteByFilter(index, type, boolQueryBuilder);
        return success(true);
    }
    @RequestMapping(value = ServiceApi.ElasticSearch.Update, method = RequestMethod.PUT)
    @ApiOperation(value = "更新数据")
    public Envelop update(
            @ApiParam(name = "index", value = "索引名称", required = true)
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型", required = true)
            @RequestParam(value = "type") String type,
            @ApiParam(name = "id", value = "id", required = true)
            @RequestParam(value = "id") String id,
            @ApiParam(name = "source", value = "值", required = true)
            @RequestParam(value = "source") String source) throws Exception {
        Map<String, Object> sourceMap = objectMapper.readValue(source, Map.class);
        Map<String, Object> result = elasticSearchUtil.update(index, type, id, sourceMap);
        if (result != null) {
            return success(result);
        }
        return failed("更新失败");
    }
    @RequestMapping(value = ServiceApi.ElasticSearch.FindById, method = RequestMethod.GET)
    @ApiOperation(value = "获取单条数据")
    public Envelop findById(
            @ApiParam(name = "index", value = "索引名称", required = true)
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型", required = true)
            @RequestParam(value = "type") String type,
            @ApiParam(name = "id", value = "id", required = true)
            @PathVariable(value = "id") String id) {
        Map<String, Object> result = elasticSearchUtil.findById(index, type, id);
        return success(result);
    }
    @RequestMapping(value = ServiceApi.ElasticSearch.FindByField, method = RequestMethod.GET)
    @ApiOperation(value = "获取结果集")
    public Envelop findByField(
            @ApiParam(name = "index", value = "索引名称", required = true)
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型", required = true)
            @RequestParam(value = "type") String type,
            @ApiParam(name = "field", value = "字段", required = true)
            @RequestParam(value = "field") String field,
            @ApiParam(name = "value", value = "字段值", required = true)
            @RequestParam(value = "value") Object value) {
        List<Map<String, Object>> resultList = elasticSearchUtil.findByField(index, type, field, value);
        return success(resultList);
    }
    @RequestMapping(value = ServiceApi.ElasticSearch.Page, method = RequestMethod.GET)
    @ApiOperation(value = "获取结果集")
    public Envelop page(
            @ApiParam(name = "index", value = "索引名称", required = true)
            @RequestParam(value = "index") String index,
            @ApiParam(name = "type", value = "索引类型", required = true)
            @RequestParam(value = "type") String type,
            @ApiParam(name = "filter", value = "过滤条件")
            @RequestParam(value = "filter" , required = false) String filter,
            @ApiParam(name = "page", value = "页码", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "分页大小", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        Page<Map<String, Object>> result = elasticSearchUtil.page(index, type, filter, page, size);
        Envelop envelop = getPageResult(result.getContent(), (int)result.getTotalElements(), page, size);
        return envelop;
    }
    @RequestMapping(value = ServiceApi.ElasticSearch.FindBySql, method = RequestMethod.GET)
    @ApiOperation(value = "获取结果集")
    public List<Map<String, Object>> findBySql (
            @ApiParam(name = "fields", value = "字段", required = true)
            @RequestParam(value = "fields") String fields,
            @ApiParam(name = "sql", value = "SQL", required = true)
            @RequestParam(value = "sql") String sql) throws Exception {
        return elasticSearchUtil.findBySql(Arrays.asList(fields.split(",")), sql);
    }
}

+ 86 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/JobController.java

@ -0,0 +1,86 @@
package com.yihu.quota.controller;
import com.yihu.quota.constants.ServiceApi;
import com.yihu.quota.service.job.JobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * 指标任务控制
 *
 * @author janseny
 */
@RestController
@RequestMapping("/api/v1.0")
@Api(description = "指标任务控制")
public class JobController extends BaseController {
    @Autowired
    private JobService jobService;
    /**
     * 初始执行指标
     */
    @ApiOperation(value = "初始执行指标")
    @RequestMapping(value = ServiceApi.TJ.FirstExecuteQuota, method = RequestMethod.POST)
    @Transactional
    public boolean firstExecuteQuota(
            @ApiParam(name = "id", value = "指标ID", required = true)
            @RequestParam(value = "id", required = true) Integer id) {
        try {
            jobService.executeJob(id, "1", null, null);
            return true;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "初始执行指标发生异常:" + e.getMessage());
            return false;
        }
    }
    /**
     * 指标执行
     */
    @ApiOperation(value = "执行指标")
    @RequestMapping(value = ServiceApi.TJ.TjQuotaExecute, method = RequestMethod.POST)
    public boolean executeQuota(
            @ApiParam(name = "id", value = "指标ID", required = true)
            @RequestParam(value = "id", required = true) Integer id,
            @ApiParam(name = "startDate", value = "起始日期")
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "截止日期")
            @RequestParam(value = "endDate", required = false) String endDate) {
        try {
            jobService.executeJob(id, "2", startDate, endDate);
            return true;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "执行指标发生异常:" + e.getMessage());
            return false;
        }
    }
    @ApiOperation(value = "停止指标")
    @RequestMapping(value = ServiceApi.TJ.TjQuotaRemove, method = RequestMethod.POST)
    public boolean removeQuota(
            @ApiParam(name = "id", value = "指标ID", required = true)
            @RequestParam(value = "id", required = true) Integer id) {
        try {
            jobService.removeJob(id);
            return true;
        } catch (Exception e) {
            error(e);
            e.printStackTrace();
            return false;
        }
    }
}

+ 93 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/MedicalInsuranceController.java

@ -0,0 +1,93 @@
//package com.yihu.quota.controller;
//
//import com.yihu.ehr.constants.ApiVersion;
//import com.yihu.ehr.util.rest.Envelop;
//import com.yihu.quota.constants.ServiceApi;
//import com.yihu.quota.service.medicalInsurance.MedicalInsuranceService;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
///**
// * @Author: zhengwei
// * @Date: 2018/9/18 09:30
// * @Description:
// */
//@RestController
//@RequestMapping("")
//@Api(description = "医保相关数据信息接口")
//public class MedicalInsuranceController extends BaseController {
//
//    @Autowired
//    private MedicalInsuranceService medicalInsuranceService;
//    @RequestMapping(value = ServiceApi.TJ.GetOftenIllList, method = RequestMethod.GET)
//    @ApiOperation(value = "频繁就医")
//    public Envelop oftenIll(
//            @ApiParam(name = "time", value = "过滤时间",required = true)
//            @RequestParam(value = "time") String time,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page) throws Exception{
//        Envelop envelop = medicalInsuranceService.oftenIll(time, size, page);
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetHighCostList, method = RequestMethod.GET)
//    @ApiOperation(value = "超高费用")
//    public Envelop highCost(
//            @ApiParam(name = "month", value = "月份", required = true)
//            @RequestParam(value = "month" , required = true) String month,
//            @ApiParam(name = "eventType", value = "就诊类型")
//            @RequestParam(value = "eventType", required = true) String eventType,
//            @ApiParam(name = "hosLevel", value = "医院等级")
//            @RequestParam(value = "hosLevel", required = false) String hosLevel,
//            @ApiParam(name = "hosHierarchy", value = "医院等次")
//            @RequestParam(value = "hosHierarchy", required = false) String hosHierarchy,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page) throws Exception{
//        Envelop envelop = medicalInsuranceService.highCost(month,eventType,hosLevel,hosHierarchy,size,page);
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetRepeateInspectList, method = RequestMethod.GET)
//    @ApiOperation(value = "重复检查")
//    public Envelop repeateInspect(
//            @ApiParam(name = "month", value = "月份", required = true)
//            @RequestParam(value = "month" , required = true) String month,
//            @ApiParam(name = "inspect", value = "检查类型", required = false)
//            @RequestParam(value = "inspect" , required = false) String inspect,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page) throws Exception{
//        Envelop envelop = medicalInsuranceService.repeateInspect(month, inspect, size, page);
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.DrugAnalysis, method = RequestMethod.GET)
//    @ApiOperation(value = "用药分析")
//    public Envelop drugAnalysis(
//            @ApiParam(name = "start", value = "开始时间", required = true)
//            @RequestParam(value = "start" , required = true) String start,
//            @ApiParam(name = "end", value = "结束时间", required = true)
//            @RequestParam(value = "end" , required = true) String end,
//            @ApiParam(name = "drugName", value = "药品名称")
//            @RequestParam(value = "drugName", required = false) String drugName,
//            @ApiParam(name = "eventType", value = "就诊类型")
//            @RequestParam(value = "eventType", required = false) String eventType,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page) throws Exception{
//        Envelop envelop = medicalInsuranceService.drugAnalysis(start, end, eventType, drugName, size, page);
//        return envelop;
//    }
//}

+ 335 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/QuotaController.java

@ -0,0 +1,335 @@
package com.yihu.quota.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.quota.constants.ServiceApi;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.model.jpa.TjQuota;
import com.yihu.quota.model.jpa.save.TjQuotaDataSave;
import com.yihu.quota.model.jpa.source.TjQuotaDataSource;
import com.yihu.quota.model.rest.ResultModel;
import com.yihu.quota.service.quota.BaseStatistsService;
import com.yihu.quota.service.quota.QuotaService;
import com.yihu.quota.service.save.TjDataSaveService;
import com.yihu.quota.service.source.TjDataSourceService;
import com.yihu.quota.vo.SaveModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 *
 * @author janseny
 */
@RestController
@RequestMapping("/api/v1.0")
@Api(description = "指标统计 -指标控制入口")
public class QuotaController extends BaseController {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private QuotaService quotaService;
    @Autowired
    private TjDataSourceService dataSourceService;
    @Autowired
    private BaseStatistsService baseStatistsService;
    @Autowired
    private TjDataSaveService dataSaveService;
/*    @Autowired
    private SolrUtil solrUtil;*/
    private static final Logger log = LoggerFactory.getLogger(QuotaController.class);
    /**
     * 查询结果
     * @param id
     * @return
     */
    @ApiOperation(value = "获取指标执行结果分页")
    @RequestMapping(value = ServiceApi.TJ.TjGetQuotaResult, method = RequestMethod.GET)
    public MixEnvelop getQuotaResult(
            @ApiParam(name = "id", value = "指标任务ID", required = true)
            @RequestParam(value = "id" , required = true) int id,
            @ApiParam(name = "filters", value = "检索条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "pageNo", value = "页码", defaultValue = "0")
            @RequestParam(value = "pageNo" , required = false ,defaultValue = "0") int pageNo,
            @ApiParam(name = "pageSize", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "pageSize" , required = false ,defaultValue ="15") int pageSize
    ) {
        MixEnvelop envelop = new MixEnvelop();
        try {
            if(filters!=null){
                filters = URLDecoder.decode(filters, "UTF-8");
            }
            System.out.println(filters);
            List<SaveModel> saveModelList = new ArrayList<SaveModel>();
            List<Map<String, Object>> resultList = quotaService.queryResultPage(id, filters, pageNo, pageSize);
            if(resultList != null && resultList.size() > 0){
                for(Map<String, Object> map : resultList){
                    SaveModel saveModel =  objectMapper.convertValue(map, SaveModel.class);
                    if(saveModel != null){
                        saveModelList.add(saveModel);
                    }
                }
            }
            long totalCount = quotaService.getQuotaTotalCount(id,filters);
            envelop.setStatus(200);
            envelop.setDetailModelList(saveModelList);
            envelop.setCurrPage(pageNo);
            envelop.setPageSize(pageSize);
            envelop.setTotalCount((int) totalCount);
            return envelop;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "查询失败:" + e.getMessage());
        }
        envelop.setStatus(-1);
        return envelop;
    }
    /**
     * 获取指标统计不同维度结果总量
     * @param id
     * @return
     */
    @ApiOperation(value = "获取指标统计不同维度结果数据")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaTotalCount, method = RequestMethod.GET)
    public MixEnvelop getQuotaTotalCount(
            @ApiParam(name = "id", value = "指标任务ID", required = true)
            @RequestParam(value = "id" , required = true) int id,
            @ApiParam(name = "filters", value = "检索条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "dimension", value = "需要统计不同维度字段多个维度用;隔开", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "top", value = "获取前几条数据")
            @RequestParam(value = "top", required = false) String top
    ) {
        MixEnvelop envelop = new MixEnvelop();
        TjQuota tjQuota = quotaService.findOne(id);
        String code = tjQuota.getCode();
        String dateType = null;
        try {
            if(filters!=null){
                filters = URLDecoder.decode(filters, "UTF-8");
                if(filters.equals("{}")){
                    filters = null;
                }
            }
            TjQuotaDataSource quotaDataSource = dataSourceService.findSourceByQuotaCode(code);
            JSONObject obj = new JSONObject().fromObject(quotaDataSource.getConfigJson());
            EsConfig esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
            List<Map<String, Object>>  resultList = new ArrayList<>();
            String configFilter = esConfig.getFilter();
            if(StringUtils.isNotEmpty(configFilter) && quotaDataSource.getSourceCode().equals("1")){//数据源为ES库
                TjQuotaDataSave quotaDataSave = dataSaveService.findByQuota(code);
                if(quotaDataSave != null && StringUtils.isNotEmpty(quotaDataSave.getConfigJson())){
                    JSONObject objSave = new JSONObject().fromObject(quotaDataSave.getConfigJson());
                    EsConfig esConfigSave = (EsConfig) JSONObject.toBean(objSave,EsConfig.class);
                    if(StringUtils.isEmpty(esConfig.getIndex()) || esConfig.getIndex().equals(esConfigSave.getIndex()) ){
                        if(StringUtils.isNotEmpty(filters)){
                            filters += " and " + configFilter;
                        }else {
                            filters = configFilter;
                        }
                    }
                }else {
                    if(StringUtils.isNotEmpty(filters)){
                        filters += " and " + configFilter;
                    }else {
                        filters = configFilter;
                    }
                }
            }
            // 判断该指标是否需要同比, 需要的话拼接时间条件
            if (StringUtils.isNotEmpty(esConfig.getIncrementFlag())) {
                filters = baseStatistsService.filtersExchangeHandle(filters, esConfig);
                log.info("filters = {}", filters);
            }
            String molecularFilter = filters;
            String denominatorFilter = filters;
            if (StringUtils.isNotEmpty(esConfig.getGrowthFlag())) {
                resultList = baseStatistsService.getGrowthByQuota(dimension, filters, esConfig, dateType, top);
            } else {
                if(tjQuota.getResultGetType().equals("1")){
                    //普通指标直接查询
                    resultList = baseStatistsService.getQuotaResultList(code, dimension, filters, dateType, top);
                }else {
                    if( (StringUtils.isNotEmpty(esConfig.getMolecular())) && StringUtils.isNotEmpty(esConfig.getDenominator())) {//除法
                        //除法指标查询输出结果
                        molecularFilter = baseStatistsService.handleFilter(esConfig.getMolecularFilter(), molecularFilter);
                        denominatorFilter = baseStatistsService.handleFilter(esConfig.getDenominatorFilter(), denominatorFilter);
                        if (StringUtils.isNotEmpty(esConfig.getDivisionType()) && esConfig.getDivisionType().equals("2")) {
                            resultList = baseStatistsService.divisionQuotaDenoConstant(esConfig.getMolecular(), dimension, molecularFilter, denominatorFilter,esConfig.getPercentOperation(), esConfig.getPercentOperationValue(), dateType, top);
                        } else {
                            resultList = baseStatistsService.divisionQuota(esConfig.getMolecular(), esConfig.getDenominator(), dimension, molecularFilter, denominatorFilter, esConfig.getPercentOperation(), esConfig.getPercentOperationValue(), dateType, top);
                        }
                    } else if (StringUtils.isNotEmpty(esConfig.getAddOperation())) {
                        String firstFilter = baseStatistsService.handleFilter(esConfig.getAddFirstFilter(), filters);
                        String secondFilter = baseStatistsService.handleFilter(esConfig.getAddSecondFilter(), filters);
                        resultList = baseStatistsService.addQuota(esConfig.getAddFirstQuotaCode(), firstFilter, esConfig.getAddSecondQuotaCode(), secondFilter, esConfig.getAddOperation(), dimension, dateType, top);
                    } else {
                        if(StringUtils.isNotEmpty(esConfig.getSuperiorBaseQuotaCode())){
                            //通过基础指标 抽取查询
                            resultList = baseStatistsService.getQuotaResultList(esConfig.getSuperiorBaseQuotaCode(), dimension,filters,dateType, top);
                        }
                    }
                }
            }
            List<ResultModel> resultModelList = new ArrayList<>();
            String [] dimens = dimension.split(";");
            if(resultList != null && resultList.size() > 0){
                for(Map<String, Object> map :resultList){
                    if(map.size() > 0){
                        List<String> cloumns = new ArrayList<>();
                        ResultModel resultModel = new ResultModel();
                        resultModel.setValue(map.get("result"));
                        for(int i = 0;i < dimens.length;i++){
                            if(map.get(dimens[i]) != null){
                                cloumns.add(map.get(dimens[i]).toString());
                            }
                        }
                        resultModel.setCloumns(cloumns);
                        resultModelList.add(resultModel);
                    }
                }
            }
            envelop.setDetailModelList(resultModelList);
            envelop.setStatus(200);
            return envelop;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "查询失败:" + e.getMessage());
        }
        envelop.setStatus(-1);
        return envelop;
    }
    /**
     * 根据指标code获取指标统计结果 swagger- 测试接口
     * @param
     * @return
     */
    @ApiOperation(value = "根据指标code获取指标统计结果")
    @RequestMapping(value = ServiceApi.TJ.TjGetReportQuotaResult, method = RequestMethod.GET)
    public MixEnvelop tjGetReportQuotaResult(
            @ApiParam(name = "code", value = "指标code", required = true)
            @RequestParam(value = "code" , required = true) String code,
            @ApiParam(name = "filters", value = "检索条件 多个条件用 and 拼接 如:town=361002 and org=10000001 ", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "dimension", value = "需要统计不同维度字段", defaultValue = "")
            @RequestParam(value = "dimension", required = true) String dimension,
            @ApiParam(name = "top", value = "获取前几条数据")
            @RequestParam(value = "top", required = false) String top
    ) {
        MixEnvelop envelop = new MixEnvelop();
        try {
            if(filters!=null){
                filters = URLDecoder.decode(filters, "UTF-8");
            }
            List<Map<String, Object>> result =  baseStatistsService.getSimpleQuotaReport(code,filters,dimension,true, top);
            envelop.setObj(result);
            envelop.setStatus(200);
            return envelop;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "查询失败:" + e.getMessage());
        }
        envelop.setStatus(-1);
        return envelop;
    }
    /*@ApiOperation("根据条件到solr中获取记录数")
    @RequestMapping(value = "/report/searchSolrByParam", method = RequestMethod.POST)
    public Envelop searchSolrByParam(
            @ApiParam(name = "core", value = "solr core名称")
            @RequestParam(value = "core") String core,
            @ApiParam(name = "eventType", value = "就诊类型")
            @RequestParam(value = "eventType") String eventType,
            @ApiParam(name = "time", value = "过滤时间")
            @RequestParam(value = "time", required = false) String time,
            @ApiParam(name = "month", value = "获取几个月数据", defaultValue = "0")
            @RequestParam(value = "month", defaultValue = "0", required = false) Integer month) throws Exception {
        Envelop envelop = new Envelop();
        List<String> xDate = new ArrayList<>(); // x轴坐标
        List<String> yDate = new ArrayList<>(); // x轴坐标对应的值
        Map<String, String> map = new HashMap();
        String q = "";
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd'T'23:59:59'Z'");
        if (StringUtils.isEmpty(eventType)) {
            q = "*:*";
        } else {
            q = "event_type:" + eventType;
        }
        if (StringUtils.isNotEmpty(time)) {
            Date dateTime = DateUtil.strToDate(time);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(dateTime);
            for (int i = 0; i < month; i++) {
                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
                String startDate = DateUtil.utcToDate(calendar.getTime());
                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                String endDate = dfs.format(calendar.getTime());
                StringBuffer sb = new StringBuffer();
                if ("1".equals(eventType)) { // 就诊类型为住院
                    sb.append("EHR_005130:[").append(startDate).append(" TO ").append(endDate).append("] OR event_date:[")
                            .append(startDate).append(" TO ").append(endDate).append("]");
                } else if ("0".equals(eventType) || "2".equals(eventType)) {  // 就诊类型为门急诊、体检
                    sb.append("event_date:[").append(startDate).append(" TO ").append(endDate).append("]");
                }
                log.info(q);
                log.info(sb.toString());
                long count = solrUtil.count(core, q, sb.toString());
                xDate.add(startDate.substring(0,7));
                yDate.add(count == 0 ? "0" : count + "");
                calendar.add(Calendar.MONTH, -1);
            }
            Collections.reverse(xDate);
            Collections.reverse(yDate);
            envelop.setSuccessFlg(true);
            envelop.setObj(xDate);
            envelop.setDetailModelList(yDate);
        }
        return envelop;
    }*/
    @ApiOperation("根据条件到solr中获取记录数,2018-11-09修改成到ES查询")
    @RequestMapping(value = "/report/searchSolrByParam", method = RequestMethod.POST)
    public MixEnvelop searchSolrByParam(
            @ApiParam(name = "core", value = "solr core名称")
            @RequestParam(value = "core") String core,
            @ApiParam(name = "eventType", value = "就诊类型")
            @RequestParam(value = "eventType") String eventType,
            @ApiParam(name = "time", value = "过滤时间")
            @RequestParam(value = "time", required = false) String time,
            @ApiParam(name = "month", value = "获取几个月数据", defaultValue = "0")
            @RequestParam(value = "month", defaultValue = "0", required = false) Integer month) throws Exception {
        MixEnvelop envelop = baseStatistsService.searchEsByParam(eventType, time, month);
        return envelop;
    }
}

+ 1050 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/QuotaReportController.java

@ -0,0 +1,1050 @@
package com.yihu.quota.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.abel533.echarts.Option;
import com.yihu.jw.restmodel.ehr.resource.MChartInfoModel;
import com.yihu.jw.restmodel.ehr.resource.MRsResources;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.quota.constants.ServiceApi;
import com.yihu.quota.model.jpa.TjQuota;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import com.yihu.quota.service.dimension.TjDimensionMainService;
import com.yihu.quota.service.dimension.TjDimensionSlaveService;
import com.yihu.quota.service.orgHealthCategory.OrgHealthCategoryStatisticsService;
import com.yihu.quota.service.quota.BaseStatistsService;
import com.yihu.quota.service.quota.QuotaService;
import com.yihu.quota.service.resource.ResourceQuotaService;
import com.yihu.quota.util.BasesicUtil;
import com.yihu.quota.util.ReportOption;
import com.yihu.quota.vo.DictModel;
import com.yihu.quota.vo.SaveModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author janseny
 */
@RestController
@RequestMapping("/api/v1.0")
@Api(description = "指标报表统计 -指标报表统计控制入口")
public class QuotaReportController extends BaseController {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private TjDimensionMainService tjDimensionMainService;
    @Autowired
    private TjDimensionSlaveService tjDimensionSlaveService;
    @Autowired
    private QuotaService quotaService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ResourceQuotaService resourceQuotaService;
    @Autowired
    private OrgHealthCategoryStatisticsService orgHealthCategoryStatisticsService;
    @Autowired
    private BaseStatistsService baseStatistsService;
/*    @Autowired
    private DeviceService deviceService;*/
    private BasesicUtil basesicUtil = new BasesicUtil();
    public static String orgHealthCategoryCode = "orgHealthCategoryCode";
    @RequestMapping(value = ServiceApi.TJ.GetYearDropdownList, method = RequestMethod.GET)
    @ApiOperation(value = "获取二维表查询年份下拉数据")
    public MixEnvelop getDropdownList(
            @ApiParam(name = "type", value = "类型 1增量型报表 2 全量型报表")
            @RequestParam(value = "type" ,required =  true ) int type,
            @ApiParam(name = "index", value = "索引")
            @RequestParam(value = "index" ,required =  true ) String index) throws Exception {
        MixEnvelop envelop = new MixEnvelop();
        Map<String, List<String>> map = null;
        String sql = "select count(1) from "+ index +" group by date_histogram(field='quotaDate','interval'='year') order by quotaDate desc";
        map = baseStatistsService.getDataInfo(sql, "date_histogram(field=quotaDate,interval=year)");
        if (null != map && map.size() > 0) {
            Collections.sort(map.get("xData"), Collections.reverseOrder());
            if(type == 1){
                envelop.setObj(map.get("xData"));
            }else {
                Map<String,String> resultMap = new HashMap<>();
                for(String key : map.get("xData")){
                    String filter = "quotaDate >= '" + key + "-01-01'" + " and quotaDate <= '" + key +"-12-31'";
                    sql = "select count(1) from "+ index +" where " + filter + " group by date_histogram(field='quotaDate','interval'='month') order by quotaDate desc";
                    System.out.println(sql);
                    Map<String, List<String>>  monthMap = baseStatistsService.getDataInfo(sql, "date_histogram(field=quotaDate,interval=month)");
                    if(monthMap != null && monthMap.size() > 0){
                        resultMap.put(key,monthMap.get("xData").get(0).toString());
                    }
                }
                envelop.setObj(resultMap);
            }
        }
        envelop.setStatus(200);
        return  envelop;
    }
    /**
     * 获取指标统计结果
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取指标统计结果")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaReport, method = RequestMethod.GET)
    public MixEnvelop getQuotaReport(
            @ApiParam(name = "id", value = "指标任务ID", required = true)
            @RequestParam(value = "id", required = true) int id,
            @ApiParam(name = "filters", value = "检索条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension
    ) {
        MixEnvelop envelop = new MixEnvelop();
        try {
            //To DO
            envelop.setStatus(200);
            return envelop;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "查询失败:" + e.getMessage());
        }
        envelop.setStatus(-1);
        return envelop;
    }
    @ApiOperation(value = "获取统计报表一个视图下多个指标组合  二维表数据")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaReportTwoDimensionalTable, method = RequestMethod.GET)
    public List<Map<String, Object>> getQuotaReportTwoDimensionalTable(
            @ApiParam(name = "quotaCodeStr", value = "指标Code,多个用,拼接", required = true)
            @RequestParam(value = "quotaCodeStr", required = true) String quotaCodeStr,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "top", value = "获取前几条数据")
            @RequestParam(value = "top", required = false) String top
    ) {
        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, List<Map<String, Object>>> quotaViewResult = new HashMap<>();
        List<String> quotaCodes = Arrays.asList(quotaCodeStr.split(","));
        String maxQuotaCode = "";
        int num = 0;
        try {
            for (String code : quotaCodes) {
                List<Map<String, Object>> quotaResult = baseStatistsService.getSimpleQuotaReport(code, filter, dimension,false, top);
                if (quotaResult.size() >= num) {
                    num = quotaResult.size();
                    maxQuotaCode = code;
                }
                quotaViewResult.put(code, quotaResult);
            }
            Map<String, List<Map<String, Object>>> otherQuotaViewResult = new HashMap<>();
            for (String key : quotaViewResult.keySet()) {
                if (key != maxQuotaCode) {
                    otherQuotaViewResult.put(key, quotaViewResult.get(key));
                }
            }
            //以查询结果数据最多的指标为主,其他指标对应维度没有数据的补充0
            for (Map<String, Object> vMap : quotaViewResult.get(maxQuotaCode)) {
                vMap.put(maxQuotaCode, vMap.get("result")==null ? 0 : ("--".equals(vMap.get("result")) ? vMap.get("result") : basesicUtil.decimalPointHandle(Double.valueOf(vMap.get("result").toString()))));
                for (String viewQuotaCode : otherQuotaViewResult.keySet()) {
                    if(otherQuotaViewResult != null && otherQuotaViewResult.get(viewQuotaCode) != null && otherQuotaViewResult.get(viewQuotaCode).size()>0 ){
                        for (Map<String, Object> quotaResultMap : otherQuotaViewResult.get(viewQuotaCode)) {
                            if (quotaResultMap.get(dimension) != null && vMap.get(dimension) != null ) {
                                if (vMap.get(dimension).toString().trim().equals(quotaResultMap.get(dimension).toString().trim())) {
                                    vMap.put(viewQuotaCode, quotaResultMap.get("result")==null ? 0 : ("--".equals(quotaResultMap.get("result")) ? quotaResultMap.get("result") : basesicUtil.decimalPointHandle(Double.valueOf(quotaResultMap.get("result").toString()))));
                                    break;
                                } else {
                                    if( !vMap.get(dimension).toString().equals("合计")){
                                        vMap.put(viewQuotaCode, 0);
                                    }
                                }
                            } else {
                                vMap.put(viewQuotaCode, 0);
                            }
                        }
                    }else {
                        vMap.put(viewQuotaCode, 0);
                    }
                }
            }
            List<Map<String, Object>> resultList = quotaViewResult.get(maxQuotaCode);
            if(dimension.equals(orgHealthCategoryCode)){//如果是特殊机构类型树状机构需要转成树状结构
                List<Map<String, Object>> orgHealthCategoryList = orgHealthCategoryStatisticsService.getOrgHealthCategoryTreeByPid(-1);
//                dataList = baseStatistsService.setResultAllDimenMap(maxQuotaCode, orgHealthCategoryList, resultList,null);
                //采用新的
                dataList = baseStatistsService.allCategoryResultMap(quotaCodes, orgHealthCategoryList, resultList);
            }else {
                dataList = resultList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        for(Map<String, Object> map : dataList){
            if(map.get("firstColumn") == null || map.get("firstColumn").toString().equals("null") || StringUtils.isEmpty(map.get("firstColumn").toString())){
                if(map.get("level")!= null && StringUtils.isNotEmpty(map.get("level").toString())){
                    String level = map.get("level").toString();
                    if (level.equals("1")){
                        level = "一级";
                    }else if (level.equals("2")){
                        level = "二级";
                    }else if (level.equals("3")){
                        level = "三级";
                    }else {
                        level = "未指定";
                    }
                    map.put("firstColumn",level);
                }
                if(map.get("economic")!= null && StringUtils.isNotEmpty(map.get("economic").toString())){
                    String economic = map.get("economic").toString();
                    if (economic.equals("1021")){
                        economic = "公立";
                    }else if (economic.equals("1022")){
                        economic = "非公立";
                    }else {
                        economic = "其他";
                    }
                    map.put("firstColumn",economic);
                }
            }
        }
        //计算合计
        if(dataList != null && dataList.size() > 0){
            Map<String, Object> sumMap = new HashMap<>();
            sumMap.put("firstColumn","合计");
            for (String code : quotaCodes) {
                String total =  existsTotal(code,dataList);
                if( total.equals("false") || total.equals("--")){
                    double sum = 0;
                    sum = calculateSum(sum,code,dataList);
                    sumMap.put(code, basesicUtil.decimalPointHandle(sum));
                }else {
                    sumMap.put(code, basesicUtil.decimalPointHandle(Double.valueOf(total)));
                }
            }
            dataList.add(0,sumMap);
            if(dataList.get(dataList.size()-1).get("firstColumn") != null){
                if(dataList.get(dataList.size()-1).get("firstColumn").equals("合计")){
                    dataList.remove(dataList.size()-1);
                }
            }
        }
        int size = dataList.size();
        if (size > 0 && dataList.get(size - 1).containsValue("合计")) {
            dataList = dataList.subList(0, size - 1);
        }
        return dataList;
    }
    /**
     * 判断指标统计中 总计 是否已经计算过
     * @param code
     * @param dataList
     * @return
     */
    private String existsTotal(String code,List<Map<String, Object>> dataList){
        for(Map<String, Object> map : dataList){
            if(map.get("firstColumn") != null && map.get("firstColumn").toString().equals("合计") && map.get(code) != null){
                if(map.get(code).toString().equals("--")){
                    return "false";
                }else {
                    return map.get(code).toString();
                }
            }
        }
        return "false";
    }
    /**
     * 统计每列合计
     * @param sum
     * @param code
     * @param dataList
     * @return
     */
    private double calculateSum( double sum,String code,List<Map<String, Object>> dataList){
        for(Map<String, Object> map : dataList){
            if(map.get(code) != null){
                sum += Double.valueOf("--".equals(map.get(code)) ? "0" : map.get(code).toString());
            }
        }
        return sum;
    }
    @ApiOperation(value = "获取指标统计结果echart图表,支持多条组合")
    @RequestMapping(value = ServiceApi.TJ.GetMoreQuotaGraphicReportPreviews, method = RequestMethod.GET)
    public MChartInfoModel getQuotaGraphicReports(
            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
            @RequestParam(value = "quotaIdStr" , required = true) String quotaIdStr,
            @ApiParam(name = "charstr", value = "多图表类型用,拼接,混合类型只支持柱状和线性", defaultValue = "1")
            @RequestParam(value = "charstr", required = true) String charstr,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "title", value = "视图名称", defaultValue = "")
            @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "top", value = "获取前几条数据")
            @RequestParam(value = "top", required = false) String top,
            @ApiParam(name = "MRsResource json串")
            @RequestParam(value = "mRsResource", required = false) String mRsResource
            ) {
        String xName = "";
        String yName = "";
        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
        List<String> charTypes = Arrays.asList(charstr.split(","));
        MChartInfoModel chartInfoModel = new MChartInfoModel();
        String dimensionName = dimension + "Name";
        if ("quotaName".equals(dimension)) {
            dimensionName = "quotaName";
        }
        try {
            Option option = null;
            List<List<Object>> optionData = new ArrayList<>();
            List<String> lineNames = new ArrayList<>();
            Map<String, Map<String, Object>> lineData = new LinkedHashMap<>();
            Map<String, String> xAxisMap = new LinkedHashMap<>();
            Integer i = 0;
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (String quotaId : quotaIds) {
                Map<String, Object> dataMap = new LinkedHashMap<>();
                TjQuota tjQuota = quotaService.findOne(Integer.valueOf(quotaId));
                if (tjQuota != null) {
                    List<Map<String, Object>> resultListMap = baseStatistsService.getSimpleQuotaReport(tjQuota.getCode(), filter, dimension,true, top);
                    if (resultListMap != null && resultListMap.size() > 0) {
                        for (Map<String, Object> map : resultListMap) {
                            if (map != null && map.size() > 0) {
                                if (map.containsKey("quotaName")) {
                                    map.put("quotaName",tjQuota.getName());
                                }
                                listMap.add(map);
                                //第一种 ES库中有定义的维度 如org,slaveKey1
                                //第二种 ES库中未定义的维度 如level,economic
                                if (map.containsKey(dimensionName)) {
                                    if(map.get(dimensionName) != null){
                                        dataMap.put(map.get(dimensionName).toString(), map.get("result"));
                                        xAxisMap.put(map.get(dimensionName).toString(), map.get(dimension).toString());
                                    }
                                } else {
                                    if(map.get(dimension) != null){
                                        dataMap.put(map.get(dimension).toString(), map.get("result"));
                                        xAxisMap.put(map.get(dimension).toString(), map.get(dimension).toString());
                                    }
                                }
                            }
                        }
                    }
                    lineData.put("" + i, dataMap);
                    lineNames.add(tjQuota.getName());
                    i++;
                }
            }
//            lineNames.add(title);
//            lineData.put("", dataMap);
            Map<String, Object> quotaMap = new LinkedHashMap<>();
            ReportOption reportOption = new ReportOption();
            int size = 0;
            String quota = "0";
            if (lineData != null && lineData.size() > 0) {
                for (String key : lineData.keySet()) {
                    int tempSize = lineData.get(key).size();
                    if (tempSize > size) {
                        size = tempSize;
                        quota = key;
                        quotaMap = lineData.get(key);
                    }
                }
                for (String key : lineData.keySet()) {
                    List<Object> dataList = new ArrayList<>();
                    Map<String, Object> valMap = lineData.get(key);
                    if (key != quota) {
                        for (String name : quotaMap.keySet()) {
                            if (valMap.containsKey(name)) {
                                dataList.add(valMap.get(name));
                            } else {
                                dataList.add(0);
                            }
                        }
                    } else {
                        for (String name : valMap.keySet()) {
                            dataList.add(valMap.get(name));
                        }
                    }
                    optionData.add(dataList);
                }
            }
            Object[] xData = (Object[]) quotaMap.keySet().toArray(new Object[quotaMap.size()]);
            for (String typeStr : charTypes) {
                if (typeStr.equals("common")) {
                    typeStr = "1";
                } else if (typeStr.equals("twoDimensional")) { // 这个需要与前端商榷  访问2次(二维表类型)
                    return null;
                }
                int type = Integer.valueOf(typeStr);
                String dataMeasurement = "";
                if (StringUtils.isNotEmpty(mRsResource)) {
                    MRsResources mRsResources = objectMapper.readValue(mRsResource, MRsResources.class);
                    dataMeasurement = mRsResources.getDataMeasurement();
                    String dataPosition = mRsResources.getDataPosition();
                    if (StringUtils.isNotEmpty(dataPosition) && "x".equalsIgnoreCase(dataPosition)) {
                        xName = "单位:" + mRsResources.getDataUnit();
                    } else if (StringUtils.isNotEmpty(dataPosition) && "y".equalsIgnoreCase(dataPosition)) {
                        yName = "单位:" + mRsResources.getDataUnit();
                    }
                }
                if (type == ReportOption.bar) {
                    option = reportOption.getLineEchartOptionMoreChart(title, xName, yName, xData, discountByMeasurement(optionData, dataMeasurement), lineNames, charTypes);
                } else if (type == ReportOption.line) {
                    option = reportOption.getLineEchartOptionMoreChart(title, xName, yName, xData, discountByMeasurement(optionData, dataMeasurement), lineNames, charTypes);
                } else if (type == ReportOption.pie) {
                    List<Map<String, Object>> datalist = new ArrayList<>();
                    for (Map<String, Object> resultMap : listMap) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("NAME", null == resultMap.get(dimensionName) ? resultMap.get(dimension) : resultMap.get(dimensionName));
                        map.put("TOTAL", resultMap.get("result"));
                        if(resultMap.get(dimensionName) != null){
                            map.put("NAME",resultMap.get(dimensionName));
                        }else {
                            //非 指标中配置的维度 关联出来的字段
                            if(dimensionName.equals("levelName")){
                                if(resultMap.get(dimension).equals("1")){
                                    map.put("NAME","一级医院");
                                }else  if(resultMap.get(dimension).equals("2")){
                                    map.put("NAME","二级医院");
                                }else  if(resultMap.get(dimension).equals("3")){
                                    map.put("NAME","三级医院");
                                }
                            }
                        }
                        map.put("TOTAL",resultMap.get("result"));
                        datalist.add(map);
                    }
                    option = reportOption.getPieEchartOption(title, "", "", datalist, lineNames.get(0), null);
                }
            }
            chartInfoModel.setOption(option.toString());
            chartInfoModel.setTitle(title);
            chartInfoModel.setxAxisMap(xAxisMap);
            return chartInfoModel;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "查询失败:" + e.getMessage());
            return null;
        }
    }
//    @ApiOperation(value = "获取指标统计结果echart图表,支持多条组合")
//    @RequestMapping(value = ServiceApi.TJ.GetMoreQuotaGraphicReportPreviews, method = RequestMethod.GET)
//    public MChartInfoModel getQuotaGraphicReports(
//            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
//            @RequestParam(value = "quotaIdStr" , required = true) String quotaIdStr,
//            @ApiParam(name = "charstr", value = "多图表类型用,拼接,混合类型只支持柱状和线性", defaultValue = "1")
//            @RequestParam(value = "charstr" , required = true) String charstr,
//            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
//            @RequestParam(value = "filter", required = false) String filter,
//            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
//            @RequestParam(value = "dimension", required = false) String dimension,
//            @ApiParam(name = "title", value = "视图名称", defaultValue = "")
//            @RequestParam(value = "title", required = false) String title
//    ) {
//        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
//        List<String> charTypes = Arrays.asList(charstr.split(","));
//        MChartInfoModel chartInfoModel = new MChartInfoModel();
//        try {
//            Option option = null;
//            List<List<Object>> optionData = new ArrayList<>();
//            List<String> lineNames = new ArrayList<>();
//            Map<String,Map<String, Object>> lineData = new LinkedHashMap<>();
//            Map<String, String> xAxisMap = new LinkedHashMap<>();
//            for(String quotaId:quotaIds){
//                Map<String, Object> dataMap = new LinkedHashMap<>();
//                TjQuota tjQuota = quotaService.findOne(Integer.valueOf(quotaId));
//                if(tjQuota != null){
//                    String dictSql = getQuotaDimensionDictSql(tjQuota.getCode(),dimension);
//                    Map<String,String> dimensionDicMap = new HashMap<>();
//                    if(StringUtils.isNotEmpty(dictSql)){
//                        BasesicUtil baseUtil = new BasesicUtil();
//                        if(dimension.contains("slaveKey")){
//                            //查询字典数据
//                            List<DictModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(DictModel.class));
//                            for (DictModel dictModel : dictDatas) {
//                                String name = baseUtil.getFieldValueByName("name", dictModel);
//                                String val = baseUtil.getFieldValueByName("code", dictModel).toLowerCase();
//                                dimensionDicMap.put(val,name);
//                            }
//                        } else{
//                            List<SaveModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(SaveModel.class));
//                            if(dictDatas != null ) {
//                                for (SaveModel saveModel : dictDatas) {
//                                    String name = baseUtil.getFieldValueByName(dimension + "Name", saveModel);
//                                    String val = baseUtil.getFieldValueByName(dimension,saveModel).toLowerCase();
//                                    dimensionDicMap.put(val,name);
//                                }
//                            }
//                        }
//                    }
//
//                    Map<String, Object> groupDataMap = new HashMap<>();
//                    if(tjQuota.getResultGetType().trim().equals("1")){
//                        //使用分组计算 返回结果实例: groupDataMap -> "4205000000-儿-1": 200 =>group by 三个字段
//                        Map<String, Integer> resultDataMap =  quotaService.searcherSumByGroupBySql(tjQuota, dimension, filter,"result","","");
//                        for(String key: resultDataMap.keySet()){
//                            groupDataMap.put(key,resultDataMap.get(key));
//                        }
//                    }else{//二次统计指标获取 结果接口
//                        List<Map<String, Object>> listMap = baseStatistsService.getSimpleQuotaReport(tjQuota.getCode(), filter, dimension);
//                        if(listMap != null && listMap.size() > 0){
//                            for(Map<String, Object> map : listMap){
//                                String keyName = "";
//                                String val = "";
//                                for (String key : map.keySet()) {
//                                    if ("result".equals(key)) {
//                                        val = map.get(key).toString();
//                                    } else {
//                                        keyName = map.get(key).toString();
//                                    }
//                                }
//                                groupDataMap.put(keyName, val);
//                            }
//                        }
//
//                    }
//
//                    for(String key : groupDataMap.keySet()){
//                        key = key.toLowerCase();
//                        dataMap.put(dimensionDicMap.containsKey(key)?dimensionDicMap.get(key):key,groupDataMap.get(key));
//                        xAxisMap.put(dimensionDicMap.containsKey(key)?dimensionDicMap.get(key): key,key);
//                    }
//                    lineNames.add(tjQuota.getName());
//                    lineData.put(tjQuota.getCode(), dataMap);
//                }
//            }
//            Map<String, Object> quotaMap = new LinkedHashMap<>();
//            ReportOption reportOption = new ReportOption();
//
//            int size = 0;
//            String quota = "";
//            if(lineData != null && lineData.size() > 0){
//                for(String key : lineData.keySet()){
//                    int tempSize = lineData.get(key).size();
//                    if (tempSize > size){
//                        size = tempSize;
//                        quota = key;
//                        quotaMap = lineData.get(key);
//                    }
//                }
//                for(String key : lineData.keySet()){
//                    List<Object> dataList = new ArrayList<>();
//                    Map<String,Object> valMap = lineData.get(key);
//                    if(key != quota){
//                        for(String name :quotaMap .keySet()){
//                            if(valMap.containsKey(name)){
//                                dataList.add(valMap.get(name));
//                            }else {
//                                dataList.add(0);
//                            }
//                        }
//                    }else{
//                        for(String name :valMap .keySet()){
//                            dataList.add(valMap.get(name));
//                        }
//                    }
//                    optionData.add(dataList);
//                }
//            }
//            Object[] xData = (Object[])quotaMap.keySet().toArray(new Object[quotaMap.size()]);
//            option = reportOption.getLineEchartOptionMoreChart(title, "", "", xData, optionData, lineNames,charTypes);
//            chartInfoModel.setOption(option.toString());
//            chartInfoModel.setTitle(title);
//            chartInfoModel.setxAxisMap(xAxisMap);
//            return chartInfoModel;
//        } catch (Exception e) {
//            error(e);
//            invalidUserException(e, -1, "查询失败:" + e.getMessage());
//            return null;
//        }
//    }
    @ApiOperation(value = "指标统计分组查询")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaGroupBy, method = RequestMethod.GET)
    public MixEnvelop getQuotaGroupBy(
            @ApiParam(name = "id", value = "指标任务ID", required = true)
            @RequestParam(value = "id", required = true) int id,
            @ApiParam(name = "filters", value = "检索条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension
    ) {
        MixEnvelop envelop = new MixEnvelop();
        try {
            TjQuota tjQuota = quotaService.findOne(id);
            Map<String, Integer>  resultMap = quotaService.searcherSumByGroupBySql(tjQuota,dimension, filters,"result","","");
            envelop.setStatus(200);
            envelop.setObj(resultMap);
            return envelop;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "查询失败:" + e.getMessage());
        }
        envelop.setStatus(-1);
        return envelop;
    }
    private String getQuotaDimensionDictSql(String quotaCode, String dimension) {
        String dictSql = "";
        //查询维度
        List<TjQuotaDimensionMain> dimensionMains = tjDimensionMainService.findTjQuotaDimensionMainByQuotaCode(quotaCode);
        if (dimensionMains != null && dimensionMains.size() > 0) {
            for (TjQuotaDimensionMain main : dimensionMains) {
                if (main.getMainCode().equals(dimension)) {
                    dictSql = main.getDictSql();
                }
            }
        }
        if (StringUtils.isEmpty(dictSql)) {
            List<TjQuotaDimensionSlave> dimensionSlaves = tjDimensionSlaveService.findTjQuotaDimensionSlaveByQuotaCode(quotaCode);
            if (dimensionSlaves != null && dimensionSlaves.size() > 0) {
                int slave = Integer.valueOf(dimension.substring(dimension.length() - 1, dimension.length()));
                if (dimensionSlaves.size() >= slave) {
                    dictSql = dimensionSlaves.get(slave - 1).getDictSql();
                }
            }
        }
        return dictSql;
    }
    @ApiOperation(value = "获取指标统计结果echart radar雷达图表")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaRadarGraphicReportPreviews, method = RequestMethod.GET)
    public MChartInfoModel getQuotaRadarGraphicReports(
            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
            @RequestParam(value = "quotaIdStr", required = true) String quotaIdStr,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "title", value = "名称", defaultValue = "")
            @RequestParam(value = "title", required = false) String title) {
        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
        MChartInfoModel chartInfoModel = new MChartInfoModel();
        List<Integer> arrayNum = new ArrayList<>();
        Integer polorCount = 50;
        try {
            Option option = null;
            List<String> radarNames = new ArrayList<>();
            Map<String, Map<String, Object>> radarData = new HashMap<>();
            List<Map<String, Object>> listData = new ArrayList<>();
            Map<String, String> xAxisMap = new HashMap<>();
            for (String quotaId : quotaIds) {
                Map<String, Object> dataMap = new HashMap<>();
                TjQuota tjQuota = quotaService.findOne(Integer.valueOf(quotaId));
                if (null != tjQuota) {
                    String dictSql = getQuotaDimensionDictSql(tjQuota.getCode(), dimension);
                    Map<String, String> dimensionDicMap = new HashMap<>();
                    dimensionDicMap = setDimensionMap(dictSql, dimension, dimensionDicMap);
                    //使用分组计算 返回结果实例: groupDataMap -> "4205000000-儿-1": 200 =>group by 三个字段
                    Map<String, Integer> groupDataMap = quotaService.searcherSumByGroupBySql(tjQuota, dimension, filter, "result", "", "");
                    for (String key : groupDataMap.keySet()) {
                        key = key.toLowerCase();
                        dataMap.put(dimensionDicMap.containsKey(key) ? dimensionDicMap.get(key) : key, groupDataMap.get(key));
                        xAxisMap.put(dimensionDicMap.containsKey(key) ? dimensionDicMap.get(key) : key, key);
                    }
                    radarNames.add(tjQuota.getName());
                    radarData.put(tjQuota.getCode(), dataMap);
                }
                Integer num = getNum(dataMap);
                arrayNum.add(num);
                Map<String, Object> map = new HashMap();
                map.put(tjQuota.getName(), num);
                listData.add(map);
            }
            ReportOption reportOption = new ReportOption();
            Integer[] array = arrayNum.toArray(new Integer[arrayNum.size()]);
            Arrays.sort(array); // 进行升序排序
            polorCount += array[arrayNum.size() - 1];   // 雷达图极坐标
            option = reportOption.getRadarEchartOption(title, listData, polorCount);
            chartInfoModel.setOption(option.toString());
            chartInfoModel.setTitle(title);
            chartInfoModel.setxAxisMap(xAxisMap);
            return chartInfoModel;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "查询失败:" + e.getMessage());
            return null;
        }
    }
//    @ApiOperation(value = "获取指标统计结果echart NestedPie图表")
//    @RequestMapping(value = ServiceApi.TJ.GetQuotaNestedPieReportPreviews, method = RequestMethod.GET)
//    public MChartInfoModel getQuotaNestedPieGraphicReports(
//            @ApiParam(name = "resourceId", value = "资源ID", defaultValue = "")
//            @RequestParam(value = "resourceId") String resourceId,
//            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
//            @RequestParam(value = "quotaIdStr", required = true) String quotaIdStr,
//            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
//            @RequestParam(value = "filter", required = false) String filter,
//            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "")
//            @RequestParam(value = "dimension", required = false) String dimension,
//            @ApiParam(name = "title", value = "名称", defaultValue = "")
//            @RequestParam(value = "title", required = false) String title) {
//        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
//        Option option = null;
//        MChartInfoModel chartInfoModel = new MChartInfoModel();
//        Map<String, String> xAxisMap = new HashMap<>();
//        try {
//            Integer quotaCount = resourceQuotaService.getQuotaCount(resourceId);
//            // 获取最顶层的资源
//            List<Integer> quotaId = new ArrayList<>();
//            ChartDataModel chartDataModel = getChartDataModel(quotaId, quotaCount, resourceId, dimension, filter, xAxisMap);
//            ReportOption reportOption = new ReportOption();
//
//            option = reportOption.getNestedPieEchartOption(title, chartDataModel);
//            chartInfoModel.setOption(option.toString());
//            chartInfoModel.setTitle(title);
//            chartInfoModel.setxAxisMap(xAxisMap);
//            return chartInfoModel;
//        } catch (Exception e) {
//            error(e);
//            invalidUserException(e, -1, "查询失败:" + e.getMessage());
//            return null;
//        }
//    }
//
//    private ChartDataModel getChartDataModel(List<Integer> quotaId, Integer count, String resourceId, String dimension, String filter, Map<String, String> xAxisMap) throws Exception {
//        ChartDataModel chartDataModel = new ChartDataModel();
//        List<RsResourceQuota> resultList = resourceQuotaService.getChildrenByPidList(quotaId, resourceId);
//        quotaId.clear();
//        for (RsResourceQuota rq : resultList) {
//            quotaId.add(Integer.valueOf(rq.getQuotaId()));
//        }
//        count = count - resultList.size();
//        if (null != resultList && resultList.size() > 0) {
//            List<Map<String, Object>> list = new ArrayList<>();
//            for (RsResourceQuota rq : resultList) {
//                RsResourceQuota parent = rq;
//                TjQuota tjQuota = quotaService.findOne(Integer.valueOf(rq.getQuotaId()));
//                Map<String, Object> dataMap = new HashMap<>();
//                if (null != tjQuota) {
//                    String dictSql = getQuotaDimensionDictSql(tjQuota.getCode(), dimension);
//                    Map<String, String> dimensionDicMap = new HashMap<>();
//                    dimensionDicMap = setDimensionMap(dictSql, dimension, dimensionDicMap);
//                    //使用分组计算 返回结果实例: groupDataMap -> "4205000000-儿-1": 200 =>group by 三个字段
//                    Map<String, Integer> groupDataMap = quotaService.searcherSumByGroupBySql(tjQuota, dimension, filter, "result", "", "");
//                    for (String key : groupDataMap.keySet()) {
//                        key = key.toLowerCase();
//                        dataMap.put(dimensionDicMap.containsKey(key) ? dimensionDicMap.get(key) : key, groupDataMap.get(key));
//                        xAxisMap.put(dimensionDicMap.containsKey(key) ? dimensionDicMap.get(key) : key, key);
//                    }
//                }
//                Integer num = getNum(dataMap);
//                List<Map<String, Object>> mapList = new ArrayList<>();
//                Map<String, Object> map = new HashMap();
//                map.put("NAME", tjQuota.getName());
//                map.put("TOTAL", num);
//                mapList.add(map);
//                rq.setMapList(mapList);
//                list.addAll(rq.getMapList());
//            }
//            chartDataModel.setList(list);
//        }
//        if (count > 0) {
//            ChartDataModel chartDataModel2 = getChartDataModel(quotaId, count, resourceId, dimension, filter, xAxisMap);
//            if (null != chartDataModel2) {
//                chartDataModel.setChildren(chartDataModel2);
//            }
//        }
//        return chartDataModel;
//    }
    private Map<String, String> setDimensionMap(String dictSql, String dimension, Map<String, String> dimensionDicMap) {
        if (StringUtils.isNotEmpty(dictSql)) {
            BasesicUtil baseUtil = new BasesicUtil();
            if (dimension.contains("slaveKey")) {
                //查询字典数据
                List<DictModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(DictModel.class));
                for (DictModel dictModel : dictDatas) {
                    String name = baseUtil.getFieldValueByName("name", dictModel);
                    String val = baseUtil.getFieldValueByName("code", dictModel).toLowerCase();
                    dimensionDicMap.put(val, name);
                }
            } else {
                List<SaveModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(SaveModel.class));
                if (dictDatas != null) {
                    for (SaveModel saveModel : dictDatas) {
                        String name = baseUtil.getFieldValueByName(dimension + "Name", saveModel);
                        String val = baseUtil.getFieldValueByName(dimension, saveModel).toLowerCase();
                        dimensionDicMap.put(val, name);
                    }
                }
            }
        }
        return dimensionDicMap;
    }
    private Integer getNum(Map<String, Object> dataMap) {
        Integer num = 0;
        for (String key : dataMap.keySet()) {
            Integer result = null != dataMap.get(key) ? Integer.parseInt(dataMap.get(key).toString()) : 0;
            num += result;
        }
        return num;
    }
//    @RequestMapping(value = "/tj/getCostAndNumOfOutPatient", method = RequestMethod.GET)
//    @ApiOperation(value = "门急诊费用、人次")
//    public Map<String, String> getCostOfOutPatient() {
//        Map<String, String> map = new HashMap<>();
//        String costOfOutPatient = baseStatistsService.getCostOfOutPatient();
//        String numOfOutPatient = baseStatistsService.getNumOfOutPatient();
//        map.put("costOfOutPatient", costOfOutPatient);
//        map.put("numOfOutPatient", numOfOutPatient);
//        return map;
//    }
//
//    @RequestMapping(value = "/tj/getCostAndNumOfInPatient", method = RequestMethod.GET)
//    @ApiOperation(value = "入院费用、人次")
//    public Map<String, String> getNumOfOutPatient() {
//        Map<String, String> map = new HashMap<>();
//        String costOfInPatient = baseStatistsService.getCostOfInPatient();
//        String numOfInPatient = baseStatistsService.getNumOfInPatient();
//        map.put("costOfInPatient", costOfInPatient);
//        map.put("numOfInPatient", numOfInPatient);
//        return map;
//    }
    @RequestMapping(value = "/tj/getMedicalMonitorInfo", method = RequestMethod.GET)
    @ApiOperation(value = "医改监测信息")
    public Map<String, String> getMedicalMonitorInfo() {
        Map<String, String> map = new HashMap<>();
        String costOfMedicalMonitor = baseStatistsService.getCostOfMedicalMonitor();
        map.put("costOfMedicalMonitor", costOfMedicalMonitor);
        return map;
    }
    @ApiOperation(value = "首页费用组成")
    @RequestMapping(value = ServiceApi.TJ.GetCostComposeReports, method = RequestMethod.GET)
    public MChartInfoModel getCostComposeReports(
            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
            @RequestParam(value = "quotaIdStr" , required = true) String quotaIdStr,
            @ApiParam(name = "charType", value = "图表类型用", defaultValue = "1")
            @RequestParam(value = "charType", required = true) String charType,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "title", value = "视图名称", defaultValue = "")
            @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "top", value = "获取前几条数据")
            @RequestParam(value = "top", required = false) String top
    ) {
        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
        MChartInfoModel chartInfoModel = new MChartInfoModel();
        String dimensionName = dimension + "Name";
        if ("quotaName".equals(dimension)) {
            dimensionName = "quotaName";
        }
        try {
            Option option = null;
            List<String> lineNames = new ArrayList<>();
            Map<String, Map<String, Object>> lineData = new LinkedHashMap<>();
            Map<String, String> xAxisMap = new LinkedHashMap<>();
            Integer i = 0;
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (String quotaId : quotaIds) {
                Map<String, Object> dataMap = new LinkedHashMap<>();
                TjQuota tjQuota = quotaService.findOne(Integer.valueOf(quotaId));
                if (tjQuota != null) {
                    List<Map<String, Object>> resultListMap = baseStatistsService.getSimpleQuotaReport(tjQuota.getCode(), filter, dimension,true, top);
                    if (resultListMap != null && resultListMap.size() > 0) {
                        for (Map<String, Object> map : resultListMap) {
                            if (map != null && map.size() > 0) {
                                if (map.containsKey("quotaName")) {
                                    map.put("quotaName",tjQuota.getName());
                                }
                                //第一种 ES库中有定义的维度 如org,slaveKey1
                                //第二种 ES库中未定义的维度 如level,economic
                                if (map.containsKey(dimensionName)) {
                                    if(map.get(dimensionName) != null){
                                        dataMap.put(map.get(dimensionName).toString(), map.get("result"));
                                        xAxisMap.put(map.get(dimensionName).toString(), map.get(dimension).toString());
                                    }
                                } else {
                                    if(map.get(dimension) != null){
                                        dataMap.put(map.get(dimension).toString(), map.get("result"));
                                        xAxisMap.put(map.get(dimension).toString(), map.get(dimension).toString());
                                    }
                                }
                            }
                        }
                    }
                }
                lineData.put("" + i, dataMap);
                lineNames.add(tjQuota.getName());
                i++;
            }
            Set<String> hashSet = new HashSet<>(lineNames);
            Map<String, Object> newMap = new HashMap<>();
            for (Map<String, Object> data : lineData.values()) {
                for (Map.Entry<String, Object> lastMap : data.entrySet()) {
                    if (newMap.containsKey(lastMap.getKey())) {
                        double v = Double.parseDouble(newMap.get(lastMap.getKey()) + "") + Double.parseDouble(lastMap.getValue() + "");
                        newMap.put(lastMap.getKey() + "", basesicUtil.decimalPointHandle(v));
                    } else {
                        newMap.put(lastMap.getKey(), lastMap.getValue());
                    }
                    hashSet.add(lastMap.getKey());
                }
            }
            lineNames.clear();
            lineNames.addAll(hashSet);
            lineData.clear();
            for (int j = 0; j < lineNames.size(); j++) {
                String name = lineNames.get(j);
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put(name, newMap.get(name));
                lineData.put("" + j, tempMap);
                Map<String, Object> listMapCon = new HashMap<>();
                listMapCon.put("quotaName", name);
                listMapCon.put("result", newMap.get(name));
                listMap.add(listMapCon);
            }
            ReportOption reportOption = new ReportOption();
            if (charType.equals("common")) {
                charType = "1";
            } else if (charType.equals("twoDimensional")) {
                return null;
            }
            List<String> charTypes = Arrays.asList(charType);
            int type = Integer.valueOf(charType);
            if (type == ReportOption.bar) {
                return null;    // 尚未拓展
            } else if (type == ReportOption.line) {
                return null;    // 尚未拓展
            } else if (type == ReportOption.pie) {
                List<Map<String, Object>> datalist = new ArrayList<>();
                for (Map<String, Object> resultMap : listMap) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("NAME", null == resultMap.get(dimensionName) ? resultMap.get(dimension) : resultMap.get(dimensionName));
                    map.put("TOTAL", resultMap.get("result"));
                    if(resultMap.get(dimensionName) != null){
                        map.put("NAME",resultMap.get(dimensionName));
                    }else {
                        //非 指标中配置的维度 关联出来的字段
                        if(dimensionName.equals("levelName")){
                            if(resultMap.get(dimension).equals("1")){
                                map.put("NAME","一级医院");
                            }else  if(resultMap.get(dimension).equals("2")){
                                map.put("NAME","二级医院");
                            }else  if(resultMap.get(dimension).equals("3")){
                                map.put("NAME","三级医院");
                            }
                        }
                    }
                    map.put("TOTAL",resultMap.get("result"));
                    datalist.add(map);
                }
                option = reportOption.getPieEchartOption(title, "", "", datalist, lineNames.get(0), null);
            }
            chartInfoModel.setOption(option.toString());
            chartInfoModel.setTitle(title);
            chartInfoModel.setxAxisMap(xAxisMap);
            return chartInfoModel;
        } catch (Exception e) {
            error(e);
            invalidUserException(e, -1, "查询失败:" + e.getMessage());
            return null;
        }
    }
   /* @RequestMapping(value = ServiceApi.TJ.GetDeviceReports, method = RequestMethod.GET)
    @ApiOperation(value = "报表-卫生设备一览")
    public Envelop getDeviceReports(
            @ApiParam(name = "year", value = "年份", required = true)
            @RequestParam(value = "year" , required = true) String year,
            @ApiParam(name = "district", value = "区县编码")
            @RequestParam(value = "district", required = false) String district,
            @ApiParam(name = "organization", value = "机构名称或者组织机构代码", defaultValue = "")
            @RequestParam(value = "organization", required = false) String organization,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page) throws Exception{
        Envelop envelop = new Envelop();
        List<MQcDevice> list = new ArrayList<>();
        DataList dataList = deviceService.listMQcDeviceByYearAndDistrictAndOrg(year,district,organization,page ,size);
        if(null!= dataList && null!=dataList.getList() && dataList.getList().size()>0){
            for(int i=0; i<dataList.getList().size(); i++){
                Map<String,Object> dataMap = (Map<String, Object>) dataList.getList().get(i);
                MQcDevice newEntity = objectMapper.readValue(toJson(dataMap), MQcDevice.class);
                list.add(newEntity);
            }
        }
        envelop.setDetailModelList(list);
        envelop.setSuccessFlg(true);
        envelop.setPageSize(size);
        envelop.setCurrPage(page);
        envelop.setTotalPage((int)dataList.getPage());
        envelop.setTotalCount((int)dataList.getCount());
        return envelop;
    }*/
    protected String toJson(Object obj) throws JsonProcessingException {
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        return objectMapper.writeValueAsString(obj);
    }
    /**
     * 如果有计量单位,则把数值换算成相应的数值单位
     * @param optionData
     * @param dataMeasurement
     * @return
     */
    public List<List<Object>> discountByMeasurement(List<List<Object>> optionData, String dataMeasurement) {
        if (!StringUtils.isEmpty(dataMeasurement)) {
            List<List<Object>> handleList = new ArrayList<>();
            double v = Double.parseDouble(dataMeasurement);
            optionData.forEach(one -> {
                List<Object> list = new ArrayList<>();
                one.forEach(item -> {
                    if(item != null && !item.toString().equals("--")){
                        item = basesicUtil.decimalPointHandle(Double.parseDouble(item.toString()) / v);
                        list.add(item);
                    }else {
                        list.add(0);
                    }
                });
                handleList.add(list);
            });
            return handleList;
        }
        return optionData;
    }
}

+ 108 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/QuotaReportStatisticsController.java

@ -0,0 +1,108 @@
package com.yihu.quota.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.restmodel.ehr.dict.MapDict;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.quota.constants.ServiceApi;
import com.yihu.quota.model.jpa.TjQuota;
import com.yihu.quota.service.quota.QuotaService;
import com.yihu.quota.util.BasesicUtil;
import com.yihu.quota.vo.SaveModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
 * Created by janseny on 2017/12/14.
 */
@RestController
@RequestMapping("/api/v1.0")
@Api(description = "报表统计 - 统计指标 接口")
public class QuotaReportStatisticsController extends BaseController {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private QuotaService quotaService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @RequestMapping(value = ServiceApi.Resources.StatisticsGetDoctorsGroupByTown, method = RequestMethod.GET)
    @ApiOperation(value = "获取各行政区划总卫生人员", notes = "获取各行政区划总卫生人员")
    MixEnvelop statisticsGetDoctorsGroupByTown(){
        MixEnvelop envelop = new MixEnvelop();
        List<MapDict> dataList = new ArrayList<>();
        String quotaCode = "HC_02_0015";
        String dimension = "town";
        try {
            TjQuota tjQuota = quotaService.findByCode(quotaCode);
            String dictSql = "SELECT id as town,name as townName  from address_dict where pid = '361100'";
            List<SaveModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(SaveModel.class));
            Map<String,String> dimensionDicMap = new HashMap<>();
            if(dictDatas != null ) {
                BasesicUtil baseUtil = new BasesicUtil();
                for (SaveModel saveModel : dictDatas) {
                    String name = baseUtil.getFieldValueByName(dimension + "Name", saveModel);
                    String val = baseUtil.getFieldValueByName(dimension, saveModel).toLowerCase();
                    dimensionDicMap.put(val,name);
                }
            }
            Map<String, Integer> resultMap = new HashMap<>();
            String filter = "year = ";
            Calendar currCal = Calendar.getInstance();
            int currentYear = currCal.get(Calendar.YEAR);
            boolean flag = true;
            while (flag){
                filter = filter + currentYear;
                resultMap = quotaService.searcherSumByGroupBySql(tjQuota, dimension, filter,"result","year","asc");
                if(resultMap != null && resultMap.size() > 0){
                    for(String key:resultMap.keySet()){
                        MapDict mapDict = new MapDict();
                        mapDict.setName(dimensionDicMap.containsKey(key)?dimensionDicMap.get(key):key);
                        mapDict.setValue(resultMap.get(key));
                        dataList.add(mapDict);
                    }
                    flag = false;
                }
                currentYear --;
                if(currentYear <=2016){
                    flag = false;
                }
            }
            envelop.setObj(objectMapper.writeValueAsString(dataList));
        } catch (Exception e) {
            e.printStackTrace();
        };
        envelop.setStatus(200);
        return envelop;
    }
}

+ 440 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/SingleDiseasesController.java

@ -0,0 +1,440 @@
//package com.yihu.quota.controller;
//
//import com.yihu.ehr.constants.ApiVersion;
//import com.yihu.ehr.constants.ServiceApi;
//import com.yihu.ehr.util.rest.Envelop;
//import com.yihu.quota.service.singledisease.SingleDiseaseService;
//import com.yihu.quota.service.singledisease.SingleDiseaseServiceNew;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.util.*;
//
///**
// * Created by janseny on 2018/4/4.
// */
//
//@RestController
//@RequestMapping("/api/v1.0")
//@Api(description = "单病种报表统计 - 糖尿病")
//public class SingleDiseasesController {
//
//    @Autowired
//    private SingleDiseaseService singleDiseaseService;
//    @Autowired
//    private SingleDiseaseServiceNew singleDiseaseServiceNew;
//
//    @RequestMapping(value = ServiceApi.TJ.GetHeatMap, method = RequestMethod.GET)
//    @ApiOperation(value = "热力图")
//    public Envelop getHeatMap(
//            @ApiParam(name = "condition", value = "过滤条件", defaultValue = "")
//            @RequestParam(value = "condition", required = false) String condition) throws Exception {
//        Envelop envelop = new Envelop();
//        if(StringUtils.isEmpty(condition)){
//            condition = "";
//        }else {
//            if( condition.contains("undefined")){
//                condition = "";
//            }
//        }
//        List<Map<String,String>>  heatMapPoint = singleDiseaseService.getHeatMap(condition);
//        envelop.setSuccessFlg(true);
//        if (null != heatMapPoint && heatMapPoint.size() > 0) {
//            envelop.setDetailModelList(heatMapPoint);
//        }
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetNumberOfDiabetes, method = RequestMethod.GET)
//    @ApiOperation(value = "糖尿病患者数")
//    public Envelop getNumberOfDiabetes(
//            @ApiParam(name = "condition", value = "过滤条件", defaultValue = "")
//            @RequestParam(value = "condition", required = false) String condition) throws Exception {
//        Envelop envelop = new Envelop();
//        if(StringUtils.isEmpty(condition)){
//            condition = "";
//        }else {
//            if( condition.contains("undefined")){
//                condition = "";
//            }
//        }
//        List<Map<String, Object>> numberOfDiabetes = singleDiseaseService.getNumberOfDiabetes(condition);
//        envelop.setSuccessFlg(true);
//        envelop.setDetailModelList(numberOfDiabetes);
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetPieData, method = RequestMethod.GET)
//    @ApiOperation(value = "获取饼图数据")
//    public Envelop getPieData(
//            @ApiParam(name = "type", value = "类型", required = true)
//            @RequestParam(value = "type") String type,
//            @ApiParam(name = "condition", value = "过滤条件", defaultValue = "")
//            @RequestParam(value = "condition", required = false) String condition) throws Exception {
//        Envelop envelop = new Envelop();
//        if(StringUtils.isEmpty(condition)){
//            condition = "";
//        }else {
//            if( condition.contains("undefined")){
//                condition = "";
//            }
//        }
//        Map<String, Object> pieDataInfo = singleDiseaseService.getPieDataInfo(type, condition);
//        envelop.setSuccessFlg(true);
//        if (null != pieDataInfo && pieDataInfo.size() > 0) {
//            envelop.setObj(pieDataInfo.get("legendData"));
//            ArrayList<Map<String, Object>> seriesData = (ArrayList<Map<String, Object>>) pieDataInfo.get("seriesData");
//            envelop.setDetailModelList(seriesData);
//        }
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetLineData, method = RequestMethod.GET)
//    @ApiOperation(value = "获取折线图数据")
//    public Envelop getLineData(
//            @ApiParam(name = "condition", value = "过滤条件", defaultValue = "")
//            @RequestParam(value = "condition", required = false) String condition) throws Exception {
//        Envelop envelop = new Envelop();
//        if(StringUtils.isEmpty(condition)){
//            condition = "";
//        }else {
//            if( condition.contains("undefined")){
//                condition = "";
//            }
//        }
//        Map<String, List<String>> map = singleDiseaseService.getLineDataInfo(condition);
//        envelop.setSuccessFlg(true);
//        if (null != map && map.size() > 0) {
//            envelop.setDetailModelList(map.get("valueData"));
//            envelop.setObj(map.get("xData"));
//        }
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetBarData, method = RequestMethod.GET)
//    @ApiOperation(value = "获取柱状图数据")
//    public Envelop getBarData(
//            @ApiParam(name = "type", required = true, value = "类型 1并发症 2用药患者数 3空腹血糖统计 4糖耐量")
//            @RequestParam(value = "type") String type,
//            @ApiParam(name = "condition", value = "过滤条件", defaultValue = "")
//            @RequestParam(value = "condition", required = false) String condition) throws Exception {
//        Envelop envelop = new Envelop();
//        if(StringUtils.isEmpty(condition)){
//            condition = "";
//        }else {
//            if( condition.contains("undefined")){
//                condition = "";
//            }
//        }
//        Map<String, List<String>> map = null;
//        if ("1".equals(type) || "2".equals(type)) {
//            if ("1".equals(type)) {
//                map = singleDiseaseService.getSymptomDataInfo(condition);
//            } else {
//                map = singleDiseaseService.getMedicineDataInfo(condition);
//            }
//            if (null != map && map.size() > 0) {
//                envelop.setDetailModelList(map.get("valueData"));
//                envelop.setObj(map.get("xData"));
//            }
//        } else if ("3".equals(type) || "4".equals(type)){
//            if ("3".equals(type)) {
//                map = singleDiseaseService.getFastingBloodGlucoseDataInfo(condition);
//            } else {
//                map = singleDiseaseService.getSugarToleranceDataInfo(condition);
//            }
////            if (null != map && map.size() > 0) {
////                List<Map<String, Object>> list = new ArrayList<>();
////                Map<String, Object> myMap = new HashMap<>();
////                myMap.put("男", map.get("valueData1"));
////                myMap.put("女", map.get("valueData2"));
////                list.add(myMap);
////                envelop.setDetailModelList(list);
////                envelop.setObj(map.get("xData"));
////            }
//
//            if (null != map && map.size() > 0) {
//                envelop.setDetailModelList(map.get("valueData"));
//                envelop.setObj(map.get("xData"));
//            }
//        }
//        envelop.setSuccessFlg(true);
//
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetDiseaseTypeAnalysisInfo, method = RequestMethod.GET)
//    @ApiOperation(value = "获取疾病类型分析数据")
//    public Envelop getDiseaseTypeAnalysisInfo(
//            @ApiParam(name = "type", required = true, value = "1 年份 2 月趋势")
//            @RequestParam(value = "type", defaultValue = "1") String type,
//            @ApiParam(name = "filter", value = "过滤的年份")
//            @RequestParam(value = "filter", required = false) String filter) {
//        Envelop envelop = new Envelop();
//        if(StringUtils.isEmpty(filter)){
//            filter = "";
//        }else {
//            if( filter.contains("undefined")){
//                filter = "";
//            }
//        }
//        Map<String, List<String>> diseaseTypeInfo = singleDiseaseService.getDiseaseTypeAnalysisInfo(type, filter);
//        List<Map<String, Object>> listMap = new ArrayList<>();
//        envelop.setSuccessFlg(true);
//        if (null != diseaseTypeInfo && diseaseTypeInfo.size() > 0) {
//            Map<String, List<String>> map = new HashMap<>();
//            List<String> list = diseaseTypeInfo.get("xName");
//            List<String> list1 = diseaseTypeInfo.get("name");
//            map.put("name", list1);
//            map.put("xName", list);
//            envelop.setObj(map);
//            for (int i = 1; i < 5; i++) {
//                Map<String, Object> valueMap = new HashMap<>();
//                valueMap.put("name", singleDiseaseService.getNameByIdType(i, "1"));
//                valueMap.put("value", diseaseTypeInfo.get("type" + i));
//                listMap.add(valueMap);
//            }
//            envelop.setDetailModelList(listMap);
//        }
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetSexAnalysisInfo, method = RequestMethod.GET)
//    @ApiOperation(value = "获取疾病类型分析数据")
//    public Envelop getSexAnalysisInfo(
//            @ApiParam(name = "type", required = true, value = "1 年份 2 月趋势")
//            @RequestParam(value = "type", defaultValue = "1") String type,
//            @ApiParam(name = "filter", value = "过滤的年份")
//            @RequestParam(value = "filter", required = false) String filter) {
//        Envelop envelop = new Envelop();
//        if(StringUtils.isEmpty(filter)){
//            filter = "";
//        }else {
//            if( filter.contains("undefined")){
//                filter = "";
//            }
//        }
//        Map<String, List<String>> diseaseTypeInfo = singleDiseaseService.getSexAnalysisInfo(type, filter);
//        List<Map<String, Object>> listMap = new ArrayList<>();
//        envelop.setSuccessFlg(true);
//        if (null != diseaseTypeInfo && diseaseTypeInfo.size() > 0) {
//            Map<String, List<String>> map = new HashMap<>();
//            map.put("name", diseaseTypeInfo.get("name"));
//            map.put("xName", diseaseTypeInfo.get("xName"));
//            envelop.setObj(map);
//            for (int i = 1; i < 4; i++) {
//                Map<String, Object> valueMap = new HashMap<>();
//                valueMap.put("name", singleDiseaseService.getNameByIdType(i, "2"));
//                valueMap.put("value", diseaseTypeInfo.get("type" + i));
//                listMap.add(valueMap);
//            }
//            envelop.setDetailModelList(listMap);
//        }
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.TJ.GetAgeAnalysisInfo, method = RequestMethod.GET)
//    @ApiOperation(value = "获取疾病类型分析数据")
//    public Envelop getAgeAnalysisInfo(
//            @ApiParam(name = "type", required = true, value = "1 年份 2 月趋势")
//            @RequestParam(value = "type", defaultValue = "1") String type,
//            @ApiParam(name = "filter", value = "过滤的年份")
//            @RequestParam(value = "filter", required = false) String filter) {
//        Envelop envelop = new Envelop();
//        if(StringUtils.isEmpty(filter)){
//            filter = "";
//        }else {
//            if( filter.contains("undefined")){
//                filter = "";
//            }
//        }
//        Map<String, List<String>> diseaseTypeInfo = singleDiseaseService.getAgeAnalysisInfo(type, filter);
//        List<Map<String, Object>> listMap = new ArrayList<>();
//        envelop.setSuccessFlg(true);
//        if (null != diseaseTypeInfo && diseaseTypeInfo.size() > 0) {
//            Map<String, List<String>> map = new HashMap<>();
//            map.put("name", diseaseTypeInfo.get("name"));
//            map.put("xName", diseaseTypeInfo.get("xName"));
//            envelop.setObj(map);
//            for (int i = 1; i < 6; i++) {
//                Map<String, Object> valueMap = new HashMap<>();
//                valueMap.put("name", singleDiseaseService.getNameByIdType(i, "3"));
//                valueMap.put("value", diseaseTypeInfo.get("type" + i));
//                listMap.add(valueMap);
//            }
//            envelop.setDetailModelList(listMap);
//        }
//        return envelop;
//    }
//
//    @RequestMapping(value = ServiceApi.SingleDisease.GetDropdownList, method = RequestMethod.GET)
//    @ApiOperation(value = "获取并发症和药品查询下拉列表前十 数据")
//    public Envelop getDropdownList(
//            @ApiParam(name = "type", value = "类型 1并发症 2 药品 3年份")
//            @RequestParam(value = "type" ,required =  true ) String type) throws Exception {
//        Envelop envelop = new Envelop();
//        String sql = "";
//        Map<String, List<String>> map = null;
//        if ("1".equals(type)) {
//            sql = "select symptomName, count(*) count from singleDiseaseCheck where checkCode = 'CH001' group by symptomName order by count desc";
//            map = singleDiseaseServiceNew.getDataInfo(sql, "symptomName");
//        } else if ("2".equals(type)) {
//            sql = "select medicineName, count(*) count from singleDiseaseCheck where checkCode = 'CH004' group by medicineName order by count desc";
//            map = singleDiseaseServiceNew.getDataInfo(sql, "medicineName");
//        } else {
//            sql = "select count(*) from singleDiseasePersonal group by date_histogram(field='eventDate','interval'='year') order by eventDate";
//            map = singleDiseaseServiceNew.getDataInfo(sql, "date_histogram(field=eventDate,interval=year)");
//        }
//        System.out.println("listData count 3333" + map.size());
//        if (null != map && map.size() > 0) {
//            if(map.get("xData").size()>9){
//                envelop.setDetailModelList(map.get("xData").subList(0,10));
//            }else {
//                envelop.setDetailModelList(map.get("xData"));
//            }
//        }
//        envelop.setSuccessFlg(true);
//        return  envelop;
//    }
//
//
//    @RequestMapping(value = ServiceApi.SingleDisease.GetSymptomDetailData, method = RequestMethod.GET)
//    @ApiOperation(value = "获取并发症详细查询页 数据")
//    public Object getSymptomDetailData(
//            @ApiParam(name = "name", value = "并发症名称")
//            @RequestParam(value = "name" ,required = false ,defaultValue = "") String name) throws Exception {
//        Map resultMap = new HashMap<>();
//        Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR) + 1;
//        String range = "range(birthYear," + (year - 151) + "," + (year - 66) + "," + (year - 41) + "," + (year - 18) + "," + (year - 7) + "," + year + ")";
//        String yearSql = "";
//        String typeSql = "";
//        String ageSql = "";
//        String sexSql = "";
//        if(StringUtils.isEmpty(name)){
//            name = "";
//        }else {
//            if( name.contains("undefined")){
//                name = "";
//            }
//        }
//        if(StringUtils.isNotEmpty(name)) {
//            name = " and symptomName = '" + name + "'";
//            yearSql = "select count(*) count from singleDiseaseCheck where checkCode = 'CH001' " + name + " group by date_histogram(field='eventDate','interval'='year')";
//            typeSql = "select diseaseTypeName,count(*) count from singleDiseaseCheck where checkCode = 'CH001' " + name + " group by diseaseTypeName";
//            ageSql = "select count(*) from singleDiseaseCheck where checkCode = 'CH001' and birthYear <> 0 " + name + " group by " + range;
//            sexSql = "select sexName, count(*) count from singleDiseaseCheck where checkCode = 'CH001' " + name + " group by sexName";
//        }else {
//            yearSql = "select count(*) count from singleDiseaseCheck where checkCode = 'CH001' group by date_histogram(field='eventDate','interval'='year')";
//            typeSql = "select diseaseTypeName,count(*) count from singleDiseaseCheck where checkCode = 'CH001' group by diseaseTypeName";
//            ageSql = "select count(*) from singleDiseaseCheck where checkCode = 'CH001'and birthYear <> 0  group by " + range;
//            sexSql = "select sexName, count(*) count from singleDiseaseCheck where checkCode = 'CH001' group by sexName";
//        }
//        //按年趋势 柱状图
//        Map<String, List<String>>  map = singleDiseaseServiceNew.getDataInfo(yearSql,"date_histogram(field=eventDate,interval=year)");
//        if (null != map && map.size() > 0) {
//            Envelop envelop = new Envelop();
//            envelop.setSuccessFlg(true);
//            envelop.setDetailModelList(map.get("valueData"));
//            envelop.setObj(map.get("xData"));
//            resultMap.put("year",envelop);
//        }
//        //按糖尿病类型 饼图
//        Map<String, Object> diseaseTypeDataInfo = singleDiseaseServiceNew.getPieDataInfoBySql("1", typeSql, "diseaseTypeName");
//        if (null != diseaseTypeDataInfo && diseaseTypeDataInfo.size() > 0) {
//            Envelop envelop = new Envelop();
//            envelop.setSuccessFlg(true);
//            envelop.setObj(diseaseTypeDataInfo.get("legendData"));
//            ArrayList<Map<String, Object>> seriesData = (ArrayList<Map<String, Object>>) diseaseTypeDataInfo.get("seriesData");
//            envelop.setDetailModelList(seriesData);
//            resultMap.put("type",envelop);
//        }
//        //按年龄段 饼图
//        Map<String, Object> ageDataInfo = singleDiseaseServiceNew.getPieDataInfoBySql("2", ageSql, "birthYear");
//        if (null != ageDataInfo && ageDataInfo.size() > 0) {
//            Envelop envelop = new Envelop();
//            envelop.setSuccessFlg(true);
//            envelop.setObj(ageDataInfo.get("legendData"));
//            ArrayList<Map<String, Object>> seriesData = (ArrayList<Map<String, Object>>) ageDataInfo.get("seriesData");
//            envelop.setDetailModelList(seriesData);
//            resultMap.put("age",envelop);
//        }
//        //按性别饼图
//        Map<String, Object> sexDataInfo = singleDiseaseServiceNew.getPieDataInfoBySql("3", sexSql, "sexName");
//        if (null != sexDataInfo && sexDataInfo.size() > 0) {
//            Envelop envelop = new Envelop();
//            envelop.setSuccessFlg(true);
//            envelop.setObj(sexDataInfo.get("legendData"));
//            ArrayList<Map<String, Object>> seriesData = (ArrayList<Map<String, Object>>) sexDataInfo.get("seriesData");
//            envelop.setDetailModelList(seriesData);
//            resultMap.put("sex",envelop);
//        }
//        return  resultMap;
//    }
//
//    @RequestMapping(value = ServiceApi.SingleDisease.GetMedicineDetailData, method = RequestMethod.GET)
//    @ApiOperation(value = "获取药品详细查询页 数据")
//    public Object getMedicineDetailData(
//            @ApiParam(name = "name", value = "药品名称")
//            @RequestParam(value = "name" ,required =  false, defaultValue = "") String name) throws Exception {
//        Map resultMap = new HashMap<>();
//        String yearsql = "";
//        String typeSql = "";
//        String symptomSql = "";
//        if(StringUtils.isEmpty(name)){
//            name = "";
//        }else {
//            if( name.contains("undefined")){
//                name = "";
//            }
//        }
//        if(StringUtils.isNotEmpty(name)){
//            name = "and medicineName = '" + name + "'";
//            yearsql = "select count(*) count from singleDiseaseCheck where checkCode = 'CH004' " + name +  " group by date_histogram(field='eventDate','interval'='year')";
//            typeSql = "select diseaseTypeName,count(*) count from singleDiseaseCheck where checkCode = 'CH004' " + name + " group by diseaseTypeName";
//            symptomSql = "select symptomName,count(*) count from singleDiseaseCheck where checkCode = 'CH004' " + name + " group by symptomName";
//        }else {
//            yearsql = "select count(*) count from singleDiseaseCheck where checkCode = 'CH004' group by date_histogram(field='eventDate','interval'='year')";
//            typeSql = "select diseaseTypeName,count(*) count from singleDiseaseCheck where checkCode = 'CH004' group by diseaseTypeName";
//            symptomSql = "select symptomName,count(*) count from singleDiseaseCheck where checkCode = 'CH004' group by symptomName";
//        }
//        //按年趋势
//        Map<String, List<String>> map = singleDiseaseServiceNew.getDataInfo(yearsql, "date_histogram(field=eventDate,interval=year)");
//        if (null != map && map.size() > 0) {
//            Envelop envelop = new Envelop();
//            envelop.setSuccessFlg(true);
//            envelop.setDetailModelList(map.get("valueData"));
//            envelop.setObj(map.get("xData"));
//            resultMap.put("year",envelop);
//        }
//        //按糖尿病类型 饼图
//        Map<String, Object> diseaseTypeDataInfo = singleDiseaseServiceNew.getPieDataInfoBySql("1", typeSql, "diseaseTypeName");
//        if (null != diseaseTypeDataInfo && diseaseTypeDataInfo.size() > 0) {
//            ArrayList<Map<String, Object>> seriesData = (ArrayList<Map<String, Object>>) diseaseTypeDataInfo.get("seriesData");
//            Envelop envelop = new Envelop();
//            envelop.setSuccessFlg(true);
//            envelop.setDetailModelList(seriesData);
//            envelop.setObj(diseaseTypeDataInfo.get("legendData"));
//            resultMap.put("type",envelop);
//        }
//        //按相关并发症 饼图
//        Map<String, Object> symptomDataInfo = singleDiseaseServiceNew.getPieDataInfoBySql("4", symptomSql, "symptomName");
//        if (null != symptomDataInfo && symptomDataInfo.size() > 0) {
//            ArrayList<Map<String, Object>> seriesData = (ArrayList<Map<String, Object>>) symptomDataInfo.get("seriesData");
//            Envelop envelop = new Envelop();
//            envelop.setSuccessFlg(true);
//            envelop.setDetailModelList(seriesData);
//            envelop.setObj(symptomDataInfo.get("legendData"));
//            resultMap.put("symptom",envelop);
//        }
//        return  resultMap;
//    }
//
//}

+ 362 - 0
svr/svr-quota/src/main/java/com/yihu/quota/controller/SolrStatisticsEndPoint.java

@ -0,0 +1,362 @@
//package com.yihu.quota.controller;
//
//import com.yihu.ehr.constants.ApiVersion;
//import com.yihu.ehr.constants.ServiceApi;
//import com.yihu.ehr.controller.EnvelopRestEndPoint;
//import com.yihu.ehr.solr.SolrUtil;
//import com.yihu.ehr.util.rest.Envelop;
//import com.yihu.quota.service.org.OrgService;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.solr.client.solrj.response.FacetField;
//import org.apache.solr.common.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import java.text.DateFormat;
//import java.text.SimpleDateFormat;
//import java.util.*;
//
//@RestController
//@RequestMapping(value = ApiVersion.Version1_0)
//@Api(value = "SolrStatisticsEndPoint", description = "门急诊服务统计接口", tags = {"临时报表接口--门急诊服务统计接口"})
//public class SolrStatisticsEndPoint extends EnvelopRestEndPoint {
//
//    @Autowired
//    private SolrUtil solr;
//    @Autowired
//    private OrgService orgService;
//
//    @ApiOperation("本月科室门诊人次")
//    @RequestMapping(value = ServiceApi.OutpatientServiceStatistic.StatisticDeptOutpatientSum, method = RequestMethod.GET)
//    public Envelop statisticDeptOutpatientSum() {
//        Envelop envelop = new Envelop();
//        envelop.setSuccessFlg(false);
//        try {
//            String startDay = getCurrMonthFirstDay();
//            String endDay = getCurrMonthLastDay();
//            String fq = String.format("event_type:0 AND event_date:[%s TO %s]", startDay, endDay);
//            String facetField = "EHR_000081"; // 按【科室】分组
//            Map<String, Object> result = oneFieldGroup(facetField, fq);
//            envelop.setObj(result);
//            envelop.setSuccessFlg(true);
//        } catch (Exception e) {
//            e.printStackTrace();
//            envelop.setErrorMsg("统计【本月科室门诊人次】发生异常");
//        }
//        return envelop;
//    }
//
//    @ApiOperation("本月科室转诊人次")
//    @RequestMapping(value = ServiceApi.OutpatientServiceStatistic.StatisticDeptTransferTreatmentSum, method = RequestMethod.GET)
//    public Envelop statisticDeptTransferTreatmentSum() {
//        Envelop envelop = new Envelop();
//        envelop.setSuccessFlg(false);
//        try {
//            String startDay = getCurrMonthFirstDay();
//            String endDay = getCurrMonthLastDay();
//            String fq = String.format("event_type:0 AND EHR_000083:T AND event_date:[%s TO %s]", startDay, endDay);
//            String facetField = "EHR_000081"; // 按【科室】分组
//            Map<String, Object> result = oneFieldGroup(facetField, fq);
//            envelop.setObj(result);
//            envelop.setSuccessFlg(true);
//        } catch (Exception e) {
//            e.printStackTrace();
//            envelop.setErrorMsg("统计【本月科室转诊人次】发生异常");
//        }
//        return envelop;
//    }
//
//    /**
//     * 根据指定字段分组统计
//     * @param facetField 分组字段名
//     * @param fq 筛选条件
//     * @return
//     * @throws Exception
//     */
//    private Map<String, Object> oneFieldGroup(String facetField, String fq) throws Exception {
//        String startDay = getCurrMonthFirstDay();
//        String endDay = getCurrMonthLastDay();
//        FacetField facetResult = solr.getFacetField("HealthProfile", facetField, fq, 0, 0, -1, false);
//        List<FacetField.Count> facetCountList = facetResult.getValues();
//        List<String> nameList = new ArrayList<>();
//        List<Long> valList = new ArrayList<>();
//        for(FacetField.Count item : facetCountList) {
//            nameList.add(item.getName());
//            valList.add(item.getCount());
//        }
//        Map<String, Object> result = new HashMap<>();
//        result.put("nameList", nameList);
//        result.put("valList", valList);
//        return result;
//    }
//
//    @ApiOperation("当月相关数据")
//    @RequestMapping(value = "/statistics/{position}", method = RequestMethod.POST)
//    public Envelop statistics(
//            @ApiParam(name = "core", value = "集合", required = true)
//            @RequestParam(value = "core") String core,
//            @ApiParam(name = "position", value = "位置参数1,2,3,4", required = true)
//            @PathVariable(value = "position") String position) throws Exception {
//        if (position.equals("1")) {
//            return emergencyRoom(core);
//        }else if(position.equals("2")){
//            return hundredPeople(core);
//        }else if(position.equals("3")){
//            return emergency(core);
//        }else if(position.equals("4")) {
//            return referral(core);
//        }else {
//            Envelop envelop = new Envelop();
//            envelop.setSuccessFlg(false);
//            envelop.setErrorMsg("参数:" + position + ",有误!");
//            return envelop;
//        }
//    }
//
//    /**
//     * 本月门急诊人次
//     * @return
//     */
//    private Envelop emergencyRoom(String core) throws Exception {
//        Envelop envelop = new Envelop();
//        Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR);
//        int month = calendar.get(Calendar.MONTH) + 1;
//        String monthStr;
//        if (month < 10) {
//            monthStr = "0" + month;
//        } else {
//            monthStr = "" + month;
//        }
//        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//        String start = String.format("%s-%s-01T00:00:00Z", year, monthStr);
//        String end = dateFormat.format(calendar.getTime());
//        String q = String.format("event_type:0 AND event_date:[%s TO %s]", start, end);
//        Map<String, Integer> data1 = solr.getFacetQuery(core, q);
//        Integer clinic = data1.get(q);
//        envelop.setSuccessFlg(true);
//        envelop.setObj(clinic);
//        return envelop;
//    }
//
//    /**
//     * 本月每百门急诊入院人数
//     * @param core
//     * @return
//     * @throws Exception
//     */
//    private Envelop hundredPeople(String core) throws Exception {
//        Envelop envelop = new Envelop();
//        Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR);
//        int month = calendar.get(Calendar.MONTH) + 1;
//        String monthStr;
//        if (month < 10) {
//            monthStr = "0" + month;
//        } else {
//            monthStr = "" + month;
//        }
//        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//        //获取当月住院数据
//        String start = String.format("%s-%s-01T00:00:00Z", year, monthStr);
//        String end = dateFormat.format(calendar.getTime());
//        String q = String.format("event_type:1 AND event_date:[%s TO %s]", start, end);
//        Map<String, Integer> data1 = solr.getFacetQuery(core, q);
//        Integer hospitalized = data1.get(q);
//        //获取当月门诊数据
//        q = String.format("event_type:0 AND event_date:[%s TO %s]", start, end);
//        Map<String, Integer> data2 = solr.getFacetQuery(core, q);
//        Integer clinic = data2.get(q);
//        if (clinic == 0) {
//            clinic = 1;
//        }
//        int count = hospitalized / clinic / 100;
//        envelop.setSuccessFlg(true);
//        envelop.setObj(count);
//        return envelop;
//    }
//
//    /**
//     * 本月急诊总人次数
//     * @return
//     */
//    private Envelop emergency(String core) throws Exception {
//        Envelop envelop = new Envelop();
//        Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR);
//        int month = calendar.get(Calendar.MONTH) + 1;
//        String monthStr;
//        if (month < 10) {
//            monthStr = "0" + month;
//        } else {
//            monthStr = "" + month;
//        }
//        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//        String start = String.format("%s-%s-01T00:00:00Z", year, monthStr);
//        String end = dateFormat.format(calendar.getTime());
//        String q = String.format("event_type:0 AND EHR_001240:51 AND event_date:[%s TO %s]", start, end);
//        Map<String, Integer> data1 = solr.getFacetQuery(core, q);
//        Integer clinic = data1.get(q);
//        envelop.setSuccessFlg(true);
//        envelop.setObj(clinic);
//        return envelop;
//    }
//
//    /**
//     * 本月转诊人次
//     *
//     * @return
//     */
//    private Envelop referral(String core) throws Exception {
//        Envelop envelop = new Envelop();
//        Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR);
//        int month = calendar.get(Calendar.MONTH) + 1;
//        String monthStr;
//        if (month < 10) {
//            monthStr = "0" + month;
//        } else {
//            monthStr = "" + month;
//        }
//        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//        String start = String.format("%s-%s-01T00:00:00Z", year, monthStr);
//        String end = dateFormat.format(calendar.getTime());
//        String q = String.format("event_type:0 AND EHR_000083:T AND event_date:[%s TO %s]", start, end);
//        Map<String, Integer> data1 = solr.getFacetQuery(core, q);
//        Integer clinic = data1.get(q);
//        envelop.setSuccessFlg(true);
//        envelop.setObj(clinic);
//        return envelop;
//    }
//
//    @ApiOperation("医院门急诊人次分布")
//    @RequestMapping(value = "/statistics/monthDistribution", method = RequestMethod.POST)
//    public Envelop monthDistribution(
//            @ApiParam(name = "core", value = "集合", required = true)
//            @RequestParam(value = "core") String core,
//            @ApiParam(name = "year", value = "年份", required = true)
//            @RequestParam(value = "year") int year) throws Exception {
//        Envelop envelop = new Envelop();
//        Calendar calendar = Calendar.getInstance();
//        int nowYear = calendar.get(Calendar.YEAR);
//        if(nowYear > year) {
//            calendar.set(Calendar.MONTH, 11);
//        }
//        calendar.set(Calendar.YEAR, year);
//        calendar.set(Calendar.DAY_OF_MONTH, 1);
//        calendar.set(Calendar.HOUR_OF_DAY, 0);
//        calendar.set(Calendar.MINUTE, 0);
//        calendar.set(Calendar.SECOND, 0);
//        calendar.set(Calendar.MILLISECOND, 0);
//        int month = calendar.get(Calendar.MONTH) + 1;
//        List<Map<String, Integer>> dataList = new ArrayList<>(month);
//        for(int i = 1; i <= month; i ++) {
//            String monthStr;
//            if(i < 10) {
//                monthStr = "0" + i;
//            }else {
//                monthStr = "" + i;
//            }
//            String start = String.format("%s-%s-01T00:00:00Z", year, monthStr);
//            String end;
//            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//            calendar.set(Calendar.MONTH, i - 1);
//            int day;
//            if(i == month && nowYear == year) {
//                Calendar calendar1 = Calendar.getInstance();
//                end = dateFormat.format(calendar1.getTime());
//            }else {
//                day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
//                end = String.format("%s-%s-%sT23:59:59Z", year, monthStr, day);
//            }
//            String q = String.format("event_type:0 AND event_date:[%s TO %s]", start, end);
//            Map<String, Integer> data = solr.getFacetQuery(core, q);
//            data.put(monthStr, data.get(q));
//            data.remove(q);
//            dataList.add(data);
//        }
//        envelop.setSuccessFlg(true);
//        envelop.setDetailModelList(dataList);
//        return envelop;
//    }
//
//    @ApiOperation("本月各类医院门急诊人次")
//    @RequestMapping(value = "/statistics/rescue", method = RequestMethod.POST)
//    public Envelop variousTypes() throws Exception{
//        Envelop envelop = new Envelop();
//        Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR);
//        int month = calendar.get(Calendar.MONTH) + 1;
//        String monthStr;
//        if(month < 10) {
//            monthStr = "0" + month;
//        }else {
//            monthStr = "" + month;
//        }
//        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//        String start = String.format("%s-%s-01T00:00:00Z", year, monthStr);
//        String end = dateFormat.format(calendar.getTime());
//        String fq = String.format("event_type:0 AND event_date:[%s TO %s]", start, end);
//        FacetField facetField = solr.getFacetField("HealthProfile", "org_code", fq, 0, 0, 1000000, false);
//        List<FacetField.Count> list = facetField.getValues();
//        Map<String, Long> dataMap = new HashMap<>(list.size());
//        for(FacetField.Count count : list) {
//            dataMap.put(count.getName(), count.getCount());
//        }
//        Map<String, Long> resultMap = new HashMap<>();
//        for(String code : dataMap.keySet()) {
//            String level = orgService.getLevel(code);
//            if(!StringUtils.isEmpty(level)) {
//                if(resultMap.containsKey(level)) {
//                    long count = resultMap.get(level) + dataMap.get(code);
//                    resultMap.put(level, count);
//                }else {
//                    resultMap.put(level, dataMap.get(code));
//                }
//            }else {
//                if(resultMap.containsKey("9")) {
//                    long count = resultMap.get("9") + dataMap.get(code);
//                    resultMap.put("9", count);
//                }else {
//                    resultMap.put("9", dataMap.get(code));
//                }
//            }
//        }
//
//        Map<String, Object> resap = new HashMap<>();
//        // dictId=99 (医院等级)
//        Map<String,Object> dictEntrysMap = orgService.getDictEntries(99);
//        for(String code : resultMap.keySet()) {
//            if(null != dictEntrysMap.get(code)){
//                resap.put(dictEntrysMap.get(code).toString(),resultMap.get(code));
//            }else{
//                resap.put(code,resultMap.get(code));
//            }
//        }
//
//        envelop.setSuccessFlg(true);
//        envelop.setObj(resap);
//        return envelop;
//    }
//
//    // 获取当月第一天日期(精确到00:00:00)
//    private String getCurrMonthFirstDay() {
//        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.DAY_OF_MONTH, 1);
//        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//        String date = sf.format(calendar.getTime());
//        return date + "T00:00:00Z";
//    }
//
//    // 获取当月最后一天(精确到23:59:59)
//    private String getCurrMonthLastDay() {
//        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.DATE, calendar.getActualMaximum(calendar.DATE));
//        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//        String date = sf.format(calendar.getTime());
//        return date + "T23:59:59Z";
//    }
//
//}

+ 30 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/RsResourceQuotaDao.java

@ -0,0 +1,30 @@
package com.yihu.quota.dao.jpa;
import com.yihu.quota.model.jpa.RsResourceQuota;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * Created by Administrator on 2017/12/19.
 */
public interface RsResourceQuotaDao extends PagingAndSortingRepository<RsResourceQuota, Integer>, JpaSpecificationExecutor<RsResourceQuota> {
    @Query("select count(rq.quotaId) from RsResourceQuota rq where rq.resourceId = :resourceId")
    Integer fingQuotaCount(@Param("resourceId") String resourceId);
    @Query("select rq from RsResourceQuota rq where rq.resourceId = :resourceId and rq.pid = :pid")
    List<RsResourceQuota> findChildByPidAndResourceId(@Param("resourceId") String resourceId, @Param("pid") Integer pid);
    @Query(" FROM RsResourceQuota rq WHERE rq.resourceId = :resourceId and rq.pid = null ")
    List<RsResourceQuota> getTopParents(@Param("resourceId") String resourceId);
    @Query("select  rq FROM RsResourceQuota rq WHERE rq.resourceId = :resourceId and rq.quotaId = :quotaId")
    RsResourceQuota findByResourceIdAndQuotaId(@Param("resourceId")String resourceId, @Param("quotaId")Integer quotaId);
    @Query("select rq from RsResourceQuota rq where rq.resourceId = :resourceId and rq.pid in (:pid)")
    List<RsResourceQuota> findChildByPidAndResourceIds(@Param("resourceId") String resourceId, @Param("pid") List<Integer> pid);
}

+ 13 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/TjQuotaDao.java

@ -0,0 +1,13 @@
package com.yihu.quota.dao.jpa;
import com.yihu.quota.model.jpa.TjQuota;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjQuotaDao extends JpaRepository<TjQuota, Integer>, JpaSpecificationExecutor<TjQuota> {
    TjQuota findByCode(String code);
}

+ 18 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/TjQuotaGovProvisionDao.java

@ -0,0 +1,18 @@
package com.yihu.quota.dao.jpa;
import com.yihu.quota.model.jpa.TjQuotaGovProvision;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
/**
 * Created by wxw on 2018/3/6.
 */
public interface TjQuotaGovProvisionDao extends PagingAndSortingRepository<TjQuotaGovProvision, Long>{
    @Query("select sum(gp.population) from TjQuotaGovProvision gp where gp.administrativeDivision = :town and gp.year = :year ")
    Long getSumByDistrict(@Param("town") long town, @Param("year") String year);
    @Query("select sum(gp.population) from TjQuotaGovProvision gp where  gp.year = :year ")
    Long getSumByDistrict(@Param("year") String year);
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/TjQuotaLogDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa;
import com.yihu.quota.model.jpa.TjQuotaLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/2.
 */
public interface TjQuotaLogDao extends PagingAndSortingRepository<TjQuotaLog, Long>, JpaSpecificationExecutor< TjQuotaLog> {
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dict/SystemDictDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa.dict;
import com.yihu.quota.model.jpa.dict.SystemDict;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface SystemDictDao extends PagingAndSortingRepository<SystemDict, Long>, JpaSpecificationExecutor<SystemDict> {
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dict/SystemDictListDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa.dict;
import com.yihu.quota.model.jpa.dict.SystemDictList;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface SystemDictListDao extends PagingAndSortingRepository<SystemDictList, Long>, JpaSpecificationExecutor<SystemDictList> {
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dimension/TjDimensionMainDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa.dimension;
import com.yihu.quota.model.jpa.dimension.TjDimensionMain;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjDimensionMainDao extends PagingAndSortingRepository<TjDimensionMain, Long>, JpaSpecificationExecutor<TjDimensionMain> {
}

+ 12 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dimension/TjDimensionSlaveDao.java

@ -0,0 +1,12 @@
package com.yihu.quota.dao.jpa.dimension;
import com.yihu.quota.model.jpa.dimension.TjDimensionSlave;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjDimensionSlaveDao extends PagingAndSortingRepository<TjDimensionSlave, Long>, JpaSpecificationExecutor<TjDimensionSlave
        > {
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dimension/TjQuotaDimensionMainDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa.dimension;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjQuotaDimensionMainDao extends PagingAndSortingRepository<TjQuotaDimensionMain, Long>, JpaSpecificationExecutor<TjQuotaDimensionMain> {
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/dimension/TjQuotaDimensionSlaveDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa.dimension;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjQuotaDimensionSlaveDao extends PagingAndSortingRepository<TjQuotaDimensionSlave, Long>, JpaSpecificationExecutor<TjQuotaDimensionSlave> {
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/save/TjDataSaveDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa.save;
import com.yihu.quota.model.jpa.save.TjDataSave;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjDataSaveDao extends PagingAndSortingRepository<TjDataSave, Long>, JpaSpecificationExecutor<TjDataSave> {
}

+ 14 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/save/TjQuotaDataSaveDao.java

@ -0,0 +1,14 @@
package com.yihu.quota.dao.jpa.save;
import com.yihu.quota.model.jpa.save.TjQuotaDataSave;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjQuotaDataSaveDao extends PagingAndSortingRepository<TjQuotaDataSave, Long>, JpaSpecificationExecutor<TjQuotaDataSave> {
    TjQuotaDataSave findByQuotaCode(String quotaCode);
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/source/TjDataSourceDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa.source;
import com.yihu.quota.model.jpa.source.TjDataSource;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjDataSourceDao extends PagingAndSortingRepository<TjDataSource, Long>, JpaSpecificationExecutor<TjDataSource> {
}

+ 11 - 0
svr/svr-quota/src/main/java/com/yihu/quota/dao/jpa/source/TjQuotaDataSourceDao.java

@ -0,0 +1,11 @@
package com.yihu.quota.dao.jpa.source;
import com.yihu.quota.model.jpa.source.TjQuotaDataSource;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/1.
 */
public interface TjQuotaDataSourceDao extends PagingAndSortingRepository<TjQuotaDataSource, Long>, JpaSpecificationExecutor<TjQuotaDataSource> {
}

+ 268 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/Contant.java

@ -0,0 +1,268 @@
package com.yihu.quota.etl;
import org.joda.time.DateTime;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
/**
 * Created by chenweida on 2017/6/1.
 */
public class Contant {
    //抽取数据的开始时间
    public static String startTime = "${start_time}";
    //抽取数据的结束时间
    public static String endTime = "${end_time}";
    //数据库类型
    public static class db_type {
        public static String oracle = "oracle";
        public static String mysql = "mysql";
    }
    /**
     * DateModel的map的key常量
     */
    public static class extract {
        public static final String computeKey1 = "oneKey";
        public static final String computeKey2 = "senondKey";
    }
    /**
     * 运算常量
     */
    public static class compute {
        public static final String add = "1"; //累加
        public static final String division = "2"; //相除
        public static final int perCount = 20000;//单位统计量
    }
    /**
     * 主维度常量
     */
    public static class main_dimension {
        public static final String time_day = "1";//时间维度 日
        public static final String time_week = "2";//时间维度 周
        public static final String time_month = "3";//时间维度  月
        public static final String time_year = "4";//时间维度 年
        public static final String area_province = "5";//行政区划 省
        public static final String area_city = "6";//行政区划 市
        public static final String area_town = "7";//行政区划 区县
        public static final String area_org = "8";//行政区划 机构
        public static final String area_dept = "9";//科室
    }
    public static class quota {
        public static final String dataLevel_all = "1"; // 全量
        public static final String dataLevel_increase = "2"; // 增量
        public static final String aggregation_count = "count";
        public static final String aggregation_sum = "sum";
        public static final String aggregation_list = "list";
        public static final String aggregation_distinct = "distinct"; // 去重
    }
    /**
     * areaLevel 具体的值
     */
    public static class main_dimension_areaLevel {
        public static final String area_province = "1";//行政区划 省
        public static final String area_city = "2";//行政区划 市
        public static final String area_town = "3";//行政区划 区县
        public static final String area_org = "4";//行政区划 机构
        public static final String area_dept = "5";//行政区划 科室
        public static String getAreaLevelByMainDimension(String key) {
            switch (key) {
                case main_dimension.area_province: {
                    return area_province;
                }
                case main_dimension.area_city: {
                    return area_city;
                }
                case main_dimension.area_town: {
                    return area_town;
                }
                case main_dimension.area_org: {
                    return area_org;
                }
                case main_dimension.area_dept: {
                    return area_dept;
                }
            }
            return "";
        }
    }
    /**
     * 主维度 时间维度
     */
    public static class main_dimension_timeLevel {
        public static final String year = "1";
        public static final String month = "2";
        public static final String week = "3";
        public static final String day = "4";
        public static String getStartTime(String key) {
            LocalDate today = LocalDate.now();
            if (StringUtils.isEmpty(key)) {
                key = day;
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00'Z'");
            switch (key) {
                case year: {
                    //去年度第一天
                    return simpleDateFormat.format(getCurrYearFirst(-1));
                }
                case month: {
                    //上个月第一天
                    return getYesterMonthDay(simpleDateFormat, -1);
                }
                case week: {
                    //上周周第一天
                    return getStartDayOfWeek(simpleDateFormat, -1);
                }
                case day: {
                    //昨天
                    return getYesterday();
                }
            }
            return getYesterday();
        }
        /**
         * 获取这个月第一天
         *
         * @param today
         * @return
         */
        private static String getCurrentMonthDay(LocalDate today) {
            LocalDate firstday = LocalDate.of(today.getYear(), today.getMonth(), 1);
            return firstday.format(DateTimeFormatter.ISO_DATE);
        }
        /**
         * 获取上个月第一天
         *
         * @return
         */
        private static String getYesterMonthDay(SimpleDateFormat simpleDateFormat, Integer n) {
            Calendar calendar = Calendar.getInstance();
            int month = calendar.get(Calendar.MONTH);
            calendar.set(Calendar.MONTH, month + n);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            Date strDateTo = calendar.getTime();
            return simpleDateFormat.format(strDateTo);
        }
        /**
         * 获取本周第一天
         *
         * @param simpleDateFormat
         * @param n                为推迟的周数,1本周,-1向前推迟一周,2下周,依次类推
         * @return
         */
        private static String getStartDayOfWeek(SimpleDateFormat simpleDateFormat, Integer n) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, n * 7);
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            Date date = cal.getTime();
            return simpleDateFormat.format(date);
        }
        /**
         * 获取去年的第一天
         *
         * @return
         */
        private static Date getCurrYearFirst(Integer n) {
            Calendar currCal = Calendar.getInstance();
            int currentYear = currCal.get(Calendar.YEAR) + n;
            return getYearFirst(currentYear);
        }
        /**
         * 获取某年第一天日期
         *
         * @param year 年份
         * @return Date
         */
        private static Date getYearFirst(int year) {
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.set(Calendar.YEAR, year);
            Date currYearFirst = calendar.getTime();
            return currYearFirst;
        }
        /**
         * 获取昨天
         *
         * @return
         */
        private static String getYesterday() {
            return new org.joda.time.LocalDate(new DateTime().minusDays(1)).toString("yyyy-MM-dd'T'00:00:00'Z'");
        }
    }
    public static class save_status {
        public static final String success = "1";
        public static final String fail = "0";
        public static final String executing = "2";
    }
    public static class save {
        public static final String es = "1";
        public static final String mysql = "2";
    }
    public static class convert{
        public static String level_age_1="1";
        public static String level_age_2="2";
        public static String level_age_3="3";
        public static String level_age_4="4";
        public static String level_age_5="5";
        public static String level_age_1_name="0~6";
        public static String level_age_2_name="7~17";
        public static String level_age_3_name="18~40";
        public static String level_age_4_name="41~65";
        public static String level_age_5_name=">65";
    }
    public static class quartz_cron {
        //每年 1月1号 0点 0点0秒触发
        public static final String everyYearFirstDay = "0 0 0 1 1 ? *";
        //每个月1号 0点 0点0秒触发
        public static final String everyMonthFirstDay = "0 0 0 1 * ?";
        //每周一 0点 0点0秒触发
        public static final String everyWeekFirstDay = "0 0 0 ? * MON";
        //每天0点0分 0秒触发
        public static final String everyDay = "0 0 0 * * ?";
    }
    public static class orgHealthTypeCode {
        public static final String hospital = "hospital"; //医院卫生机构
        public static final String basicMedical = "basic_medical"; //基层医疗卫生机构
        public static final String pro_public = "pro_public";//专业公共卫生机构
        public static final String other = "other";//其他医疗卫生机构
        public static final String hospital_Id = "13"; //医院卫生机构
        public static final String basicMedical_Id = "57"; //基层医疗卫生机构
        public static final String pro_public_Id = "94";//专业公共卫生机构
        public static final String other_Id = "134";//其他医疗卫生机构
    }
}

+ 47 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/ExtractConverUtil.java

@ -0,0 +1,47 @@
package com.yihu.quota.etl;
import com.yihu.quota.etl.conver.ConvertHelper;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import com.yihu.quota.util.SpringUtil;
import com.yihu.quota.vo.FilterModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by janseny on 2018/5/10.
 */
@Component
@Scope("prototype")
public class ExtractConverUtil {
    private Logger logger = LoggerFactory.getLogger(ExtractConverUtil.class);
    /**
     * 细维度数据转换
     * @param filterModel
     * @param qds
     * @return
     */
    public FilterModel convert(FilterModel filterModel, List<TjQuotaDimensionSlave> qds) throws Exception {
        try {
            if( qds != null && qds.size() > 0  && filterModel.getDataList()!= null  && filterModel.getDataList().size() > 0){
                for(TjQuotaDimensionSlave slave : qds){
                    if(  !StringUtils.isEmpty(slave.getConverClass())){
                        return SpringUtil.getBean(ConvertHelper.class).convert(filterModel, slave);
                    }
                }
            }else {
                return  filterModel;
            }
        } catch (Exception e) {
            throw new Exception("数据转换异常"+e.getMessage());
        }
        return null;
    }
}

+ 99 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/conver/AgeConvert.java

@ -0,0 +1,99 @@
package com.yihu.quota.etl.conver;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by janseny on 2018/5/9.
 * 年龄转换
 */
public class AgeConvert implements Convert {
    private static String patient_age = "patient_age";  //solr年龄
    private static String mysql_age = "cardIdCalculateAge(id_card_no)";  //mysql 年龄
    /**
     * @param dataList  数据
     * @return
     */
    public List<Map<String, Object>> convert(JdbcTemplate jdbcTemplate, List<Map<String, Object>> dataList , TjQuotaDimensionSlave slave ) {
        System.out.println("run in age Conver");
        Map<String,Object> tempMap = new HashMap<>();
        List<Map<String, Object>> result = new ArrayList<>();
        for(Map<String, Object> one:dataList) {
            try {
                //TODO 业务逻辑处理
                int age = 0;
                String ageStr = "";
                String oldAgeStr = "";
                tempMap = one;
                if(one.get(patient_age) != null ||  one.get(mysql_age) != null ){
                    String ageIndex = "";
                    if(one.get(patient_age) != null){
                        ageIndex = patient_age;
                    }else  if(one.get(mysql_age) != null){
                        ageIndex = mysql_age;
                    }
                    oldAgeStr = one.get(ageIndex).toString();
                    ageStr = oldAgeStr;
                    boolean falg = false;
                    if(ageStr.contains("岁") ){
                        ageStr = ageStr.substring(0,ageStr.indexOf("岁"));
                        falg = true;
                    }else if(ageStr.contains("月")){
                        ageStr = "0";
                        falg = true;
                    }else if(ageStr.contains("天")){
                        ageStr = "0";
                        falg = true;
                    }else{
                        if(ageStr.contains(".")){
                            ageStr = ageStr.substring(0,ageStr.indexOf("."));
                            falg = true;
                        }else {
                            falg = true;
                        }
                    }
                    if(falg){
                        age = Integer.parseInt(ageStr);
                        String ageLevel = getAgeCode(age);
                        tempMap.put(ageIndex,ageLevel);
                        if(one.get("$statisticsKey") != null){
                            String statisticsKey = one.get("$statisticsKey").toString();
                            tempMap.put("$statisticsKey",statisticsKey.replaceAll(oldAgeStr,ageLevel));
                        }
                        result.add(tempMap);
                    }
                }else{
                    result.add(tempMap);
                }
            } catch (Exception e) {
               throw  new NumberFormatException("年龄转换有误!" + e.getMessage());
            }
        };
        return result;
    }
    // TODO 从数据字典中提取 年龄段区间
    public String getAgeCode(Integer age) {
        if (age <= 6) {
            return Contant.convert.level_age_1;
        } else if (age >= 7 && age <= 17) {
            return Contant.convert.level_age_2;
        } else if (age >= 18 && age <= 40) {
            return Contant.convert.level_age_3;
        } else if (age >= 41 && age < 65) {
            return Contant.convert.level_age_4;
        } else {
            return Contant.convert.level_age_5;
        }
    }
}

+ 24 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/conver/Convert.java

@ -0,0 +1,24 @@
package com.yihu.quota.etl.conver;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;
/**
 * Created by janseny on 2018/5/9.
 */
public interface Convert {
    /**
     * @param jdbcTemplate jdbc工具
     * @param dataList 需要赋值的数据
     * @param slave 细维度
     * @return
     */
    public List<Map<String, Object>> convert(JdbcTemplate jdbcTemplate, List<Map<String, Object>> dataList , TjQuotaDimensionSlave slave);
}

+ 44 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/conver/ConvertHelper.java

@ -0,0 +1,44 @@
package com.yihu.quota.etl.conver;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import com.yihu.quota.vo.FilterModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
 * Created by janseny on 2018/5/9.
 * 维度的key值转换器
 */
@Component
@Scope("prototype")
public class ConvertHelper {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 维度的key清洗到对应的slaveKey中
     * @param filterModel     过滤之后的model
     * @param tjQuotaDimensionSlave 维度
     * @return
     * @throws Exception
     */
    public FilterModel convert(FilterModel filterModel, TjQuotaDimensionSlave tjQuotaDimensionSlave) throws Exception {
        List<Map<String, Object>> data = filterModel.getDataList();
        String clazz = tjQuotaDimensionSlave.getConverClass();
        if (!StringUtils.isEmpty(clazz)) {
            //反射出对象并且调用convert方法去转换对应的slavekey
            Object obj = Class.forName(clazz).newInstance();
            Method method = obj.getClass().getMethod("convert", JdbcTemplate.class, List.class, TjQuotaDimensionSlave.class);
            data = (List<Map<String, Object>>) method.invoke(obj, jdbcTemplate, data, tjQuotaDimensionSlave);
            filterModel.setDataList(data);
        }
        return filterModel;
    }
}

+ 162 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/ExtractHelper.java

@ -0,0 +1,162 @@
package com.yihu.quota.etl.extract;
import com.yihu.quota.etl.extract.es.EsExtract;
import com.yihu.quota.etl.extract.mysql.MysqlExtract;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import com.yihu.quota.model.jpa.save.TjQuotaDataSave;
import com.yihu.quota.model.jpa.source.TjDataSource;
import com.yihu.quota.model.jpa.source.TjQuotaDataSource;
import com.yihu.quota.service.dimension.TjDimensionMainService;
import com.yihu.quota.service.dimension.TjDimensionSlaveService;
import com.yihu.quota.service.save.TjDataSaveService;
import com.yihu.quota.service.source.TjDataSourceService;
import com.yihu.quota.util.SpringUtil;
import com.yihu.quota.vo.QuotaVo;
import com.yihu.quota.vo.SaveModel;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by chenweida on 2017/6/1.
 */
@Component
@Scope("prototype")
public class ExtractHelper {
    @Autowired
    private TjDataSourceService dataSourceService;
    @Autowired
    private TjDataSaveService datsSaveService;
    @Autowired
    private TjDimensionMainService dimensionMainService;
    @Autowired
    private TjDimensionSlaveService dimensionSlaveService;
    @Autowired
    private EsExtract esExtract;
/*    @Autowired
    private SolrExtract solrExtract;*/
    private Logger logger = LoggerFactory.getLogger(ExtractHelper.class);
    public EsConfig getEsConfig(String quotaCode) throws Exception {
        //得到该指标的数据存储位置
        TjQuotaDataSave quotaDataSave = datsSaveService.findByQuota(quotaCode);
        //如果为空说明数据错误
        if (quotaDataSave == null) {
            throw new Exception("QuotaDataSave data error");
        }
        JSONObject obj = new JSONObject().fromObject(quotaDataSave.getConfigJson());
        EsConfig esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
        return  esConfig;
    }
    public EsConfig getDataSourceEsConfig(String quotaCode) throws Exception {
        TjQuotaDataSource quotaDataSource= dataSourceService.findSourceByQuotaCode(quotaCode);
        if (quotaDataSource == null) {
            throw new Exception("quotaDataSource data error");
        }
        JSONObject obj = new JSONObject().fromObject(quotaDataSource.getConfigJson());
        EsConfig esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
        return  esConfig;
    }
    /**
     * 抽取数据统计值
     *
     * @param quotaVo
     * @return
     * @throws Exception
     */
    public List<SaveModel> extractData(QuotaVo quotaVo, String startTime, String endTime,String timeLevel,String saasid) throws Exception {
        try {
            TjQuotaDataSource quotaDataSource = dataSourceService.findSourceByQuotaCode(quotaVo.getCode());
            if (quotaDataSource == null) {
                throw new Exception("数据源配置错误");
            }
            JSONObject obj = new JSONObject().fromObject(quotaDataSource.getConfigJson());
            EsConfig esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
            //得到主维度
            List<TjQuotaDimensionMain> tjQuotaDimensionMains = dimensionMainService.findTjQuotaDimensionMainByQuotaCode(quotaDataSource.getQuotaCode());
            //当维度中有机构维度时,机构对应的区县会自动关联出来,所以区县不用在分组计算
            boolean orgFlag = false;
            TjQuotaDimensionMain townMain = null;
            for (int j = 0; j < tjQuotaDimensionMains.size(); j++) {
                TjQuotaDimensionMain one = tjQuotaDimensionMains.get(j);
                if ( one.getMainCode().equals("org")) {
                    orgFlag = true;
                }
                if ( one.getMainCode().equals("town")) {
                    townMain = one;
                }
            }
            if(esConfig.getEspecialType() != null){
                if(orgFlag && !esConfig.getEspecialType().equals("orgHealthCategory") ){
                    tjQuotaDimensionMains.remove(townMain);
                }
            }else {
                if(orgFlag){
                    tjQuotaDimensionMains.remove(townMain);
                }
            }
            //得到细维度
            List<TjQuotaDimensionSlave> tjQuotaDimensionSlaves = dimensionSlaveService.findTjQuotaDimensionSlaveByQuotaCode(quotaDataSource.getQuotaCode());
            if ( TjDataSource.type_es.equals(quotaDataSource.getCode()) ) {
                // 抽取 ES 统计值
                if( (!StringUtils.isEmpty(esConfig.getEspecialType())) && esConfig.getEspecialType().equals("orgHealthCategory")){
                    return esExtract.extractOrgHealthCategory(tjQuotaDimensionMains,tjQuotaDimensionSlaves,startTime,endTime,timeLevel,saasid, quotaVo,esConfig);
                }else{
                    return esExtract.extract(tjQuotaDimensionMains,tjQuotaDimensionSlaves,startTime,endTime,timeLevel,saasid, quotaVo,esConfig);
                }
            }else if( TjDataSource.type_solr.equals(quotaDataSource.getCode()) ){
                // 抽取 solr 统计值
//                return  solrExtract.extract(tjQuotaDimensionMains,tjQuotaDimensionSlaves,startTime,endTime,timeLevel, quotaVo,esConfig);
            }else if( TjDataSource.type_mysql.equals(quotaDataSource.getCode()) ){
                // 抽取 mysql 统计值
                return  SpringUtil.getBean(MysqlExtract.class).extract(tjQuotaDimensionMains,tjQuotaDimensionSlaves,startTime,endTime,timeLevel, quotaVo,esConfig);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("数据抽取错误," + e.getMessage() );
        }
    }
    // 该方法没有被用到,在 ExtractUtil 中有相同方法,推测可替代。  -- 张进军 2018.1.10
    /*private Map<String, SaveModel> setAllSlaveData(Map<String, SaveModel> allData, List<DictModel> dictData) {
        try {
            Map<String, SaveModel> returnAllData = new HashMap<>();
            for (Map.Entry<String, SaveModel> one : allData.entrySet()) {
                for (int i = 0; i < dictData.size(); i++) {
                    DictModel dictOne = dictData.get(i);
                    //设置新key
                    StringBuffer newKey = new StringBuffer(one.getKey() + "-" + dictOne.getCode());
                    //设置新的value
                    SaveModel saveModelTemp = new SaveModel();
                    BeanUtils.copyProperties(one.getValue(), saveModelTemp);
                    StringBuffer keyMethodName = new StringBuffer("setSlaveKey" + (i + 1));
                    StringBuffer nameMethodName = new StringBuffer("setSlaveKey" + (i + 1) + "Name");
                    SaveModel.class.getMethod(keyMethodName.toString(), String.class).invoke(saveModelTemp, dictOne.getCode());
                    SaveModel.class.getMethod(nameMethodName.toString(), String.class).invoke(saveModelTemp, dictOne.getName());
                    returnAllData.put(newKey.toString(), saveModelTemp);
                }
            }
            return returnAllData;
        } catch (Exception e) {
            e.getMessage();
        }
        return null;
    }*/
}

+ 279 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/ExtractPercentHelper.java

@ -0,0 +1,279 @@
package com.yihu.quota.etl.extract;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.quota.etl.extract.es.EsExtract;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.etl.util.ElasticsearchUtil;
import com.yihu.quota.etl.util.EsClientUtil;
import com.yihu.quota.model.jpa.TjQuota;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import com.yihu.quota.model.jpa.source.TjQuotaDataSource;
import com.yihu.quota.service.dimension.TjDimensionMainService;
import com.yihu.quota.service.dimension.TjDimensionSlaveService;
import com.yihu.quota.service.quota.QuotaService;
import com.yihu.quota.service.source.TjDataSourceService;
import com.yihu.quota.vo.DictModel;
import com.yihu.quota.vo.QuotaVo;
import com.yihu.quota.vo.SaveModel;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.text.DecimalFormat;
import java.util.*;
/**
 * Created by janseny on 2017/08/22.
 */
@Component
@Scope("prototype")
public class ExtractPercentHelper {
    @Autowired
    private TjDataSourceService dataSourceService;
    @Autowired
    private QuotaService quotaService;
    @Autowired
    private TjDimensionMainService dimensionMainService;
    @Autowired
    private TjDimensionSlaveService dimensionSlaveService;
    @Autowired
    private EsExtract esExtract;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    EsClientUtil esClientUtil;
    @Autowired
    ObjectMapper objectMapper;
    private Logger logger = LoggerFactory.getLogger(ExtractPercentHelper.class);
    /**
     * 公共的抽取数据
     *
     * @param quotaVo
     * @return
     * @throws Exception
     */
    public List<SaveModel> extractData(QuotaVo quotaVo, String startTime, String endTime,String timeLevel) throws Exception {
        String message = "";
        try {
            //得到该指标的数据来源
            TjQuotaDataSource quotaDataSource = dataSourceService.findSourceByQuotaCode(quotaVo.getCode());
            //如果为空说明数据错误
            if (quotaDataSource == null) {
                message = "数据源配置错误";
                throw new Exception(message);
            }
            JSONObject obj = new JSONObject().fromObject(quotaDataSource.getConfigJson());
            EsConfig esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
            if(StringUtils.isEmpty(esConfig.getThousandFlag())){
                if(StringUtils.isNotEmpty(esConfig.getMolecular()) &&  StringUtils.isNotEmpty(esConfig.getDenominator())){
                    Map<String,DictModel> dimensionMap = getQuotaDimension(quotaDataSource.getQuotaCode());
                    Map<String,DictModel> moleDimensionMap = getQuotaDimension(esConfig.getMolecular());
                    Map<String,DictModel> denoDimensionMap = getQuotaDimension(esConfig.getDenominator());
                    List<String> quotaDimension = new ArrayList<>();
                    String moleDimension = "";
                    String denoDimension = "";
                    int num = 0;
                    int count = 0;
                    for(String key : dimensionMap.keySet()){
                        for(String molekey : moleDimensionMap.keySet()){
                            if(key.equals(molekey) && dimensionMap.get(key).getCode().equals( moleDimensionMap.get(molekey).getCode() )){
                                moleDimension = moleDimension + moleDimensionMap.get(molekey).getName() + ";";
                                num ++;
                            }
                        }
                        for(String denokey : denoDimensionMap.keySet()){
                            if(key.equals(denokey) && dimensionMap.get(key).getCode().equals( denoDimensionMap.get(denokey).getCode() )){
                                denoDimension = denoDimension + denoDimensionMap.get(denokey).getName() + ";";
                                count ++;
                            }
                        }
                        quotaDimension.add(dimensionMap.get(key).getName());
                    }
                    if(num != dimensionMap.size()){
                        message = "指标维度无法与分子指标维度匹配";
                        throw new Exception(message);
                    }
                    if(count != dimensionMap.size()){
                        message = "指标维度无法与分母指标维度匹配";
                        throw new Exception(message);
                    }
                    TjQuota moleTjQuota = quotaService.findByCode(esConfig.getMolecular());
                    TjQuota denoTjQuota = quotaService.findByCode(esConfig.getDenominator());
                    Map<String,String> param =  new HashMap<>();
                    param.put("startTime",startTime);
                    param.put("endTime",endTime);
                    Map<String,Map<String, Object>>  moleResultMap = quotaService.getQuotaResult(moleTjQuota.getId(), objectMapper.writeValueAsString(param), moleDimension.substring(0, moleDimension.length() - 1));
                    Map<String,Map<String, Object>>  denoResultMap = quotaService.getQuotaResult(denoTjQuota.getId(), objectMapper.writeValueAsString(param), denoDimension.substring(0, denoDimension.length() - 1));
                    List<SaveModel>  resultModel = getPercentResult(moleResultMap, denoResultMap,quotaVo,esConfig);
                    return resultModel;
                }else{
                    message = "配置错误,分子或分母指标没有配置";
                    throw new Exception(message);
                }
            }else {
                // 每千每万人口 计算
                if(StringUtils.isNotEmpty(esConfig.getThousandDmolecular()) &&  StringUtils.isNotEmpty(esConfig.getThousandDenominator())){
                    Map<String,DictModel> dimensionMap = getQuotaDimension(quotaDataSource.getQuotaCode());
                    Map<String,DictModel> moleDimensionMap = getQuotaDimension(esConfig.getThousandDmolecular());
                    String moleDimension = "";
                    int num = 0;
                    for(String key : dimensionMap.keySet()){
                        for(String molekey : moleDimensionMap.keySet()){
                            if(key.equals(molekey)){
                                moleDimension = moleDimension + moleDimensionMap.get(molekey).getName() + ";";
                                num ++;
                            }
                        }
                    }
                    if(num != dimensionMap.size()){
                        message = "指标维度无法与分子指标维度匹配";
                        throw new Exception(message);
                    }
                    TjQuota moleTjQuota = quotaService.findByCode(esConfig.getThousandDmolecular());
                    TjQuota denoTjQuota = quotaService.findByCode(esConfig.getThousandDenominator());
                    Map<String,String> param =  new HashMap<>();
                    param.put("startTime",startTime);
                    param.put("endTime",endTime);
                    Map<String,Map<String, Object>>  moleResultMap = quotaService.getQuotaResult(moleTjQuota.getId(), objectMapper.writeValueAsString(param), moleDimension.substring(0, moleDimension.length() - 1));
                    int totalCount = 0;
                    Calendar calendar = Calendar.getInstance();
                    Map<String,Integer>  doneResultMap = quotaService.searcherSumByGroupBySql(denoTjQuota, "year", "year=" + calendar.get(Calendar.YEAR),"result","","");
                    if(doneResultMap != null && doneResultMap.size()>0){
                        for(String key :doneResultMap.keySet())
                        totalCount = totalCount + doneResultMap.get(key);
                    }
                    List<SaveModel>  resultModel = new ArrayList<>();
                    if(moleResultMap != null && moleResultMap.size() > 0 && totalCount > 0){
                        resultModel = getThousandPercentResult(moleResultMap,totalCount, quotaVo,esConfig.getThousandFlag());
                    }
                    return resultModel;
                }else{
                    message = "配置错误,分子或分母指标没有配置";
                    throw new Exception(message);
                }
            }
        } catch (Exception e) {
            message = "数据抽取错误";
            throw new Exception(message);
        }
    }
    //获取指标维度
    public Map<String,DictModel> getQuotaDimension(String quotaCode){
        // 指标 主维度
        List<TjQuotaDimensionMain> dimensionMains = dimensionMainService.findTjQuotaDimensionMainByQuotaCode(quotaCode);
        // 指标 细维度
        List<TjQuotaDimensionSlave> dimensionSlaves = dimensionSlaveService.findTjQuotaDimensionSlaveByQuotaCode(quotaCode);
        Map<String,DictModel> map = new HashMap<>();
        String mainKey = "";
        String mainVal = "";
        for(int i = 0 ;i < dimensionMains.size() ; i++){
            mainKey =  dimensionMains.get(i).getMainCode();
            mainVal =  dimensionMains.get(i).getMainCode() + " - " + dimensionMains.get(i).getDictSql();
            DictModel dictModel = new DictModel();
            dictModel.setName(mainKey);
            dictModel.setCode(mainVal);
            map.put(mainKey,dictModel);
        }
        String slaveKey = "";
        String slaveVal = "";
        String slaveName = "";
        for(int i = 0 ;i< dimensionSlaves.size(); i++){
            slaveName = slaveName + "slaveKey" + (i+1);
            slaveKey =  dimensionSlaves.get(i).getSlaveCode();
            slaveVal =  dimensionSlaves.get(i).getSlaveCode() + " - " + dimensionSlaves.get(i).getDictSql() ;
            DictModel dictModel = new DictModel();
            dictModel.setName(slaveName);
            dictModel.setCode(slaveVal);
            map.put(slaveKey,dictModel);
        }
        return map;
    }
    public List<SaveModel> getPercentResult(Map<String,Map<String, Object>> moleReultMap,Map<String,Map<String, Object>> denoReultMap,QuotaVo quotaVo,EsConfig esConfig){
        List<SaveModel> saveModelList = new ArrayList<>();
        for(String dekey :denoReultMap.keySet()){
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> denoMap = denoReultMap.get(dekey);
            if(denoMap.get("result").toString().equals("0")){
                map = denoMap;
            }else {
                for(String mokey :moleReultMap.keySet()){
                    Map<String, Object> moleMap = moleReultMap.get(mokey);
                    if(dekey.equals(mokey)) {
                        if(moleMap.get("result").toString().equals("0")){
                            map = moleMap;
                       }else{
                           int point = 0;
                           float moleVal = Float.valueOf(moleMap.get("result").toString());
                           float denoVal = Float.valueOf(denoMap.get("result").toString());
                            int percentOperationValue = 100;
                            if(StringUtils.isNotEmpty(esConfig.getPercentOperationValue())){
                                percentOperationValue = Integer.valueOf(esConfig.getPercentOperationValue());
                            }
                            if(esConfig.getPercentOperation().equals(1)){
                                point = (int)(moleVal/denoVal)*percentOperationValue;
                            }else if(esConfig.getPercentOperation().equals(2)){
                                point = (int)(moleVal/denoVal)/percentOperationValue;
                            }
                           moleMap.remove("result");
                           moleMap.put("result",point);
                           map = moleMap;
                       }
                        break;
                    }
                }
            }
            SaveModel saveModel =  objectMapper.convertValue(map, SaveModel.class);
            saveModel.setQuotaName(quotaVo.getName());
            saveModel.setQuotaCode(quotaVo.getCode());
            saveModelList.add(saveModel);
        }
        return saveModelList;
    }
    public List<SaveModel> getThousandPercentResult(Map<String,Map<String, Object>> moleReultMap,int totalCount,QuotaVo quotaVo,String thousandFlag){
        List<SaveModel> saveModelList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for(String mokey :moleReultMap.keySet()){
            Map<String, Object> moleMap = moleReultMap.get(mokey);
            if(moleMap.get("result").toString().equals("0")){
                map = moleMap;
                moleMap.put("result","0");
            }else{
                String point = "0";
                float moleVal = Float.valueOf(moleMap.get("result").toString());
                DecimalFormat   df = new   DecimalFormat("#.##");
                point = df.format( (moleVal / totalCount) * Integer.valueOf(thousandFlag));
                moleMap.put("result",point);
                map = moleMap;
            }
            SaveModel saveModel =  objectMapper.convertValue(map, SaveModel.class);
            saveModel.setQuotaName(quotaVo.getName());
            saveModel.setQuotaCode(quotaVo.getCode());
            saveModelList.add(saveModel);
        }
        return  saveModelList;
    }
}

+ 723 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/ExtractUtil.java

@ -0,0 +1,723 @@
package com.yihu.quota.etl.extract;
import com.yihu.jw.restmodel.ehr.org.MOrganization;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import com.yihu.quota.util.BasesicUtil;
import com.yihu.quota.vo.DictModel;
import com.yihu.quota.vo.OrgHealthCategoryShowModel;
import com.yihu.quota.vo.QuotaVo;
import com.yihu.quota.vo.SaveModel;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.*;
/**
 * Created by janseny on 2017/7/10.
 */
@Component
@Scope("prototype")
public class ExtractUtil {
    private Logger logger = LoggerFactory.getLogger(ExtractUtil.class);
    private static String main_town = "twon";
    private static String main_org = "org";
    private static String main_dept = "dept";
    private static String main_year = "year";
    private static String slave_sex = "sex";
    private static String slave_age = "age";
    private static  String unknown = "未知";
    private static String create_date = "create_date";
    @Autowired
    private JdbcTemplate jdbcTemplate;
/*    @Autowired
    SolrUtil solrUtil;
    @Autowired
    SolrQuery solrQuery;*/
    private QuotaVo quotaVo;
    private String timeLevel;
    /**
     * 抽取列表数据 关联数据字典
     * @param qdm
     * @param qds
     * @param dataList
     * @param timeKey  时间维度字段
     * @param aggregationKey 抽取统计的数据值字段
     * @param quotaVo
     * @return
     * @throws Exception
     */
    public  List<SaveModel> computeList(List<TjQuotaDimensionMain> qdm, List<TjQuotaDimensionSlave> qds,List<Map<String, Object>> dataList,
                                        String timeKey,String aggregationKey,QuotaVo quotaVo) throws Exception {
        this.quotaVo = quotaVo;
        List<SaveModel> returnList = new ArrayList<>();
        List<SaveModel> totalSaveModelDictList = getTotalDictDataList(qdm,qds);
        Map<String,String> townDictMap = new HashMap<>();
        Map<String,String> orgDictMap = new HashMap<>();
        Map<String,String> deptDictMap = new HashMap<>();
        Map<String,String> yearDictMap = new HashMap<>();
        Map<String,String> slave1DictMap = new HashMap<>();
        Map<String,String> slave2DictMap = new HashMap<>();
        Map<String,String> slave3DictMap = new HashMap<>();
        Map<String,String> slave4DictMap = new HashMap<>();
        for(SaveModel saveModel: totalSaveModelDictList){
            if(saveModel.getTown() != null){
                townDictMap.put(saveModel.getTown(), saveModel.getTownName());
            }
            if(saveModel.getOrg() != null){
                orgDictMap.put(saveModel.getOrg(), saveModel.getOrgName());
            }
            if(saveModel.getDept() != null){
                deptDictMap.put(saveModel.getDept(), saveModel.getDeptName());
            }
            if(saveModel.getYear() != null){
                yearDictMap.put(saveModel.getYear(), saveModel.getYearName());
            }
            if(saveModel.getSlaveKey1() != null){
                slave1DictMap.put(saveModel.getSlaveKey1(), saveModel.getSlaveKey1Name());
            }
            if(saveModel.getSlaveKey2() != null){
                slave2DictMap.put(saveModel.getSlaveKey2(), saveModel.getSlaveKey2Name());
            }
            if(saveModel.getSlaveKey3() != null){
                slave3DictMap.put(saveModel.getSlaveKey3(), saveModel.getSlaveKey3Name());
            }
            if(saveModel.getSlaveKey4() != null){
                slave4DictMap.put(saveModel.getSlaveKey4(), saveModel.getSlaveKey4Name());
            }
        }
        int errorCount = 0;
        for(Map<String, Object> map : dataList){
            SaveModel saveModel = new SaveModel();
            // 去重查询场合
            Object distinctField = map.get("distinctField");
            Object distinctFieldValue = map.get("distinctFieldValue");
            if (distinctField != null) {
                saveModel.setDistinctField(distinctField.toString());
                saveModel.setDistinctFieldValue(distinctFieldValue.toString());
            }
            for (TjQuotaDimensionMain main : qdm) {
                String keyVal = main.getKeyVal().contains(".")?main.getKeyVal().substring(main.getKeyVal().indexOf(".")+1):main.getKeyVal();//如mysql 多表拼接时 d.org_code
                if(map.get(keyVal.trim()) != null ){
                    String value = map.get(keyVal.trim()).toString();
                    if(main.getMainCode().equals(main_town) && !StringUtils.isEmpty(townDictMap.get(value))){
                        saveModel.setTown(value);
                        saveModel.setTownName(townDictMap.get(value));
                    }else if(main.getMainCode().equals(main_org) && !StringUtils.isEmpty(orgDictMap.get(value))){
                        saveModel.setOrg(value);
                        saveModel.setOrgName(orgDictMap.get(value));
                    }else if(main.getMainCode().equals(main_year) && !StringUtils.isEmpty(yearDictMap.get(value))){
                        saveModel.setYearName(yearDictMap.get(value));
                        saveModel.setYear(value);
                    }else if(main.getMainCode().equals(main_dept)){
                        if(value.length() > 2){
                            value = value.substring(0,2);
                        }
                        if( !StringUtils.isEmpty(deptDictMap.get(value))){
                            saveModel.setDeptName(deptDictMap.get(value));
                            saveModel.setDept(value);
                        }
                    }
                }
            }
            if(saveModel.getTown() != null || saveModel.getOrg() !=null){
                for (int i = 0; i < qds.size(); i++) {
                    int num = i+1 ;
                    if(num == 1) {
                        if(map.get(qds.get(i).getKeyVal().trim()) != null){
                            String value = map.get(qds.get(i).getKeyVal().trim()).toString();
                            if( !StringUtils.isEmpty(slave1DictMap.get(value))){
                                saveModel.setSlaveKey1(value);
                                saveModel.setSlaveKey1Name(slave1DictMap.get(value));
                            }
                        }
                    }else if(num == 2) {
                        if(map.get(qds.get(i).getKeyVal().trim()) != null){
                            String value = map.get(qds.get(i).getKeyVal().trim()).toString();
                            if( !StringUtils.isEmpty(slave2DictMap.get(value))){
                                saveModel.setSlaveKey2(value);
                                saveModel.setSlaveKey2Name(slave2DictMap.get(value));
                            }
                        }
                    }else if(num == 3) {
                        if(map.get(qds.get(i).getKeyVal().trim()) != null){
                            String value = map.get(qds.get(i).getKeyVal().trim()).toString();
                            if( !StringUtils.isEmpty(slave3DictMap.get(value))){
                                saveModel.setSlaveKey3(value);
                                saveModel.setSlaveKey3Name(slave3DictMap.get(value));
                            }
                        }
                    }else if(num == 4 ) {
                        if(map.get(qds.get(i).getKeyVal().trim()) != null){
                            String value = map.get(qds.get(i).getKeyVal().trim()).toString();
                            if( !StringUtils.isEmpty(slave4DictMap.get(value))){
                                saveModel.setSlaveKey4(value);
                                saveModel.setSlaveKey4Name(slave4DictMap.get(value));
                            }
                        }
                    }
                }
                if(!StringUtils.isEmpty(timeKey)){
                    if(!StringUtils.isEmpty( map.get(timeKey) ) ){
                        String date = "";
                        if(map.get(timeKey) instanceof String){
                            date = map.get(timeKey).toString().substring(0,10);
                        }else if(map.get(timeKey) instanceof Date){
                            date = DateUtil.formatDate((Date)map.get(timeKey), DateUtil.DEFAULT_DATE_YMD_FORMAT);
                        }
                        saveModel.setQuotaDate(date);
                    }
//                    if(!StringUtils.isEmpty( map.get("quotaDate") ) ){
//                        String date = "";
//                        if(map.get("quotaDate") instanceof String){
//                            date = map.get("quotaDate").toString();
//                        }else if(map.get("quotaDate") instanceof Date){
//                            date = DateUtil.formatDate((Date)map.get("quotaDate"),DateUtil.DEFAULT_DATE_YMD_FORMAT);
//                        }
//                        saveModel.setQuotaDate(date);
//                    }
                    if(!StringUtils.isEmpty( map.get("event_date") )){
                        String date = "";
                        if(map.get("event_date") instanceof String){
                            date = map.get("event_date").toString().substring(0,10);
                        }else if(map.get("event_date") instanceof Date){
                            date = DateUtil.formatDate((Date)map.get("event_date"),DateUtil.DEFAULT_DATE_YMD_FORMAT);
                        }
                        saveModel.setQuotaDate(date);
                    }
                    if(!StringUtils.isEmpty( map.get("eventDate") )){
                        String date = "";
                        if(map.get("eventDate") instanceof String){
                            date = map.get("eventDate").toString().substring(0,10);
                        }else if(map.get("eventDate") instanceof Date){
                            date = DateUtil.formatDate((Date)map.get("event_date"),DateUtil.DEFAULT_DATE_YMD_FORMAT);
                        }
                        saveModel.setQuotaDate(date);
                    }
                    if(!StringUtils.isEmpty(create_date)) {
                            if (map.get(create_date) instanceof Date) {
                                Date createDate = (Date)map.get(create_date);
                                Date createDateVal = DateUtils.addHours(createDate, -8);
                                saveModel.setCreateDate(createDateVal);
                            }
                    }
                }
                if(!StringUtils.isEmpty(aggregationKey)){
                    if(map.get(aggregationKey) != null){
                        saveModel.setResult(map.get(aggregationKey).toString());
                    }
                }else {
                    saveModel.setResult("1");
                }
                saveModel.setQuotaCode(quotaVo.getCode().replaceAll("_",""));
                saveModel.setQuotaName(quotaVo.getName());
                returnList.add(saveModel);
            }else {
                errorCount++;
            }
        }
        //关联机构相关信息
        if(orgDictMap != null && orgDictMap.size() > 0){
            setSaveModelProperties(returnList);
        }
        logger.info("指标:" + quotaVo.getName() + "统计时指标或者机构未关联上错误数据有:" + errorCount);
        return returnList;
    }
    /**
     * 获取所有维度字典
     * @param qdm
     * @param qds
     * @return
     */
    public List<SaveModel> getTotalDictDataList(List<TjQuotaDimensionMain> qdm, List<TjQuotaDimensionSlave> qds){
        List<SaveModel> totalSaveModelDictList = new ArrayList<>();
        for (TjQuotaDimensionMain main : qdm) {
            List<SaveModel> saveModelDicts = jdbcTemplate.query(main.getDictSql(), new BeanPropertyRowMapper(SaveModel.class));
            if (saveModelDicts != null) {
                for(SaveModel saveModel :saveModelDicts){
                    totalSaveModelDictList.add(saveModel);
                }
            }
        }
        for (int i = 0; i < qds.size(); i++) {
            int num = i+1;
            if(qds.get(i).getDictSql() != null){
                List<DictModel> dictModels = jdbcTemplate.query(qds.get(i).getDictSql(), new BeanPropertyRowMapper(DictModel.class));
                if (dictModels != null) {
                    for(DictModel dictModel :dictModels){
                        SaveModel saveModel = new SaveModel();
                        if(num == 1){
                            saveModel.setSlaveKey1(dictModel.getCode());
                            saveModel.setSlaveKey1Name(dictModel.getName());
                        }else  if(num == 2){
                            saveModel.setSlaveKey2(dictModel.getCode());
                            saveModel.setSlaveKey2Name(dictModel.getName());
                        }else  if(num == 3){
                            saveModel.setSlaveKey3(dictModel.getCode());
                            saveModel.setSlaveKey3Name(dictModel.getName());
                        }else  if(num == 4){
                            saveModel.setSlaveKey4(dictModel.getCode());
                            saveModel.setSlaveKey4Name(dictModel.getName());
                        }
                        totalSaveModelDictList.add(saveModel);
                    }
                }
            }
        }
        return totalSaveModelDictList;
    }
    /**
     * 融合主细维度、其组合统计值为SaveModel
     *
     * @param qdm                 主维度集合
     * @param qds                 细维度集合
     * @param returnList          转换后的 SaveModel 集合
     * @param statisticsResultMap 统计结果集
     * @param daySlaveDictMap     按天统计的所有日期项
     * @param quotaVo             指标配置
     */
    public void compute(List<TjQuotaDimensionMain> qdm,
                        List<TjQuotaDimensionSlave> qds,
                        List<SaveModel> returnList,
                        Map<String, String> statisticsResultMap,
                        Map<String, String> daySlaveDictMap,
                        QuotaVo quotaVo) throws Exception {
        if (statisticsResultMap == null || statisticsResultMap.size() == 0) {
            logger.warn("没有查询到数据");
            return;
        }
        this.quotaVo = quotaVo;
        // 将主细维度的字典项转换成 SaveModel
        Map<String, SaveModel> allData = new HashMap<>();
        if (qdm.size() == 1) {
            allData = initDimension(qds, qdm.get(0), allData, daySlaveDictMap);
        } else {
            allData = initDimensionMoreMain(qds, qdm, allData, daySlaveDictMap);
        }
        // 设置维度组合的统计值
        for (Map.Entry<String, String> entry : statisticsResultMap.entrySet()) {
            String key = entry.getKey();
            SaveModel saveModel = allData.get(key);
            if (saveModel != null) {
                saveModel.setResult(statisticsResultMap.get(key));
                saveModel.setQuotaDate(daySlaveDictMap.get(key));
                returnList.add(saveModel);
            }
        }
        List<String> dimins = new ArrayList<>();
        for (TjQuotaDimensionSlave slave : qds) {
            if (slave.getId() != null) {
                dimins.add(slave.getSlaveCode());
            }
        }
        for (TjQuotaDimensionMain main : qdm) {
            dimins.add(main.getMainCode());
        }
        dimins.add("quotaDate");
        BasesicUtil baseUtil = new BasesicUtil();
        Map<String, String> diminMap = new HashMap<>();
        for (SaveModel saveModel : returnList) {
            String diminStr = "";
            for (String key : dimins) {
                diminStr += baseUtil.getFieldValueByName(key, saveModel);
            }
            diminMap.put(diminStr, diminStr);
        }
    }
    /**
     * 将主细维度的字典项转换成 SaveModel(一个主维度场合)
     */
    private Map<String, SaveModel> initDimension(List<TjQuotaDimensionSlave> dimensionSlaves,
                                                 TjQuotaDimensionMain dimensionMain,
                                                 Map<String, SaveModel> allData,
                                                 Map<String, String> daySlaveDictMap) throws Exception {
        try {
            if (dimensionMain != null && !StringUtils.isEmpty(dimensionMain.getDictSql())) {
                //查询字典数据
                List<SaveModel> dictData = jdbcTemplate.query(dimensionMain.getDictSql(), new BeanPropertyRowMapper(SaveModel.class));
                if (dictData == null) {
                    throw new Exception("主纬度配置有误");
                } else {
                    if (dimensionMain.getMainCode().equals("org")) {//机构关联出区县
                        setSaveModelProperties(dictData);
                    }
                    //设置到map里面
                    setAllData(allData, dictData, dimensionMain.getType());
                }
            }
            for (int i = 0; i < dimensionSlaves.size(); i++) {
                List<DictModel> dictDataSlave = new ArrayList<>();
                if (dimensionSlaves.get(i).getId() != null) {
                    dictDataSlave = jdbcTemplate.query(dimensionSlaves.get(i).getDictSql(), new BeanPropertyRowMapper(DictModel.class));
                } else { // 在solr、mysql抽取中默认追加的按天统计的维度
                    DictModel dict;
                    for (Map.Entry<String, String> item : daySlaveDictMap.entrySet()) {
                        dict = new DictModel();
                        dict.setName(item.getValue());
                        dict.setCode(item.getValue());
                        dictDataSlave.add(dict);
                    }
                }
                allData = setAllSlaveData(allData, dictDataSlave, i);
            }
        } catch (Exception e) {
            throw new Exception("纬度配置有误");
        }
        return allData;
    }
    /**
     * 将主细维度的字典项转换成 SaveModel(多个个主维度场合)
     */
    private Map<String, SaveModel> initDimensionMoreMain(List<TjQuotaDimensionSlave> dimensionSlaves,
                                                         List<TjQuotaDimensionMain> dimensionMains,
                                                         Map<String, SaveModel> allData,
                                                         Map<String, String> daySlaveDictMap) throws Exception {
        try {
            if (dimensionMains != null) {
                //查询字典数据
                List<SaveModel> dictData = jdbcTemplate.query(dimensionMains.get(0).getDictSql(), new BeanPropertyRowMapper(SaveModel.class));
                if (dictData == null) {
                    throw new Exception("主纬度配置有误");
                } else {
                    if (dimensionMains.get(0).getMainCode().equals("org")) {//机构关联出区县
                        setSaveModelProperties(dictData);
                    }
                    //设置到map里面
                    setAllData(allData, dictData, dimensionMains.get(0).getType());
                }
            }
            for (int i = 0; i < dimensionMains.size(); i++) {
                if (i != 0) {
                    List<SaveModel> saveDataMain = jdbcTemplate.query(dimensionMains.get(i).getDictSql(), new BeanPropertyRowMapper(SaveModel.class));
                    if (dimensionMains.get(i).getMainCode().equals("org")) {//机构关联出区县
                        setSaveModelProperties(saveDataMain);
                    }
                    allData = setOtherMainData(allData, saveDataMain, dimensionMains.get(i).getMainCode(), dimensionMains.get(i).getType());
                }
            }
            for (int i = 0; i < dimensionSlaves.size(); i++) {
                List<DictModel> dictDataSlave = new ArrayList<>();
                if (dimensionSlaves.get(i).getId() != null) {
                    dictDataSlave = jdbcTemplate.query(dimensionSlaves.get(i).getDictSql(), new BeanPropertyRowMapper(DictModel.class));
                } else { // 在solr、mysql抽取中默认追加的按天统计的维度
                    DictModel dict;
                    for (Map.Entry<String, String> item : daySlaveDictMap.entrySet()) {
                        dict = new DictModel();
                        dict.setName(item.getValue());
                        dict.setCode(item.getValue());
                        dictDataSlave.add(dict);
                    }
                }
                allData = setAllSlaveData(allData, dictDataSlave, i);
            }
        } catch (Exception e) {
            throw new Exception("纬度配置有误");
        }
        return allData;
    }
    //如果选择多个维度,除了第一个维度外其他维度组合
    private Map<String, SaveModel> setOtherMainData(Map<String, SaveModel> allData,
                                                    List<SaveModel> saveDataMain,
                                                    String code,
                                                    String dimensionType) {
        Map<String, SaveModel> returnAllData = new HashMap<>();
        try {
            for (Map.Entry<String, SaveModel> one : allData.entrySet()) {
                for (int i = 0; i < saveDataMain.size(); i++) {
                    SaveModel mainOne = saveDataMain.get(i);
                    //设置新key
                    String codeVal = getMainCode(mainOne, dimensionType, "code");
                    String nameVal = getMainCode(mainOne, dimensionType, "name");
                    StringBuffer newKey = new StringBuffer(one.getKey() + "-" + codeVal);
                    //设置新的value
                    SaveModel saveModelTemp = new SaveModel();
                    BeanUtils.copyProperties(one.getValue(), saveModelTemp);
                    if (!StringUtils.isEmpty(mainOne.getTown())) {
                        saveModelTemp.setTown(mainOne.getTown());
                        saveModelTemp.setTownName(mainOne.getTownName());
                    }
                    if (!StringUtils.isEmpty(mainOne.getEconomic())) {
                        saveModelTemp.setEconomic(mainOne.getEconomic());
                        saveModelTemp.setEconomicName(mainOne.getEconomicName());
                    }
                    if (!StringUtils.isEmpty(mainOne.getLevel())) {
                        saveModelTemp.setLevel(mainOne.getLevel());
                        saveModelTemp.setLevelName(mainOne.getLevelName());
                    }
                    if (!StringUtils.isEmpty(mainOne.getOrgHealthCategoryId())) {
                        saveModelTemp.setOrgHealthCategoryId(mainOne.getOrgHealthCategoryId());
                    }
                    if (!StringUtils.isEmpty(mainOne.getOrgHealthCategoryCode())) {
                        saveModelTemp.setOrgHealthCategoryCode(mainOne.getOrgHealthCategoryCode());
                    }
                    if (!StringUtils.isEmpty(mainOne.getOrgHealthCategoryName())) {
                        saveModelTemp.setOrgHealthCategoryName(mainOne.getOrgHealthCategoryName());
                    }
                    if (!StringUtils.isEmpty(mainOne.getOrgHealthCategoryPid())) {
                        saveModelTemp.setOrgHealthCategoryPid(mainOne.getOrgHealthCategoryPid());
                    }
                    if (!StringUtils.isEmpty(mainOne.getOrgHealthCategoryTopPid())) {
                        saveModelTemp.setOrgHealthCategoryTopPid(mainOne.getOrgHealthCategoryTopPid());
                    }
                    code = code.substring(0, 1).toUpperCase() + code.substring(1);
                    StringBuffer keyMethodName = new StringBuffer("set" + code);
                    StringBuffer nameMethodName = new StringBuffer("set" + code + "Name");
                    SaveModel.class.getMethod(keyMethodName.toString(), String.class).invoke(saveModelTemp, codeVal);
                    SaveModel.class.getMethod(nameMethodName.toString(), String.class).invoke(saveModelTemp, nameVal);
                    returnAllData.put(newKey.toString(), saveModelTemp);
                }
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return returnAllData;
    }
    private Map<String, SaveModel> setAllSlaveData(Map<String, SaveModel> allData, List<DictModel> dictData, Integer key) {
        Map<String, SaveModel> returnAllData = new HashMap<>();
        String keyMethod = "setSlaveKey" + (key + 1);
        String nameMethod = keyMethod + "Name";
        try {
            for (Map.Entry<String, SaveModel> one : allData.entrySet()) {
                DictModel dictOne = null;
                for (int i = 0; i < dictData.size(); i++) {
                    dictOne = dictData.get(i);
                    //设置新key
                    String newKey = one.getKey() + "-" + dictOne.getCode();
                    //设置新的value
                    SaveModel saveModelTemp = new SaveModel();
                    BeanUtils.copyProperties(one.getValue(), saveModelTemp);
                    SaveModel.class.getMethod(keyMethod, String.class).invoke(saveModelTemp, dictOne.getCode());
                    SaveModel.class.getMethod(nameMethod, String.class).invoke(saveModelTemp, dictOne.getName());
                    returnAllData.put(newKey.toString(), saveModelTemp);
                }
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return returnAllData;
    }
    /**
     * @param allData
     * @param dictData
     * @param dictType
     */
    private void setAllData(Map<String, SaveModel> allData, List<SaveModel> dictData, String dictType) {
        switch (dictType) {
            case Contant.main_dimension.area_province: {
                //设置省的全部的值
                dictData.stream().forEach(one -> {
                    setOneData(allData, one.getProvince(), one, Contant.main_dimension_areaLevel.area_province);
                });
                break;
            }
            case Contant.main_dimension.area_city: {
                //设置市的全部的值
                dictData.stream().forEach(one -> {
                    setOneData(allData, one.getCity(), one, Contant.main_dimension_areaLevel.area_city);
                });
                break;
            }
            case Contant.main_dimension.area_town: {
                //设置区的全部的值
                dictData.stream().forEach(one -> {
                    setOneData(allData, one.getTown(), one, Contant.main_dimension_areaLevel.area_town);
                });
                break;
            }
            case Contant.main_dimension.area_org: {
                //设置机构
                dictData.stream().forEach(one -> {
                    setOneData(allData, one.getOrg(), one, Contant.main_dimension_areaLevel.area_org);
                });
                break;
            }
            case Contant.main_dimension.area_dept: {
                //设置科室
                dictData.stream().forEach(one -> {
                    setOneData(allData, one.getDept(), one, Contant.main_dimension_areaLevel.area_dept);
                });
                break;
            }
            case Contant.main_dimension.time_year: {
                //设置年份
                dictData.stream().forEach(one -> {
                    this.timeLevel = Contant.main_dimension_timeLevel.year;
                    setOneData(allData, one.getYear(), one, null);
                });
                break;
            }
        }
    }
    private String getMainCode(SaveModel mainOne, String dimensionType, String returnType) {
        String code = "";
        String name = "";
        switch (dimensionType) {
            case Contant.main_dimension.area_province: {
                code = mainOne.getProvince();
                name = mainOne.getProvinceName();
                break;
            }
            case Contant.main_dimension.area_city: {
                code = mainOne.getCity();
                name = mainOne.getCityName();
                break;
            }
            case Contant.main_dimension.area_town: {
                code = mainOne.getTown();
                name = mainOne.getTownName();
                break;
            }
            case Contant.main_dimension.area_org: {
                code = mainOne.getOrg();
                name = mainOne.getOrgName();
                break;
            }
            case Contant.main_dimension.area_dept: {
                code = mainOne.getDept();
                name = mainOne.getDeptName();
                break;
            }
            case Contant.main_dimension.time_year: {
                code = mainOne.getYear();
                name = mainOne.getYearName();
                break;
            }
        }
        if (returnType.equals("code")) {
            return code;
        }
        if (returnType.equals("name")) {
            return name;
        }
        return "";
    }
    private void setOneData(Map<String, SaveModel> allData, String key, SaveModel one, String areaLevel) {
        one.setAreaLevel(areaLevel);
        one.setResult("0");
        one.setCreateTime(new Date());
        one.setQuotaCode(quotaVo.getCode());
        one.setQuotaName(quotaVo.getName());
        one.setTimeLevel(timeLevel);
        one.setSaasId(null);
        allData.put(key, one);
    }
    private void setSaveModelProperties(List<SaveModel> saveDataMain) {
        //上饶区县
        String townSql = "SELECT id as code,name as name  from address_dict where pid = '361100'";
        List<DictModel> townDictDatas = jdbcTemplate.query(townSql, new BeanPropertyRowMapper(DictModel.class));
        Map<String,String> townMap = new HashMap<>();
        for(DictModel dictModel : townDictDatas){
            townMap.put(dictModel.getCode(), dictModel.getName());
        }
        //机构类型 目录对应的名称和节点id
        String orgHealthCategorySql = "SELECT id as orgHealthCategoryId,pid as orgHealthCategoryPid,top_pid as orgHealthCategoryTopPid,code as orgHealthCategoryCode, name as orgHealthCategoryName from org_health_category";
        List<OrgHealthCategoryShowModel> orgHealthCategoryDictDatas = jdbcTemplate.query(orgHealthCategorySql, new BeanPropertyRowMapper(OrgHealthCategoryShowModel.class));
        Map<String,OrgHealthCategoryShowModel>  orgHealthCategoryMap = new HashMap<>();
        for(OrgHealthCategoryShowModel orgHealthCategory : orgHealthCategoryDictDatas){
            orgHealthCategoryMap.put(orgHealthCategory.getOrgHealthCategoryCode(), orgHealthCategory);
        }
        //经济类型
        String economicSql = "SELECT code, catalog from system_dict_entries WHERE dict_id = 102 ";
        Map<String, Object> economicMap = new HashMap<>();
        List<Map<String, Object>> list = jdbcTemplate.queryForList(economicSql);
        if (null != list && list.size() > 0) {
            for (Map<String, Object> map : list) {
                economicMap.put(map.get("code") + "", map.get("catalog") + "");
            }
        }
        for (SaveModel model : saveDataMain) {
            String dictSql = "SELECT org_code as orgCode,hos_type_id as hosTypeId,administrative_division as administrativeDivision, hos_economic as hosEconomic, level_id as levelId  from organizations where org_code=";
            dictSql += "'" + model.getOrg() + "'";
            List<MOrganization> organizations = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(MOrganization.class));
            if (organizations != null && organizations.size() > 0) {
                MOrganization organization = organizations.get(0);
                if (!StringUtils.isEmpty(organization.getAdministrativeDivision())) {
                    String orgCode = organization.getAdministrativeDivision().toString();
                    if(townMap.get(orgCode) != null ){
                        model.setTown(orgCode);
                        model.setTownName(townMap.get(orgCode));
                    }
                }
                //关联出对应的机构类型
                if (!StringUtils.isEmpty(organization.getHosTypeId())) {
                    if(orgHealthCategoryMap.get(organization.getHosTypeId()) != null ){
                        OrgHealthCategoryShowModel orgHealthCategory = orgHealthCategoryMap.get(organization.getHosTypeId());
                        model.setOrgHealthCategoryCode(organization.getHosTypeId());
                        model.setOrgHealthCategoryName(orgHealthCategory.getOrgHealthCategoryName());
                        model.setOrgHealthCategoryId(orgHealthCategory.getOrgHealthCategoryId());
                        model.setOrgHealthCategoryPid(orgHealthCategory.getOrgHealthCategoryPid());
                        model.setOrgHealthCategoryTopPid(orgHealthCategory.getOrgHealthCategoryTopPid());
                    }
                }
                if (!StringUtils.isEmpty(organization.getHosEconomic())) {
                    String name = economicMap.get(organizations.get(0).getHosEconomic()) + "";
                    if ("公立".equals(name)) {
                        model.setEconomic("1021");
                        model.setEconomicName("公立");
                    } else {
                        model.setEconomic("1022");
                        model.setEconomicName("非公立");
                    }
                }
                if (!StringUtils.isEmpty(organization.getLevelId())) {
                    String levelId = organization.getLevelId();
                    if ("1".equals(levelId)) {
                        model.setLevel(levelId);
                        model.setLevelName("一级");
                    } else if ("2".equals(levelId)) {
                        model.setLevel(levelId);
                        model.setLevelName("二级");
                    } else if ("3".equals(levelId)) {
                        model.setLevel(levelId);
                        model.setLevelName("三级");
                    } else {
                        model.setLevel(levelId);
                        model.setLevelName("未定级");
                    }
                }
            }
        }
    }
}

+ 451 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/es/EsExtract.java

@ -0,0 +1,451 @@
package com.yihu.quota.etl.extract.es;
import com.yihu.jw.restmodel.ehr.org.MOrganization;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.etl.extract.ExtractUtil;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.etl.util.ElasticsearchUtil;
import com.yihu.quota.etl.util.EsClientUtil;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import com.yihu.quota.service.orgHealthCategory.OrgHealthCategoryStatisticsService;
import com.yihu.quota.service.quota.BaseStatistsService;
import com.yihu.quota.vo.QuotaVo;
import com.yihu.quota.vo.SaveModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.text.NumberFormat;
import java.util.*;
/**
 * Created by chenweida on 2017/6/6.
 */
@Component
@Scope("prototype")
public class EsExtract {
    private Logger logger = LoggerFactory.getLogger(EsExtract.class);
    @Autowired
    private EsClientUtil esClientUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ExtractUtil extractUtil;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private BaseStatistsService baseStatistsService;
    @Autowired
    private OrgHealthCategoryStatisticsService orgHealthCategoryStatisticsService;
    private String startTime;
    private String endTime;
    private String timeLevel;
    private String saasid;
    private QuotaVo quotaVo;
    private EsConfig esConfig;
    private static String orgHealthCategory = "orgHealthCategory";
    public List<SaveModel> extract(List<TjQuotaDimensionMain> qdm,//主维度
                                   List<TjQuotaDimensionSlave> qds,//细维度
                                   String startTime,//开始时间
                                   String endTime, //结束时间
                                   String timeLevel, //时间维度  1日,2 周, 3 月,4 年
                                   String saasid,//saasid
                                   QuotaVo quotaVo,//指标code
                                   EsConfig esConfig //es配置
    ) throws Exception {
        this.startTime = startTime;
        this.endTime = endTime;
        this.timeLevel = timeLevel;
        this.saasid = saasid;
        this.quotaVo = quotaVo;
        this.esConfig = esConfig;
        initParams(this.startTime ,this.endTime);
        List<SaveModel> saveModels = null;
        //普通通用 拼接sql 方式
        //拼凑查询的sql
        String sql = getSql(qdm, qds);
        logger.warn("查询sql:" + sql);
        //根据sql查询ES
        try {
            saveModels = queryEsBySql(sql,esConfig.getTimekey(),qdm, qds);
        }catch (Exception e){
            throw new Exception("es 查询数据出错!" +e.getMessage() );
        }
        return saveModels;
    }
    public void initParams(String startTime, String endTime) {
        // 初始执行指标,起止日期没有值
        this.startTime = startTime == null ? null : startTime.substring(0,10);
        String now = DateUtil.formatDate(new Date(), DateUtil.DEFAULT_DATE_YMD_FORMAT);
        this.endTime = endTime == null ? now : endTime.substring(0,10);;
    }
    /**
     * 卫生机构类别 抽取
     * @param qdm
     * @param qds
     * @param startTime
     * @param endTime
     * @param timeLevel
     * @param saasid
     * @param quotaVo
     * @param esConfig
     * @return
     * @throws Exception
     */
    public List<SaveModel> extractOrgHealthCategory(List<TjQuotaDimensionMain> qdm,//主维度
                                   List<TjQuotaDimensionSlave> qds,//细维度
                                   String startTime,//开始时间
                                   String endTime, //结束时间
                                   String timeLevel, //时间维度  1日,2 周, 3 月,4 年
                                   String saasid,//saasid
                                   QuotaVo quotaVo,//指标code
                                   EsConfig esConfig //es配置
    ) throws Exception {
        this.startTime = startTime;
        this.endTime = endTime;
        this.timeLevel = timeLevel;
        this.saasid = saasid;
        this.quotaVo = quotaVo;
        this.esConfig = esConfig;
        System.out.println();
        List<SaveModel> saveModels = new ArrayList<>();
        try {
            //二次统计   特殊类型:卫生机构类型
            if( (!StringUtils.isEmpty(esConfig.getEspecialType())) && esConfig.getEspecialType().equals(orgHealthCategory)){
                Map<String, Object> dimensionMap = new HashMap<>();
                Map<String,String>  dimensionDicMap = new HashMap<>();
                //查询除开 机构维度  其他维度的字典项和 维度合并到map
                //维度key 统一变小写
                for(TjQuotaDimensionMain main:qdm){
                    if(!main.getMainCode().trim().equals("org")){
                        dimensionMap.put(main.getMainCode(),main.getMainCode());
                        if(org.apache.commons.lang.StringUtils.isNotEmpty(main.getDictSql())){
                            Map<String,String> dicMap = baseStatistsService.getDimensionMap(main.getDictSql(),main.getMainCode());
                            if(dicMap != null && dicMap.size() > 0){
                                for(String key :dicMap.keySet()){
                                    dimensionDicMap.put(key.toLowerCase(),dicMap.get(key));
                                }
                            }
                        }
                    }
                }
                for(TjQuotaDimensionSlave slave:qds){
                    dimensionMap.put(slave.getKeyVal(),slave.getKeyVal());
                    if(org.apache.commons.lang.StringUtils.isNotEmpty(slave.getDictSql())){
                        Map<String,String> dicMap = baseStatistsService.getDimensionMap(slave.getDictSql(), slave.getSlaveCode());
                        if(dicMap != null && dicMap.size() > 0){
                            for(String key :dicMap.keySet()){
                                dimensionDicMap.put(key.toLowerCase(),dicMap.get(key));
                            }
                        }
                    }
                }
                String dimension = "";
                for(String key :dimensionMap.keySet()){
                    dimension += dimensionMap.get(key) + ";";
                }
                if(dimension.length() < 1 ){
                    throw new Exception("特殊机构类型转化时 维度不能为空!" );
                }else {
                    dimension = dimension.substring(0,dimension.length()-1);
                }
                String filter = "";
                if ( !StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    filter = " quotaDate >= '" + startTime.substring(0,10) + "' and quotaDate <= '" + endTime.substring(0,10) +"' ";
                }
                //查询分组的时候要增加 org 时间 ,每天的不同机构的数据
                dimension += ";org;quotaDate";
                dimensionMap.put("org", "org");
                dimensionMap.put("quotaDate","quotaDate");
                List<Map<String, Object>> orgTypeResultList = new ArrayList<>();
                List<Map<String, Object>> mapList = baseStatistsService.getOrgHealthCategoryQuotaResultList(esConfig.getSuperiorBaseQuotaCode(),dimension,filter, "");
                if(mapList != null && mapList.size() > 0){
                    for(Map<String,Object> map : mapList){
                        String dictSql = "SELECT org_code as orgCode,hos_type_id as hosTypeId from organizations where org_code=";
                        dictSql = dictSql + "'"+ map.get("org") + "'";
                        List<MOrganization> organizations = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(MOrganization.class));
                        if(organizations != null && organizations.size() > 0){
                            if(!StringUtils.isEmpty(organizations.get(0).getHosTypeId())){
                                map.put(orgHealthCategory,organizations.get(0).getHosTypeId());
                                orgTypeResultList.add(map);
                            }
                        }
                    }
                }
                List<List<Map<String, Object>>> sumOrgTypeList =  stastisOrtType(orgTypeResultList,dimensionMap, dimensionDicMap);
                Map<String,String> dimenKeyValMap = new HashMap<>();
                dimensionMap.remove("org");
                for(Map<String,Object> map : orgTypeResultList){
                    String key = "";
                    for(String dimen:dimensionMap.keySet()){
                        key +=  map.get(dimen) + "-" ;
                    }
                    dimenKeyValMap.put(key,key);
                }
                List<List<Map<String, Object>>> dimenSumOrgTypeList = new ArrayList<>();
                for(String dimenKey :dimenKeyValMap.keySet()){
                    List<Map<String, Object>> newDimenList = new ArrayList<>();
                    for(List<Map<String, Object>> list:sumOrgTypeList){
                        String key = "";
                        for(Map<String, Object> map :list){
                            for(String dimen:dimensionMap.keySet()){
                                key += map.get(dimen)  + "-" ;
                            }
                            if(dimenKey.equals(key)){
                                key +=  map.get("code");
                                boolean flag = true;
                                //判断有没有维度一致的 有就结果叠加
                                if(newDimenList != null && newDimenList.size() > 0){
                                    for(Map<String, Object> newDimeMap :newDimenList) {
                                        String newkey = "";
                                        for (String dimen : dimensionMap.keySet()) {
                                            newkey += newDimeMap.get(dimen) + "-";
                                        }
                                        newkey +=  newDimeMap.get("code");
                                        if(newkey.equals(key)){
                                            int newResult = Integer.valueOf(newDimeMap.get("result").toString());
                                            int result = Integer.valueOf(map.get("result").toString());
                                            newDimeMap.put("result",newResult + result );
                                            flag = false;
                                        }
                                    }
                                }
                                if(flag){
                                    newDimenList.add(map);
                                }
                            }
                        }
                    }
                    dimenSumOrgTypeList.add(newDimenList);
                }
                for(List<Map<String, Object>> list:dimenSumOrgTypeList){
                    saveModels.addAll(orgHealthCategoryStatisticsService.getAllNodesStatistic(list));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception("ES 特殊机构转化 查询数据出错!" +e.getMessage() );
        }
        return saveModels;
    }
    /**
     * 统计整理 不同维度的组合数据
     * @param orgTypeList
     * @param dimensionMap 维度集合
     * @param dimensionDicMap 字典项key-value map
     * @return
     */
    public List<List<Map<String, Object>>> stastisOrtType(List<Map<String, Object>> orgTypeList,Map<String, Object> dimensionMap,
                                                          Map<String,String>  dimensionDicMap){
        Map<String,String> dimenTypeMap = new HashMap<>();
        Map<String,String> orgDimenTypeMap = new HashMap<>();
        if(orgTypeList != null && orgTypeList.size() > 0){
            for(Map<String,Object> map : orgTypeList){
                if( !StringUtils.isEmpty(map.get(orgHealthCategory))){
                    String key = "";
                    String orgTypekey = map.get(orgHealthCategory).toString();
                    for(String dimen:dimensionMap.keySet()){
                        key += "-" + map.get(dimen);
                        orgTypekey += "-" + map.get(dimen);
                    }
                    dimenTypeMap.put(key, key);//map 不重复
                    orgDimenTypeMap.put(orgTypekey, orgTypekey);//map 不重复
                }
            }
        }
        List<List<Map<String, Object>>> dimenSumList = new ArrayList<>();
        if(dimenTypeMap != null && dimenTypeMap.size() > 0){
            for(String type : dimenTypeMap.keySet()){
                List<Map<String, Object>> sumOrgTypeList = new ArrayList<>();
                double count = 0.0;
                for(String orgDimenType : orgDimenTypeMap.keySet()){
                    Map<String, Object> sumDimenMap = new HashMap<>();
                    if(orgDimenType.contains(type) && orgTypeList != null && orgTypeList.size() > 0){
                        for(Map<String,Object> map : orgTypeList){
                            String key = map.get(orgHealthCategory).toString();
                            for(String dimen:dimensionMap.keySet()){
                                key += "-" + map.get(dimen);
                            }
                            if(orgDimenType.equals(key)){
                                sumDimenMap.put("code",map.get(orgHealthCategory).toString());
                                sumDimenMap.put("quotaDate",map.get("quotaDate"));
                                count = count + Double.valueOf(map.get("result").toString());
                                if(dimensionMap != null && dimensionMap.size() > 0){
                                    for(String dimen:dimensionMap.keySet()){
                                        sumDimenMap.put(dimen,map.get(dimen));
                                        sumDimenMap.put(dimen+"Name",dimensionDicMap.get(map.get(dimen).toString().toLowerCase()));
                                    }
                                }
                            }
                        }
                        sumDimenMap.put("quotaCode",quotaVo.getCode());
                        sumDimenMap.put("quotaName",quotaVo.getName());
                        sumDimenMap.put("result",(int)count);
                        sumOrgTypeList.add(sumDimenMap);
                    }
                }
                dimenSumList.add(sumOrgTypeList);
            }
        }
        return  dimenSumList;
    }
    private  List<SaveModel> queryEsBySql(String sql,String timekey,List<TjQuotaDimensionMain> qdm,  List<TjQuotaDimensionSlave> qds) {
        List<SaveModel> returnList = new ArrayList<>();
        try {
            List<String> dimenList = new ArrayList<>();
            for(TjQuotaDimensionMain main:qdm){
                dimenList.add(main.getKeyVal());
            }
            for(TjQuotaDimensionSlave slave:qds){
                dimenList.add(slave.getKeyVal());
            }
            Map<String,String> resultMap = new HashMap<>();
            Map<String, String> daySlaveDictMap = new HashMap<>();
            List<Map<String, Object>> listMap = elasticsearchUtil.excuteDataModel(sql.toString());
            if(org.apache.commons.lang.StringUtils.isNotEmpty(esConfig.getAggregation()) && esConfig.getAggregation().equals("list")){
                returnList = extractUtil.computeList(qdm, qds, listMap, esConfig.getTimekey(), esConfig.getAggregationKey(), quotaVo);
            }else {
                for(Map<String, Object> map : listMap){
                    String keyVal = "";
                    for(String dimen :dimenList){
                        if(map.get(dimen) != null){
                            if(keyVal.length()==0){
                                keyVal = map.get(dimen).toString();
                            }else {
                                keyVal += "-" + map.get(dimen) ;
                            }
                        }
                    }
                    String dateKey = "date_histogram(field=" + timekey + ",interval=day)";
                    if(map.containsKey(dateKey)){
                        keyVal += "-" + map.get(dateKey).toString().substring(0, 10);
                        daySlaveDictMap.put(keyVal,map.get(dateKey).toString().substring(0,10));
                    }
                    if(map.containsKey("result")){
                        NumberFormat nf = NumberFormat.getInstance();
                        nf.setGroupingUsed(false);
                        nf.setMaximumFractionDigits(2);
                        resultMap.put(keyVal, nf.format(map.get("result")));
                    }
                    if(map.containsKey("count(1)")){
                        NumberFormat nf = NumberFormat.getInstance();
                        nf.setGroupingUsed(false);
                        nf.setMaximumFractionDigits(2);
                        resultMap.put(keyVal, nf.format(map.get("count(1)")));
                    }
                    if(map.containsKey("SUM(result)")){
                        NumberFormat nf = NumberFormat.getInstance();
                        nf.setGroupingUsed(false);
                        nf.setMaximumFractionDigits(2);
                        resultMap.put(keyVal, nf.format(map.get("SUM(result)")));
                    }
                }
                TjQuotaDimensionSlave tjQuotaDimensionSlave = new TjQuotaDimensionSlave();
                tjQuotaDimensionSlave.setQuotaCode(quotaVo.getCode());
                qds.add(tjQuotaDimensionSlave);
                extractUtil.compute(qdm, qds, returnList, resultMap, daySlaveDictMap, quotaVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnList;
    }
    /**
     * 拼接sql
     * @param tjQuotaDimensionMains
     * @param tjQuotaDimensionSlaves
     * @return
     */
    private String getSql(List<TjQuotaDimensionMain> tjQuotaDimensionMains, List<TjQuotaDimensionSlave> tjQuotaDimensionSlaves) throws Exception{
        StringBuffer allField = new StringBuffer("");
        String tableName = esConfig.getIndex();
        for (TjQuotaDimensionMain one :tjQuotaDimensionMains) {
            String code = one.getKeyVal();
            allField.append(code+ ",");
        }
        for (TjQuotaDimensionSlave slave :tjQuotaDimensionSlaves) {
            allField.append(slave.getKeyVal() + ",");
        }
        //拼接where语句 和 分组字段
        StringBuffer whereSql = new StringBuffer(" where ");
        boolean filterFlag = false;
        if (!StringUtils.isEmpty(esConfig.getFilter())) {
            whereSql.append("" + esConfig.getFilter());
            filterFlag = true;
        }
        String timeKey = esConfig.getTimekey();
        String timeGroup = "";
        if ( !StringUtils.isEmpty(timeKey)) {
            timeGroup = ",date_histogram(field='"+ timeKey +"','interval'='day')";
            if(filterFlag){
                whereSql.append(" and ");
            }
            if ( !StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                whereSql.append( timeKey + " >= '" + startTime + "' and ");
                whereSql.append( timeKey + " <='" + endTime + "'");
            }
        }
        String selectGroupField = allField.toString();
        String whereGroupField = allField.substring(0,allField.length() - 1);
        //拼接整个sql 语法
        StringBuffer sql = new StringBuffer();
        if(StringUtils.isEmpty(esConfig.getAggregation()) && StringUtils.isEmpty(esConfig.getAddFirstQuotaCode())){
            sql.append("select " + selectGroupField + " count(1) from " + tableName + whereSql + " group by " + whereGroupField + timeGroup );
        } else if (!StringUtils.isEmpty(esConfig.getAddFirstQuotaCode())) {
            String myWhere = "quotaCode in('" + esConfig.getAddFirstQuotaCode().replace("_", "") + "','" + esConfig.getAddSecondQuotaCode().replace("_", "") + "')";
            if (!"where".equals(whereSql.toString().trim())) {
                myWhere = " and " + myWhere;
            }
            sql.append("select " + selectGroupField + " sum(result) from " + tableName + whereSql + myWhere + " group by " + whereGroupField + timeGroup);
        } else if(esConfig.getAggregation().equals(Contant.quota.aggregation_sum)){
            if(!StringUtils.isEmpty(esConfig.getAggregation()) && StringUtils.isEmpty(selectGroupField)|| selectGroupField.length()==0){
                sql.append("select sum(" ).append(esConfig.getAggregationKey()).append(" )  from " + tableName + whereSql);
            }else {
                sql.append("select ").append(selectGroupField ).append(" sum(").append(esConfig.getAggregationKey()).append(" ) result from " + tableName + whereSql + " group by "  + whereGroupField + timeGroup );
            }
        }else if(esConfig.getAggregation().equals(Contant.quota.aggregation_list)){
            if(esConfig.getTimekey() != null){
                if( StringUtils.isEmpty( esConfig.getAggregationKey()) ){
                    sql.append("select " + selectGroupField.substring(0,selectGroupField.length()-1) + "," + esConfig.getTimekey() +  " from " + tableName + whereSql + " limit 10000 ");//最多一次1万条
                }else {
                    sql.append("select " + selectGroupField + esConfig.getAggregationKey() + "," + esConfig.getTimekey() +   " from " + tableName + whereSql  + " limit 10000 ");
                }
            }else {
                throw  new Exception("配置参数 timekey 不能为空");
            }
        }
        return sql.toString();
    }
}

+ 444 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/es/EsResultExtract.java

@ -0,0 +1,444 @@
package com.yihu.quota.etl.extract.es;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.elasticsearch.ElasticSearchPool;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.etl.util.ElasticsearchUtil;
import com.yihu.quota.model.jpa.TjQuota;
import com.yihu.quota.model.jpa.save.TjDataSave;
import com.yihu.quota.model.jpa.save.TjQuotaDataSave;
import com.yihu.quota.service.save.TjDataSaveService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.bucket.terms.DoubleTerms;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.search.aggregations.metrics.valuecount.InternalValueCount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * Created by janseny on 2017/6/24
 */
@Component
@Scope("prototype")
public class EsResultExtract {
    private Logger logger = LoggerFactory.getLogger(EsResultExtract.class);
    private String startTime;
    private String endTime;
    private String org;
    private String orgName;
    private String province;
    private String city;
    private String town;
    private String townName;
    private String year;
    private String slaveKey1;
    private String slaveKey2;
    private String result;
    private TjQuota tjQuota;
    private String quotaCode;
    private EsConfig esConfig;
    @Autowired
    ElasticsearchUtil elasticsearchUtil;
    @Autowired
    ElasticSearchPool elasticSearchPool;
    @Autowired
    private TjDataSaveService tjDataSaveService;
    @Autowired
    private ObjectMapper objectMapper;
    public void initialize(TjQuota tjQuota ,String filters) throws Exception {
        this.startTime = null;
        this.endTime = null;
        this.orgName = null;
        this.org = null;
        this.province = null;
        this.city = null;
        this.town = null;
        this.townName = null;
        this.year = null;
        this.quotaCode = null;
        this.result = null;
        this.slaveKey1 = null;
        this.slaveKey2 = null;
        if(!StringUtils.isEmpty(filters)){
            Map<String, Object> params  = objectMapper.readValue(filters, new TypeReference<Map>() {});
            if (params !=null && params.size() > 0){
                for(String key : params.keySet()){
                    if( params.get(key) != null ){
                        if(key.equals("startTime"))
                            this.startTime = params.get(key).toString();
                        else if(key.equals("endTime"))
                            this.endTime = params.get(key).toString();
                        else if(key.equals("orgName"))
                            this.orgName = params.get(key).toString();
                        else if(key.equals("org"))
                            this.org = params.get(key).toString();
                        else if(key.equals("province"))
                            this.province = params.get(key).toString();
                        else if(key.equals("city"))
                            this.city = params.get(key).toString();
                        else if(key.equals("town"))
                            this.town = params.get(key).toString();
                        else if(key.equals("townName"))
                            this.townName = params.get(key).toString();
                        else if(key.equals("year"))
                            this.year = params.get(key).toString();
                        else if(key.equals("slaveKey1"))
                            this.slaveKey1 = params.get(key).toString();
                        else if(key.equals("slaveKey2"))
                            this.slaveKey2 = params.get(key).toString();
                        else if(key.equals("result")){
                            this.result = params.get(key).toString();
                        }
                    }
                }
            }
        }
        this.tjQuota = tjQuota;
        if(null != tjQuota && StringUtils.isNotEmpty(tjQuota.getCode())){
            this.quotaCode = tjQuota.getCode();
        }
        EsConfig esConfig = null;
        esConfig = getEsConfig(tjQuota);
        this.esConfig = esConfig;
    }
    public EsConfig getEsConfig(TjQuota tjQuota) throws Exception {
        //得到该指标的数据存储
        TjQuotaDataSave quotaDataSave = tjDataSaveService.findByQuota(tjQuota.getCode());
        //如果为空说明数据错误
        if (quotaDataSave == null) {
            throw new Exception("quotaDataSave data error");
        }
        //判断数据源是什么类型,根据类型和数据库相关的配置信息抽取数据
        EsConfig esConfig = null;
        if (TjDataSave.type_es.equals(quotaDataSave.getType())) {
            JSONObject obj = new JSONObject().fromObject(quotaDataSave.getConfigJson());
            esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
        }else {
            // wait TO DO
        }
        //初始化es链接
        esConfig = (EsConfig) JSONObject.toBean(JSONObject.fromObject(esConfig), EsConfig.class);
        return esConfig;
    }
    public List<Map<String, Object>> queryResultPage(TjQuota tjQuota ,String filters,int pageNo,int pageSize) throws Exception {
        pageNo = (pageNo-1)*pageSize;
        initialize(tjQuota,filters);
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
        getBoolQueryBuilder(boolQueryBuilder);
        TransportClient client = elasticSearchPool.getClient();
        List<Map<String, Object>> restltList = null;
        try {
            restltList =  elasticsearchUtil.queryPageList(client, esConfig.getIndex(), esConfig.getType(), boolQueryBuilder, pageNo, pageSize,"quotaDate");
        } catch (Exception e){
            e.getMessage();
        }
        return restltList;
    }
    public int getQuotaTotalCount(TjQuota tjQuota,String filters) throws Exception {
        initialize(tjQuota,filters);
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
        getBoolQueryBuilder(boolQueryBuilder);
        TransportClient  client = elasticSearchPool.getClient();
        int count  = 0;
        try {
            count  = (int)elasticsearchUtil.getTotalCount(client,esConfig.getIndex(),esConfig.getType(),boolQueryBuilder);
        }catch (Exception e){
            e.getMessage();
        }
        return count;
    }
    public List<Map<String, Object>> getQuotaReport(TjQuota tjQuota, String filters,int size) throws Exception {
        initialize(tjQuota,filters);
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
        getBoolQueryBuilder(boolQueryBuilder);
        TransportClient  client = elasticSearchPool.getClient();
        List<Map<String, Object>> list = null;
        try {
           list = elasticsearchUtil.queryList(client,esConfig.getIndex(),esConfig.getType(),boolQueryBuilder, "quotaDate",size);
        }catch (Exception e){
            e.getMessage();
        }
        return  list;
    }
    public BoolQueryBuilder getBoolQueryBuilder(BoolQueryBuilder boolQueryBuilder){
        if( !StringUtils.isEmpty(result)){
            if( !result.equals("qb")){//查全部
                result = "1";
                RangeQueryBuilder rangeQueryResult = QueryBuilders.rangeQuery("result").gte(result);
                boolQueryBuilder.must(rangeQueryResult);
            }
        }
        if( !StringUtils.isEmpty(quotaCode)){
//            TermQueryBuilder termQueryQuotaCode = QueryBuilders.termQuery("quotaCode", quotaCode);
            if(esConfig.getType().equals("orgHealthCategoryQuota")){
                QueryStringQueryBuilder termQuotaCode = QueryBuilders.queryStringQuery("orgHealthCategoryQuotaCode:" + quotaCode.replaceAll("_",""));
                boolQueryBuilder.must(termQuotaCode);
            }else{
                QueryStringQueryBuilder termQuotaCode = QueryBuilders.queryStringQuery("quotaCode:" + quotaCode.replaceAll("_",""));
                boolQueryBuilder.must(termQuotaCode);
            }
        }
        BoolQueryBuilder qbChild =  QueryBuilders.boolQuery();
        if( !StringUtils.isEmpty(orgName) ){
//            TermQueryBuilder termQueryOrgName = QueryBuilders.termQuery("orgName", orgName);
            QueryStringQueryBuilder termOrgName = QueryBuilders.queryStringQuery("orgName:" + orgName);
            boolQueryBuilder.must(termOrgName);
        }
        if( !StringUtils.isEmpty(org) ){
            String [] orgvals =org.split(",");
            for(int i=0;i<orgvals.length ; i++){
                MatchQueryBuilder termOrg = QueryBuilders.matchPhraseQuery("org", orgvals[i]);
                qbChild.should(termOrg);
            }
            boolQueryBuilder.must(qbChild);
        }
        if( !StringUtils.isEmpty(slaveKey1) ){
            QueryStringQueryBuilder termSlaveKey1 = QueryBuilders.queryStringQuery("slaveKey1:" + slaveKey1);
            qbChild.should(termSlaveKey1);
            boolQueryBuilder.must(qbChild);
        }
        if( !StringUtils.isEmpty(slaveKey2) ){
            QueryStringQueryBuilder termSlaveKey2 = QueryBuilders.queryStringQuery("slaveKey2:" + slaveKey2);
            qbChild.should(termSlaveKey2);
            boolQueryBuilder.must(qbChild);
        }
        if( !StringUtils.isEmpty(province) ){
            QueryStringQueryBuilder termProvince = QueryBuilders.queryStringQuery("province:" + province);
            boolQueryBuilder.must(termProvince);
        }
        if( !StringUtils.isEmpty(city) ){
            QueryStringQueryBuilder termCity = QueryBuilders.queryStringQuery("city:" + city);
            boolQueryBuilder.must(termCity);
        }
        if( !StringUtils.isEmpty(town) ){
            QueryStringQueryBuilder termTown = QueryBuilders.queryStringQuery("town:" + town);
            boolQueryBuilder.must(termTown);
        }
        if( !StringUtils.isEmpty(townName) ){
            QueryStringQueryBuilder termTown = QueryBuilders.queryStringQuery("townName:" + townName);
            boolQueryBuilder.must(termTown);
        }
        if( !StringUtils.isEmpty(year) ){
            QueryStringQueryBuilder termYear = QueryBuilders.queryStringQuery("year:" + year);
            boolQueryBuilder.must(termYear);
        }
        if( !StringUtils.isEmpty(startTime) ){
            RangeQueryBuilder rangeQueryStartTime = QueryBuilders.rangeQuery("quotaDate").gte(startTime);
            boolQueryBuilder.must(rangeQueryStartTime);
        }
        if( !StringUtils.isEmpty(endTime)){
            RangeQueryBuilder rangeQueryEndTime = QueryBuilders.rangeQuery("quotaDate").lte(endTime);
            boolQueryBuilder.must(rangeQueryEndTime);
        }
        return boolQueryBuilder;
    }
    /**
     * 递归解析json
     *
     * @param gradeBucketIt
     * @param map
     * @param sb
     */
    private void expainJson(Iterator<Terms.Bucket> gradeBucketIt,Map<String,Integer>map, StringBuffer sb) {
        while (gradeBucketIt.hasNext()) {
            Terms.Bucket b =  gradeBucketIt.next();
            if (b.getAggregations().asList().get(0) instanceof StringTerms) {
                StringTerms stringTermsCh = (StringTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = stringTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof LongTerms) {
                LongTerms longTermsCh = (LongTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = longTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof DoubleTerms) {
                DoubleTerms doubleTermsCh = (DoubleTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = doubleTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else {
                if (b.getAggregations().asList().get(0) instanceof InternalValueCount) {
                    InternalValueCount count = (InternalValueCount) b.getAggregations().asList().get(0);
                    map.put(new StringBuffer((sb == null ? "" : (sb.toString() + "-"))+ b.getKey()).toString() , (int)count.getValue());
                }else if (b.getAggregations().asList().get(0) instanceof InternalSum) {
                    InternalSum count = (InternalSum) b.getAggregations().asList().get(0);
                    map.put(new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + "-" + b.getKey()).toString() , (int)count.getValue());
                }
            }
        }
    }
    //指标分组统计数量 - 只支持一个字段
    public List<Map<String, Object>> searcherByGroup(TjQuota tjQuota, String filters,String aggsField ) throws Exception {
        initialize(tjQuota,filters);
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
        getBoolQueryBuilder(boolQueryBuilder);
        TransportClient client = elasticSearchPool.getClient();
        List<Map<String, Object>> list = null;
        try {
            list = elasticsearchUtil.searcherByGroup(client,esConfig.getIndex(),esConfig.getType(), boolQueryBuilder, aggsField, "result");
        } catch (Exception e){
            e.getMessage();
        }
        return  list;
    }
    //根据mysql 指标分组求和 支持一个和多个字段
    public Map<String, Integer> searcherSumByGroupBySql(TjQuota tjQuota , String aggsFields ,String filter, String sumField,String orderFild,String order) throws Exception {
        initialize(tjQuota,null);
        if(StringUtils.isEmpty(filter)){
            filter =  " quotaCode='" + tjQuota.getCode().replaceAll("_", "") + "' ";
        }else {
            filter = filter + " and quotaCode='" + tjQuota.getCode().replaceAll("_","") + "' ";
        }
        TransportClient client = elasticSearchPool.getClient();
        Map<String, Integer> map = null;
        try {
            map = elasticsearchUtil.searcherSumByGroupBySql(client, esConfig.getIndex(), aggsFields, filter, sumField,orderFild,order);;
        } catch (Exception e){
            e.getMessage();
        }
        return map;
    }
    /**
     * //根据mysql 指标分组 按时间聚合
     * @param tjQuota
     * @param aggsFields
     * @param filter
     * @param dateDime
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> searcherSumByGroupByTime(TjQuota tjQuota , String aggsFields ,String filter,String dateDime) throws Exception {
        initialize(tjQuota,null);
        String quotaCode = " quotaCode='" + tjQuota.getCode().replaceAll("_", "") + "' ";
        if(StringUtils.isEmpty(filter)){
            filter =  quotaCode;
        }else {
            filter += " and " + quotaCode;
        }
        if(StringUtils.isNotEmpty(aggsFields)){
            aggsFields += ",";
        }
        try {
            //SELECT sum(result) FROM medical_service_index group by town,date_histogram(field='quotaDate','interval'='year')
            StringBuffer mysql = new StringBuffer("SELECT ")
                    .append(aggsFields)
                    .append(" sum(result) FROM ").append(esConfig.getIndex())
                    .append(" where quotaDate is not null and ").append(filter)
                    .append(" group by ").append(aggsFields)
                    .append(" date_histogram(field='quotaDate','interval'='")
                    .append(dateDime).append("')").append(" limit 10000 ");
            logger.warn("查询分组 mysql= " + mysql.toString());
            List<Map<String, Object>> listMap = elasticsearchUtil.excuteDataModel(mysql.toString());
            if(listMap != null &&  listMap.size() > 0){
                if(listMap.get(0).get("SUM(result)") != null){
                    return  listMap;
                }
            }
            return  new ArrayList<>();
        } catch (Exception e){
            e.getMessage();
        }
        return null;
    }
    /**
     * 根据sql  分组统计数据
     * @param tjQuota
     * @param aggsFields
     * @param filter
     * @param sumField
     * @param orderFild
     * @param order
     * @return
     * @throws Exception
     */
    public  List<Map<String, Object>>  searcherSumGroup(TjQuota tjQuota , String aggsFields ,String filter, String sumField,String orderFild,String order, String top) throws Exception {
        initialize(tjQuota,null);
        String quotaCode = " quotaCode='" + tjQuota.getCode().replaceAll("_", "") + "' ";
        if(StringUtils.isEmpty(filter)){
            filter =  quotaCode;
        }else {
            filter += " and " + quotaCode;
        }
        try {
            StringBuffer mysql = new StringBuffer("select ");
            mysql.append(aggsFields)
                    .append(" ,sum(").append(sumField).append(") ")
                    .append(" from ").append(esConfig.getIndex())
                    .append(" where quotaDate is not null and ").append(filter)
                    .append(" group by ").append(aggsFields);
            if(StringUtils.isNotEmpty(orderFild) && StringUtils.isNotEmpty(order)){
                if (StringUtils.isNotEmpty(top)) {
                    mysql.append(" order by sum(").append(sumField).append(") desc");
                } else {
                    mysql.append(" order by ").append(orderFild).append(" ").append(order);
                }
            }
            if (StringUtils.isNotEmpty(top)) {
                mysql.append(" limit ").append(top);
            } else {
                mysql.append(" limit 10000 ");
            }
            logger.warn("查询分组 mysql= " + mysql.toString());
            List<Map<String, Object>> listMap = elasticsearchUtil.excuteDataModel(mysql.toString());
            if(listMap != null &&  listMap.size() > 0){
                if(listMap.get(0).get("SUM(result)") != null){
                    return  listMap;
                }
            }
            return  new ArrayList<>();
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }
}

+ 176 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/mysql/MysqlExtract.java

@ -0,0 +1,176 @@
package com.yihu.quota.etl.extract.mysql;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.etl.ExtractConverUtil;
import com.yihu.quota.etl.extract.ExtractUtil;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import com.yihu.quota.vo.FilterModel;
import com.yihu.quota.vo.QuotaVo;
import com.yihu.quota.vo.SaveModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.time.LocalDate;
import java.util.*;
/**
 * Created by janseny on 2017/7/10.
 */
@Component
@Scope("prototype")
public class MysqlExtract {
    private Logger logger = LoggerFactory.getLogger(MysqlExtract.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ExtractUtil extractUtil;
    @Autowired
    private ExtractConverUtil extractConverUtil;
    private QuotaVo quotaVo;
    private String startTime;
    private String endTime;
    private String timeLevel;
    private EsConfig esConfig;
    public List<SaveModel> extract(List<TjQuotaDimensionMain> qdm,//主维度
                                   List<TjQuotaDimensionSlave> qds,//细维度
                                   String startTime,//开始时间
                                   String endTime, //结束时间
                                   String timeLevel, //时间维度  1日,2 周, 3 月,4 年
                                   QuotaVo quotaVo,//指标code
                                   EsConfig esConfig //es配置
    ) throws Exception {
        this.startTime = startTime;
        this.endTime = endTime;
        this.timeLevel = timeLevel;
        this.quotaVo = quotaVo;
        this.esConfig = esConfig;
        initParams(this.startTime ,this.endTime);
        List<SaveModel> returnList = new ArrayList<>();
        //获取mysql
        String mysql = getSql(qdm,qds);
        logger.warn(mysql);
        if( !StringUtils.isEmpty(mysql)){
            Map<String,String> resultMap = new HashMap<>();
            Map<String, String> daySlaveDictMap = new HashMap<>();
            //执行MySQL
            List<Map<String, Object>> mapList = null;
            try {
                mapList =  jdbcTemplate.queryForList(mysql);
                FilterModel filterModel = new FilterModel(mapList,null);
                //数据转换
                filterModel =  extractConverUtil.convert(filterModel,qds);
                if(filterModel != null && filterModel.getDataList() != null){
                    mapList = filterModel.getDataList();
                }
            }catch (Exception e){
                throw new Exception("mysql查询数据出错" + e.getMessage());
            }
            if(org.apache.commons.lang.StringUtils.isNotEmpty(esConfig.getAggregation()) && esConfig.getAggregation().equals("list")){
                returnList = extractUtil.computeList(qdm, qds, mapList, esConfig.getTimekey(), esConfig.getAggregationKey(), quotaVo);
            }else {
                if(mapList != null && mapList.size() > 0){
                    for(Map<String, Object> map :mapList){
                        String keyVal  = "";
                        for(String key :map.keySet()){
                            if(!key.equals("result")){
                                keyVal = keyVal + map.get(key) +  "-";
                            }
                        }
                        String result = map.get("result").toString();
                        String mapKey = keyVal.substring(0, keyVal.length() - 1);
                        resultMap.put(mapKey, result);
                        daySlaveDictMap.put(mapKey, map.get("quotaDate").toString());
                    }
                    TjQuotaDimensionSlave tjQuotaDimensionSlave = new TjQuotaDimensionSlave();
                    tjQuotaDimensionSlave.setQuotaCode(quotaVo.getCode());
                    qds.add(tjQuotaDimensionSlave);
                    extractUtil.compute(qdm, qds, returnList, resultMap,daySlaveDictMap,quotaVo);
                }
            }
        }
        return returnList;
    }
    public void initParams(String startTime, String endTime) {
        // 初始执行指标,起止日期没有值
        this.startTime = startTime == null ? null : startTime.substring(0,10);
        String now = DateUtil.formatDate(new Date(), DateUtil.DEFAULT_DATE_YMD_FORMAT);
        this.endTime = endTime == null ? now : endTime.substring(0,10);;
    }
    /**
     * @param tjQuotaDimensionMains
     * @param tjQuotaDimensionSlaves
     * @return
     */
    private String getSql(List<TjQuotaDimensionMain> tjQuotaDimensionMains, List<TjQuotaDimensionSlave> tjQuotaDimensionSlaves) {
        StringBuffer allField = new StringBuffer("");
        String tableName = esConfig.getTable();
        for (int j = 0; j < tjQuotaDimensionMains.size(); j++) {
            TjQuotaDimensionMain one = tjQuotaDimensionMains.get(j);
            if ( !StringUtils.isEmpty(one.getKeyVal())) {
                allField.append(one.getKeyVal() + ",");
            }
        }
        for (int i = 0; i < tjQuotaDimensionSlaves.size(); i++) {
            allField.append(tjQuotaDimensionSlaves.get(i).getKeyVal()+ ",");
        }
        //拼接where语句 和 分组字段
        StringBuffer whereSql = new StringBuffer();
        whereSql.append(" where 1=1");
        if (!StringUtils.isEmpty(esConfig.getFilter())) {
            whereSql.append(" and " + esConfig.getFilter());
        }
        String selectGroupField = allField.toString();
        String whereGroupField = allField.toString();
        String timeKey = esConfig.getTimekey();
        if ( !StringUtils.isEmpty(timeKey)) {
            if ( !StringUtils.isEmpty(esConfig.getFullQuery() ) && esConfig.getFullQuery().equals("true")) {
                whereSql.append( " and " + timeKey + " < '" + endTime + "'");
                selectGroupField += " '"+ LocalDate.now().toString() +"' as quotaDate ,";
            }else{
                if ( !StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    whereSql.append(" and " + timeKey + " >= '" + startTime + "'");
                    whereSql.append( " and " + timeKey + " < '" + endTime + "'");
                }
                selectGroupField += " DATE_FORMAT(" + timeKey + ",'%Y-%m-%d') as quotaDate ,";
            }
            whereGroupField += timeKey;
        }else{
            whereGroupField = allField.substring(0,allField.length() - 1);
        }
        //拼接整个sql 语法
        StringBuffer sql = new StringBuffer();
        if(StringUtils.isEmpty(esConfig.getAggregation())){
            sql.append("select " + selectGroupField + " count(*) result from " + tableName + whereSql + " group by " + whereGroupField);
        }else if(esConfig.getAggregation().equals(Contant.quota.aggregation_sum)){
            if(StringUtils.isEmpty(selectGroupField)|| selectGroupField.length()==0){
                sql.append("select sum(" ).append(esConfig.getAggregationKey()).append(" ) result  from " + tableName + whereSql);
            }else {
                sql.append("select ").append(selectGroupField ).append(" sum(").append(esConfig.getAggregationKey()).append(" ) result from " + tableName + whereSql + " group by " + whereGroupField);
            }
        }else if(esConfig.getAggregation().equals(Contant.quota.aggregation_list)){
            if( StringUtils.isEmpty( esConfig.getAggregationKey()) ){
                sql.append("select " + selectGroupField + " 1 result from " + tableName + whereSql);
            }else {
                sql.append("select " + selectGroupField + esConfig.getAggregationKey() + " result from " + tableName + whereSql);
            }
        }
        return sql.toString();
    }
}

+ 283 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/extract/solr/SolrExtract.java

@ -0,0 +1,283 @@
//package com.yihu.quota.etl.extract.solr;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.elasticsearch.ElasticSearchUtil;
//import com.yihu.ehr.query.common.model.SolrGroupEntity;
//import com.yihu.ehr.query.services.SolrQuery;
//import com.yihu.ehr.util.datetime.DateUtil;
//import com.yihu.quota.dao.jpa.save.TjQuotaDataSaveDao;
//import com.yihu.quota.etl.Contant;
//import com.yihu.quota.etl.ExtractConverUtil;
//import com.yihu.quota.etl.extract.ExtractUtil;
//import com.yihu.quota.etl.model.EsConfig;
//import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
//import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
//import com.yihu.quota.model.jpa.save.TjQuotaDataSave;
//import com.yihu.quota.vo.FilterModel;
//import com.yihu.quota.vo.QuotaVo;
//import com.yihu.quota.vo.SaveModel;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Scope;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
//
//import java.io.IOException;
//import java.util.*;
//
///**
// * 对solr抽取数据,基于指标配置维度(不能包括按周、月、年等时间维度) +
// * 默认按天维度统计值作为最小单位分组聚合,
// * 保存聚合结果到ES。二次统计基于以上的聚合结果进行统计。
// * <p>
// * Created by janseny on 2017/7/10.
// */
//@Component
//@Scope("prototype")
//public class SolrExtract {
//
//    private Logger logger = LoggerFactory.getLogger(SolrExtract.class);
//
//    @Autowired
//    private ExtractUtil extractUtil;
//    @Autowired
//    private SolrQuery solrQuery;
//    @Autowired
//    private ExtractConverUtil extractConverUtil;
//    @Autowired
//    private ElasticSearchUtil esUtil;
//    @Autowired
//    private TjQuotaDataSaveDao tjQuotaDataSaveDao;
//    @Autowired
//    private ObjectMapper objectMapper;
//
//    private static String create_date = "create_date";
//
//    private QuotaVo quotaVo;
//    private String startTime;
//    private String endTime;
//    private String timeLevel;
//    private EsConfig esConfig;
//
//    public List<SaveModel> extract(List<TjQuotaDimensionMain> qdm,//主维度
//                                   List<TjQuotaDimensionSlave> qds,//细维度
//                                   String startTime,//开始时间
//                                   String endTime, //结束时间
//                                   String timeLevel, // 时间维度,默认且只按天统计
//                                   QuotaVo quotaVo,//指标配置
//                                   EsConfig esConfig //es配置
//    ) throws Exception {
//        this.startTime = startTime;
//        this.endTime = endTime;
//        this.timeLevel = timeLevel;
//        this.quotaVo = quotaVo;
//        this.esConfig = esConfig;
//        solrQuery.initParams(this.startTime, this.endTime);
//
//        // 统计数据
//        return statiscSlor(qdm, qds, quotaVo);
//    }
//
//    public int getExtractTotal(String startTime, String endTime, EsConfig esConfig) throws Exception {
//        this.startTime = startTime;
//        this.endTime = endTime;
//        this.esConfig = esConfig;
//        solrQuery.initParams(this.startTime, this.endTime);
//        String core = esConfig.getTable(); // solr的core名
//        String q = null; // 过滤条件
//        String createDateFilter = "";//入库时间过滤条件
//        // 统计数据数量
//        String timeKey = esConfig.getTimekey();
//        if (!StringUtils.isEmpty(timeKey)) {
//            if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
//                q = String.format("%s:[%s TO %s]", timeKey, startTime, endTime);
//                createDateFilter = String.format("%s:[%s TO %s]", create_date, startTime, endTime);
//                q = q + " OR " + createDateFilter;
//            } else {
//                q = timeKey + ":[* TO *]";
//            }
//        }
//        long rows = solrQuery.count(core, q ,esConfig.getFilter());
//        return Integer.valueOf(String.valueOf(rows));
//    }
//
//    public List<SaveModel> statiscSlor(List<TjQuotaDimensionMain> qdm,
//                                       List<TjQuotaDimensionSlave> qds,
//                                       QuotaVo quotaVo) throws Exception {
//        List<SaveModel> returnList = new ArrayList<>();
//
//        String core = esConfig.getTable(); // solr的core名
//        String q = null; // 查询条件
//        String fq = null; // 过滤条件
//        String createDateFilter = "";//入库时间过滤条件
//        if (esConfig.getFilter() != null) {
//            fq = esConfig.getFilter();
//        }
//        String fl = ""; // 结果指定查询字段
//        List<SolrGroupEntity> dimensionGroupList = new ArrayList<>(); // 维度分组统计条件
//        if (StringUtils.isEmpty(esConfig.getTimekey())) {
//            throw new Exception("数据源配置 timeKey 不能为空!");
//        }
//        String timeKey = esConfig.getTimekey();
//
//        Map<String, String> mainMap = new HashMap<>();
//        Map<String, String> slaveMap = new HashMap<>();
//        for (int i = 0; i < qdm.size(); i++) {
//            String key = qdm.get(i).getKeyVal();
//            mainMap.put(key, key);
//            dimensionGroupList.add(new SolrGroupEntity(key, SolrGroupEntity.GroupType.FIELD_VALUE));
//            fl += key + ",";
//            if(qdm.get(i).getMainCode().equals("org")){
//                String orgFilter = " AND org_code:*" ;
//                if ( !StringUtils.isEmpty(fq)) {
//                    fq += orgFilter ;
//                }else {
//                    fq = orgFilter;
//                }
//            }
//            if(qdm.get(i).getMainCode().equals("town")){
//                String townFilter = " AND org_area:*" ;
//                if ( !StringUtils.isEmpty(fq)) {
//                    fq += townFilter ;
//                }else {
//                    fq = townFilter;
//                }
//            }
//        }
//        for (int i = 0; i < qds.size(); i++) {
//            String key = qds.get(i).getKeyVal();
//            slaveMap.put(key, key);
//            dimensionGroupList.add(new SolrGroupEntity(key, SolrGroupEntity.GroupType.FIELD_VALUE));
//            fl += key + ",";
//        }
//        fl += timeKey + "," + create_date + ",rowkey";
//
//        if (StringUtils.isEmpty(esConfig.getAggregation()) || (!esConfig.getAggregation().equals(Contant.quota.aggregation_list)  && !esConfig.getAggregation().equals(Contant.quota.aggregation_distinct))) {
//            // 默认追加一个日期字段作为细维度,方便按天统计作为最小单位统计值。
//            slaveMap.put(timeKey, timeKey);
//            TjQuotaDimensionSlave daySlave = new TjQuotaDimensionSlave();
//            daySlave.setSlaveCode(timeKey);
//            daySlave.setKeyVal(timeKey);
//            qds.add(daySlave);
//            dimensionGroupList.add(new SolrGroupEntity(timeKey, SolrGroupEntity.GroupType.DATE_RANGE, "+1DAY"));
//        }
//
//        // 拼接增量或全量的筛选条件
//        if (!StringUtils.isEmpty(timeKey)) {
//            if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
//                q = String.format("%s:[%s TO %s]", timeKey, startTime, endTime);
//                createDateFilter = String.format("%s:[%s TO %s]", create_date, startTime, endTime);
//                q = q + " OR " + createDateFilter;
//            } else {
//                q = timeKey + ":[* TO *]";
//            }
//        }
//
//        boolean listFlag = false;
//        // 最后一个维度基于其他维度组合作为条件的统计结果的集合
//        List<Map<String, Object>> list = new ArrayList<>();
//        if (StringUtils.isEmpty(esConfig.getAggregation())
//                || Contant.quota.aggregation_count.equals(esConfig.getAggregation())) {
//            // count 聚合
//            list = solrQuery.getCountMultList(core, q, fq, dimensionGroupList, null);
//        } else if (!StringUtils.isEmpty(esConfig.getAggregationKey()) && Contant.quota.aggregation_sum.equals(esConfig.getAggregation())) {
//            // sum 聚合
//            list = solrQuery.getSumMultList(core, q, fq, esConfig.getAggregationKey(), dimensionGroupList, null);
//        } else if (Contant.quota.aggregation_list.equals(esConfig.getAggregation())) {
//            listFlag = true;
//            // 查询列表
//            try {
//                if (esConfig.getAggregation().equals(Contant.quota.aggregation_list) && !StringUtils.isEmpty(esConfig.getAggregationKey())) {
//                    fl = fl + "," + esConfig.getAggregationKey();
//                }
//                logger.warn("solr 从"+ quotaVo.getStart() + " 开始获取数据,这次准备获取" + quotaVo.getRows() + "条");
//                Map<String, String> sort = new HashMap<>();
//                sort.put("rowkey", "asc");
//                list = solrQuery.queryReturnFieldList(core, q, fq, sort, quotaVo.getStart(), quotaVo.getRows(), fl.split(","));
//            } catch (Exception e) {
//                throw new Exception("solr 查询异常 " + e.getMessage());
//            }
//        } else if (Contant.quota.aggregation_distinct.equals(esConfig.getAggregation())) {
//            listFlag = true;
//            // 去重查询
//            fl += "," + esConfig.getDistinctGroupField();
//            boolean groupNullIsolate = esConfig.getDistinctGroupNullIsolate() != null ? esConfig.getDistinctGroupNullIsolate() : false;
//            int count = (int) solrQuery.count(core, q, fq);
//            list = solrQuery.distinctQueryReturnFieldList(core, q, fq, null, 0, count, fl.split(","),
//                    esConfig.getDistinctGroupField(), esConfig.getDistinctGroupSort(), groupNullIsolate);
//            // 对比ES中如果已存在该条数据则更新,并从集合中移除该条数据。
//            checkEsDistinctData(list);
//        }
//
//        //数据转换
//        FilterModel filterModel = new FilterModel(list, null);
//        filterModel = extractConverUtil.convert(filterModel, qds);
//        if (filterModel != null && filterModel.getDataList() != null) {
//            list = filterModel.getDataList();
//        }
//        Map<String, String> statisticsResultMap = new LinkedHashMap<>(); // 统计结果集
//        Map<String, String> daySlaveDictMap = new LinkedHashMap<>(); // 按天统计的所有日期项
//        if (listFlag) {
//            if (list != null && list.size() > 0) {
//                returnList = extractUtil.computeList(qdm, qds, list, timeKey, esConfig.getAggregationKey(), quotaVo);
//            }
//        } else {
//            if (list != null && list.size() > 0) {
//                for (Map<String, Object> objectMap : list) {
//                    String statisticsKey = objectMap.get("$statisticsKey").toString();
//                    String result = objectMap.get("$result").toString();
//                    String quotaDate = objectMap.get(timeKey).toString();
//                    statisticsResultMap.put(statisticsKey, result);
//                    daySlaveDictMap.put(statisticsKey, quotaDate);
//                }
//            }
//            // 融合主细维度、其组合统计值为SaveModel
//            extractUtil.compute(qdm, qds, returnList, statisticsResultMap, daySlaveDictMap, quotaVo);
//        }
//        return returnList;
//    }
//
//    /**
//     * 去重查询后,对比 ES 中如果已存在该条数据,且去重集合中有更前的则更新quotaDate,并从去重集合中移除该条数据。
//     *
//     * @param distinctQueryList 去重查询结果集
//     */
//    private void checkEsDistinctData(List<Map<String, Object>> distinctQueryList) throws IOException {
//        List<Map<String, Object>> updateList = new ArrayList<>();
//
//        String esIndex = null;
//        String esType = null;
//        if (distinctQueryList.size() > 0) {
//            TjQuotaDataSave quotaDataSave = tjQuotaDataSaveDao.findByQuotaCode(quotaVo.getCode());
//            Map<String, Object> configJson = objectMapper.readValue(quotaDataSave.getConfigJson(), Map.class);
//            esIndex = configJson.get("index").toString();
//            esType = configJson.get("type").toString();
//        }
//
//        Iterator<Map<String, Object>> iterator = distinctQueryList.iterator();
//        while (iterator.hasNext()) {
//            Map<String, Object> item = iterator.next();
//            String timeKeyValue = DateUtil.formatDate((Date) item.get(esConfig.getTimekey()), DateUtil.DEFAULT_DATE_YMD_FORMAT);
//            String distinctField = item.get("distinctField").toString();
//            String distinctFieldValue = item.get("distinctFieldValue").toString();
//
//            String filters = "quotaCode=" + quotaVo.getCode().replace("_", "") + ";distinctField=" + distinctField + ";distinctFieldValue=" + distinctFieldValue;
//            List<Map<String, Object>> existedList = esUtil.list(esIndex, esType, filters);
//            if (existedList.size() > 0) {
//                Map<String, Object> quotaData = existedList.get(0);
//                String quotaDate = quotaData.get("quotaDate").toString();
//                if (DateUtil.compareDate(DateUtil.DEFAULT_DATE_YMD_FORMAT, timeKeyValue, quotaDate) < 0) {
//                    quotaData.put("quotaDate", timeKeyValue);
//                    updateList.add(quotaData);
//                    iterator.remove();
//                }
//            }
//        }
//
//        if (updateList.size() != 0) {
//            esUtil.bulkUpdate(esIndex, esType, updateList);
//        }
//    }
//
//}

+ 91 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/model/DbConfig.java

@ -0,0 +1,91 @@
package com.yihu.quota.etl.model;
import com.yihu.quota.etl.Contant;
/**
 * Created by chenweida on 2017/6/1.
 */
public class DbConfig {
    private String driver;//数据库驱动
    private String url; //数据库链接
    private String username; //账号
    private String password;//密码
    private String sql;// 语句 如果是多条就是分子
    private String sqlCount;// 语句数目
    private String secondSql;// 语句 分母
    private String secondSqlCount;// 语句数目
    public String getDriver() {
        return driver;
    }
    public void setDriver(String driver) {
        this.driver = driver;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSql() {
        return sql;
    }
    public void setSql(String sql) {
        this.sql = sql;
    }
    public String getSqlCount() {
        return sqlCount;
    }
    public void setSqlCount(String sqlCount) {
        this.sqlCount = sqlCount;
    }
    public String getSecondSql() {
        return secondSql;
    }
    public void setSecondSql(String secondSql) {
        this.secondSql = secondSql;
    }
    public String getSecondSqlCount() {
        return secondSqlCount;
    }
    public void setSecondSqlCount(String secondSqlCount) {
        this.secondSqlCount = secondSqlCount;
    }
    public String getDbType() {
        if(driver.contains(Contant.db_type.mysql)){
            return Contant.db_type.mysql;
        }
        if(driver.contains( Contant.db_type.oracle)){
            return  Contant.db_type.oracle;
        }
        return null;
    }
}

+ 326 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/model/EsConfig.java

@ -0,0 +1,326 @@
package com.yihu.quota.etl.model;
/**
 * Created by chenweida on 2017/6/2.
 */
public class EsConfig {
    private String host;//地址
    private Integer port;//端口
    private String index;// 索引 es相当与数据库
    private String type;// 类型 es 相当于表
    private String clusterName;//es clusterName
    private String table;// 数据库表
    private String fullQuery;  //全量查询
    private String filter;  // where条件
    private String timekey;//根据sql去查询的key 时间控制字段
    private String aggregation;// 聚合方式,默认count:计数;sum:求和;list:查询;distinct:去重查询;
    private String aggregationKey;//聚合字段
    private String especialType; //特殊类型  orgHealthCategory:卫生机构类型
    private String superiorBaseQuotaCode;  // 上级基础指标code
    private String dateComparisonType;      //时间对比类型  lastYear 去年 lastMonth 上个月 lastWeek 上个星期 lastDay 昨天
    // solr去重查询
    private String distinctGroupField; // 分组去重字段
    private String distinctGroupSort; // 去重组内排序,如:“event_date asc”。
    private Boolean distinctGroupNullIsolate; // 去重组内,空值记录是保存第一条,还是每条记录单独保存,true:拆分保存,false:保存第一条,默认合并保存。
    //除法运算
    private String molecular;  // 统计除法的分子  指标code
    private String molecularFilter;  // 除法的分子过滤条件
    private String denominator;// 统计除法的分母  指标code
    private String denominatorFilter;// 除法的分母过滤条件
    private String percentOperation;//运算方式  1 乘法  2 除法
    private String percentOperationValue;//运算对应的值
    private String divisionType; //除法运算类型 1 分子分母各维度对应相除 默认 2 分子按维度 /分母按年份获取总数 如:技术人员每千人口 = 技术人员数/对应区县总人口数*1000
    //加法运算
    private String addOperation;//加法运算方式  1 加法 默认 2 减法
    private String addFirstQuotaCode;//加法第一个指标
    private String addFirstFilter;//加法第一个指标过滤条件
    private String addSecondQuotaCode;//加法第二个指标
    private String addSecondFilter;//加法第二个指标过滤条件
    private String growthFlag;  // 增幅标志  1 year  2 month 3 quarter
    private String incrementFlag;   // 环比  1 上月  2 本月
    //已停止使用
    private String thousandFlag; //每千,每万 1000,10000
    private String thousandDmolecular; //每千,每万 统计分子
    private String thousandDenominator; //每千,每万 统计分母
    public String getSuperiorBaseQuotaCode() {
        return superiorBaseQuotaCode;
    }
    public void setSuperiorBaseQuotaCode(String superiorBaseQuotaCode) {
        this.superiorBaseQuotaCode = superiorBaseQuotaCode;
    }
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public String getIndex() {
        return index;
    }
    public void setIndex(String index) {
        this.index = index;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getTimekey() {
        return timekey;
    }
    public void setTimekey(String timekey) {
        this.timekey = timekey;
    }
    public Integer getPort() {
        return port;
    }
    public void setPort(Integer port) {
        this.port = port;
    }
    public String getClusterName() {
        return clusterName;
    }
    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }
    public String getTable() {
        return table;
    }
    public void setTable(String table) {
        this.table = table;
    }
    public String getMolecular() {
        return molecular;
    }
    public void setMolecular(String molecular) {
        this.molecular = molecular;
    }
    public String getDenominator() {
        return denominator;
    }
    public void setDenominator(String denominator) {
        this.denominator = denominator;
    }
    public String getFilter() {
        return filter;
    }
    public void setFilter(String filter) {
        this.filter = filter;
    }
    public String getAggregation() {
        return aggregation;
    }
    public void setAggregation(String aggregation) {
        this.aggregation = aggregation;
    }
    public String getAggregationKey() {
        return aggregationKey;
    }
    public void setAggregationKey(String aggregationKey) {
        this.aggregationKey = aggregationKey;
    }
    public String getThousandFlag() {
        return thousandFlag;
    }
    public void setThousandFlag(String thousandFlag) {
        this.thousandFlag = thousandFlag;
    }
    public String getThousandDmolecular() {
        return thousandDmolecular;
    }
    public void setThousandDmolecular(String thousandDmolecular) {
        this.thousandDmolecular = thousandDmolecular;
    }
    public String getThousandDenominator() {
        return thousandDenominator;
    }
    public void setThousandDenominator(String thousandDenominator) {
        this.thousandDenominator = thousandDenominator;
    }
    public String getEspecialType() {
        return especialType;
    }
    public void setEspecialType(String especialType) {
        this.especialType = especialType;
    }
    public String getPercentOperation() {
        return percentOperation;
    }
    public void setPercentOperation(String percentOperation) {
        this.percentOperation = percentOperation;
    }
    public String getPercentOperationValue() {
        return percentOperationValue;
    }
    public void setPercentOperationValue(String percentOperationValue) {
        this.percentOperationValue = percentOperationValue;
    }
    public String getMolecularFilter() {
        return molecularFilter;
    }
    public void setMolecularFilter(String molecularFilter) {
        this.molecularFilter = molecularFilter;
    }
    public String getDenominatorFilter() {
        return denominatorFilter;
    }
    public void setDenominatorFilter(String denominatorFilter) {
        this.denominatorFilter = denominatorFilter;
    }
    public String getFullQuery() {
        return fullQuery;
    }
    public void setFullQuery(String fullQuery) {
        this.fullQuery = fullQuery;
    }
    public String getAddOperation() {
        return addOperation;
    }
    public void setAddOperation(String addOperation) {
        this.addOperation = addOperation;
    }
    public String getAddFirstQuotaCode() {
        return addFirstQuotaCode;
    }
    public void setAddFirstQuotaCode(String addFirstQuotaCode) {
        this.addFirstQuotaCode = addFirstQuotaCode;
    }
    public String getAddFirstFilter() {
        return addFirstFilter;
    }
    public void setAddFirstFilter(String addFirstFilter) {
        this.addFirstFilter = addFirstFilter;
    }
    public String getAddSecondQuotaCode() {
        return addSecondQuotaCode;
    }
    public void setAddSecondQuotaCode(String addSecondQuotaCode) {
        this.addSecondQuotaCode = addSecondQuotaCode;
    }
    public String getAddSecondFilter() {
        return addSecondFilter;
    }
    public void setAddSecondFilter(String addSecondFilter) {
        this.addSecondFilter = addSecondFilter;
    }
    public String getGrowthFlag() {
        return growthFlag;
    }
    public void setGrowthFlag(String growthFlag) {
        this.growthFlag = growthFlag;
    }
    public String getIncrementFlag() {
        return incrementFlag;
    }
    public void setIncrementFlag(String incrementFlag) {
        this.incrementFlag = incrementFlag;
    }
    public String getDivisionType() {
        return divisionType;
    }
    public void setDivisionType(String divisionType) {
        this.divisionType = divisionType;
    }
    public String getDateComparisonType() {
        return dateComparisonType;
    }
    public void setDateComparisonType(String dateComparisonType) {
        this.dateComparisonType = dateComparisonType;
    }
    public String getDistinctGroupField() {
        return distinctGroupField;
    }
    public void setDistinctGroupField(String distinctGroupField) {
        this.distinctGroupField = distinctGroupField;
    }
    public String getDistinctGroupSort() {
        return distinctGroupSort;
    }
    public void setDistinctGroupSort(String distinctGroupSort) {
        this.distinctGroupSort = distinctGroupSort;
    }
    public Boolean getDistinctGroupNullIsolate() {
        return distinctGroupNullIsolate;
    }
    public void setDistinctGroupNullIsolate(Boolean distinctGroupNullIsolate) {
        this.distinctGroupNullIsolate = distinctGroupNullIsolate;
    }
}

+ 122 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/save/ExtractDataWithRunnable.java

@ -0,0 +1,122 @@
package com.yihu.quota.etl.save;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.job.EsQuotaJob;
import com.yihu.quota.model.jpa.TjQuotaLog;
import com.yihu.quota.util.SpringUtil;
import com.yihu.quota.vo.QuotaVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Created by janseny on 2018/5/23.
 */
public class ExtractDataWithRunnable implements Runnable {
    private Logger logger = LoggerFactory.getLogger(ExtractDataWithRunnable.class);
    private String saasid;
    private String timeLevel;
    private String startTime;
    private String endTime;
    private QuotaVo quotaVo;
    private TjQuotaLog tjQuotaLog;
    private int start ;
    private int perCount ;
    private final int count = 0;
    public ExtractDataWithRunnable(TjQuotaLog tjQuotaLog ,QuotaVo quotaVo, String startTime,String endTime,
                                   String timeLevel,String saasid,int start,int perCount ){
        this.tjQuotaLog = tjQuotaLog;
        this.quotaVo = quotaVo;
        this.quotaVo.setStart(start);
        this.quotaVo.setRows(perCount);
        this.startTime = startTime;
        this.endTime = endTime;
        this.timeLevel = timeLevel;
        this.saasid = saasid;
    }
    @Override
    public void run(){
        try {
            synchronized(this){
                if (count != 0){
                    quotaVo.setStart(count*perCount+1);
                }else {
                    quotaVo.setStart(0);
                }
                quotaVo.setRows(Contant.compute.perCount);
                System.out.println("start = " + start );
                SpringUtil.getBean(EsQuotaJob.class).quota(tjQuotaLog,quotaVo);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }
    public String getSaasid() {
        return saasid;
    }
    public void setSaasid(String saasid) {
        this.saasid = saasid;
    }
    public String getTimeLevel() {
        return timeLevel;
    }
    public void setTimeLevel(String timeLevel) {
        this.timeLevel = timeLevel;
    }
    public String getStartTime() {
        return startTime;
    }
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }
    public String getEndTime() {
        return endTime;
    }
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }
    public QuotaVo getQuotaVo() {
        return quotaVo;
    }
    public void setQuotaVo(QuotaVo quotaVo) {
        this.quotaVo = quotaVo;
    }
    public TjQuotaLog getTjQuotaLog() {
        return tjQuotaLog;
    }
    public void setTjQuotaLog(TjQuotaLog tjQuotaLog) {
        this.tjQuotaLog = tjQuotaLog;
    }
    public int getStart() {
        return start;
    }
    public void setStart(int start) {
        this.start = start;
    }
    public int getPerCount() {
        return perCount;
    }
    public void setPerCount(int perCount) {
        this.perCount = perCount;
    }
}

+ 148 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/save/LargDataWithRunnable.java

@ -0,0 +1,148 @@
package com.yihu.quota.etl.save;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.etl.util.EsClientUtil;
import com.yihu.quota.vo.SaveModel;
import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
/**
 * Created by janseny on 2018/5/23.
 */
public class LargDataWithRunnable implements Runnable {
    private Logger logger = LoggerFactory.getLogger(LargDataWithRunnable.class);
    private EsClientUtil esClientUtil;
    private String jsonConfig;
    private List<SaveModel> list;//待处理数据
    private int threadCount = 0;//初始化线程数
    private int flag = 1;       //这是第几个线程
    private int perCount = 10000;//每个线程处理的数据量
    private int totalCount = 0;//待处理数据总数量
    private int havedCount = 0;//已经处理的数据量
    public LargDataWithRunnable(List<SaveModel> saveModels, String jsonConfig , EsClientUtil esClientUtil){
        this.list = saveModels;
        int count  = saveModels.size()/perCount;
        int remainder = saveModels.size()%perCount;
        if(remainder != 0){
            count ++;
        }
        this.threadCount = count;
        this.totalCount = list.size();
        this.jsonConfig = jsonConfig;
        this.esClientUtil = esClientUtil;
    }
    @Override
    public void run() {
        List<SaveModel> sublist = null;
        while(totalCount - havedCount > 0){//线程会循环执行,直到所有数据都处理完
            synchronized(this){//在分包时需要线程同步,避免线程间处理重复的数据
                if(totalCount-havedCount != 0) {
                    sublist = list.subList(perCount*(flag-1), totalCount - havedCount > perCount ? perCount*flag : perCount*(flag-1) + (totalCount - havedCount));
                    flag = flag+1;
                    havedCount = sublist.size() + havedCount;
                    logger.debug("这是第" + (flag-1) +"个线程;数据 = "+ sublist.size());
                    System.out.println(Thread.currentThread().getName()+"这是第" + (flag-1) +"个线程;数据 = "+ sublist.size());
                }
                if(sublist != null) {
                    //此处为数据处理(简单打印 )
                    BulkResult br = null;
                    boolean isSuccessed = false;
                    try {
                        //得到链接
                        EsConfig esConfig = (EsConfig) JSONObject.toBean(JSONObject.fromObject(jsonConfig), EsConfig.class);
                        JestClient jestClient = esClientUtil.getJestClient(esConfig.getHost(),esConfig.getPort());
                        Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esConfig.getIndex()).defaultType(esConfig.getType());
                        for (SaveModel obj : sublist) {
                            obj.setCreateTime( new Date());
                            Index index = new Index.Builder(obj).build();
                            bulk.addAction(index);
                        }
                        br = jestClient.execute(bulk.build());
                        //关闭链接
                        jestClient.shutdownClient();
                        isSuccessed = br.isSucceeded();
                    }catch (Exception e){
                        throw new RuntimeException("ES 保存数据异常");
                    }
                }
            }
        }
    }
    public List<SaveModel> getList() {
        return list;
    }
    public void setList(List<SaveModel> list) {
        this.list = list;
    }
    public int getThreadCount() {
        return threadCount;
    }
    public void setThreadCount(int threadCount) {
        this.threadCount = threadCount;
    }
    public int getFlag() {
        return flag;
    }
    public void setFlag(int flag) {
        this.flag = flag;
    }
    public int getPerCount() {
        return perCount;
    }
    public void setPerCount(int perCount) {
        this.perCount = perCount;
    }
    public int getTotalCount() {
        return totalCount;
    }
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
    public int getHavedCount() {
        return havedCount;
    }
    public void setHavedCount(int havedCount) {
        this.havedCount = havedCount;
    }
    public String getJsonConfig() {
        return jsonConfig;
    }
    public void setJsonConfig(String jsonConfig) {
        this.jsonConfig = jsonConfig;
    }
    public EsClientUtil getEsClientUtil() {
        return esClientUtil;
    }
    public void setEsClientUtil(EsClientUtil esClientUtil) {
        this.esClientUtil = esClientUtil;
    }
}

+ 39 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/save/SaveHelper.java

@ -0,0 +1,39 @@
package com.yihu.quota.etl.save;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.etl.save.es.ElastricSearchSave;
import com.yihu.quota.model.jpa.save.TjQuotaDataSave;
import com.yihu.quota.service.save.TjDataSaveService;
import com.yihu.quota.util.SpringUtil;
import com.yihu.quota.vo.QuotaVo;
import com.yihu.quota.vo.SaveModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.List;
/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class SaveHelper {
    @Autowired
    private TjDataSaveService datsSaveService;
    public Boolean save(List<SaveModel> dataModels, QuotaVo quotaVo) {
        //查看指标保存的数据源
        TjQuotaDataSave quotaDataSave = datsSaveService.findByQuota(quotaVo.getCode());
        switch (quotaDataSave.getType()) {
            case Contant.save.mysql: {
                return null;
            }
            case Contant.save.es: {
                return SpringUtil.getBean(ElastricSearchSave.class).save(dataModels,quotaDataSave.getConfigJson());
//                return SpringUtil.getBean(ElastricSearchSave.class).saveByMoreThred(dataModels,quotaDataSave.getConfigJson());
            }
        }
        return false;
    }
}

+ 129 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/save/es/ElastricSearchSave.java

@ -0,0 +1,129 @@
package com.yihu.quota.etl.save.es;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.etl.save.LargDataWithRunnable;
import com.yihu.quota.etl.util.EsClientUtil;
import com.yihu.quota.vo.SaveModel;
import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
;
/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class ElastricSearchSave {
    private Logger logger = LoggerFactory.getLogger(ElastricSearchSave.class);
    @Autowired
    private EsClientUtil esClientUtil;
    private EsConfig esConfig;
    public Boolean saveByMoreThred(List<SaveModel> saveModels, String jsonConfig) {
        boolean isSuccessed = true;
        try {
            int perCount = Contant.compute.perCount;
            if(saveModels.size() > perCount){
                int count  = saveModels.size()/perCount;
                int remainder = saveModels.size()%perCount;
                if(remainder != 0){
                    count ++;
                }
                for(int i=0; i< count; i++){
                    int totalCount = saveModels.size();
                    int start = 0;
                    int end = perCount - 1;
                    if( i!=0 ){
                        start = i * perCount;
                        if((i + 1) * perCount >= totalCount){
                            end = totalCount-1;
                        }else {
                            end = (i + 1) * perCount-1;
                        }
                    }
                    logger.info("data save 这是第" + (i+1) + "个线程;数据 = " + start+ " - " + end);
                    List<SaveModel> list = saveModels.subList(start, end);
                    LargDataWithRunnable dataWithRunnable = new LargDataWithRunnable(list,jsonConfig,esClientUtil);
                    Thread thread = new Thread(dataWithRunnable);
                    thread.start();
                }
            }else {
                save(saveModels,jsonConfig);
            }
        } catch (Exception e) {
            throw new RuntimeException("ES 保存数据异常");
        }
        return  isSuccessed;
    }
    public Boolean save(List<SaveModel> smss, String jsonConfig) {
        BulkResult br = null;
        boolean isSuccessed = false;
        try {
            int perCount = Contant.compute.perCount;
            //初始化参数
            esConfig = (EsConfig) JSONObject.toBean(JSONObject.fromObject(jsonConfig), EsConfig.class);
            if(smss.size() > perCount){
                int count  = smss.size()/perCount;
                int remainder = smss.size()%perCount;
                if(remainder != 0){
                    count ++;
                }
                for(int i = 1;i<= count ;i++){
                    List<SaveModel> newList = null;
                    if(i == count){
                        newList = smss.subList(perCount*(i-1),smss.size() -1);
                    }else {
                        newList = smss.subList(perCount*(i-1),perCount*i);
                    }
                    //得到链接
                    JestClient jestClient = esClientUtil.getJestClient(esConfig.getHost(),esConfig.getPort());
                    Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esConfig.getIndex()).defaultType(esConfig.getType());
                    for (SaveModel obj : newList) {
                        obj.setCreateTime( new Date());
                        Index index = new Index.Builder(obj).build();
                        bulk.addAction(index);
                    }
                    br = jestClient.execute(bulk.build());
                    //关闭链接
                    jestClient.shutdownClient();
                    isSuccessed = br.isSucceeded();
                }
            }else{
                //得到链接
                JestClient jestClient = esClientUtil.getJestClient(esConfig.getHost(),esConfig.getPort());
                Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esConfig.getIndex()).defaultType(esConfig.getType());
                for (SaveModel obj : smss) {
                    obj.setCreateTime( new Date());
                    Index index = new Index.Builder(obj).build();
                    bulk.addAction(index);
                }
                br = jestClient.execute(bulk.build());
                //关闭链接
                jestClient.shutdownClient();
                isSuccessed = br.isSucceeded();
            }
            return isSuccessed;
        } catch (Exception e) {
            throw new RuntimeException("ES 保存数据异常"+ e.getMessage());
        }
    }
}

+ 403 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/util/ElasticsearchUtil.java

@ -0,0 +1,403 @@
package com.yihu.quota.etl.util;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.parser.ParserException;
import com.alibaba.druid.sql.parser.SQLExprParser;
import com.alibaba.druid.sql.parser.Token;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.elasticsearch.ElasticSearchPool;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.search.aggregations.metrics.sum.SumBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.InternalValueCount;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.nlpcn.es4sql.domain.Select;
import org.nlpcn.es4sql.jdbc.ObjectResult;
import org.nlpcn.es4sql.jdbc.ObjectResultsExtractor;
import org.nlpcn.es4sql.parse.ElasticSqlExprParser;
import org.nlpcn.es4sql.parse.SqlParser;
import org.nlpcn.es4sql.query.AggregationQueryAction;
import org.nlpcn.es4sql.query.DefaultQueryAction;
import org.nlpcn.es4sql.query.SqlElasticSearchRequestBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
/**
 * Created by janseny on 2017/7/21.
 */
@Component
public class ElasticsearchUtil {
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private ElasticSearchPool elasticSearchPool;
    /**
     * @param boolQueryBuilder  查询参数 build
     * @param pageNo
     * @param pageSize
     * @param sortName 排序字段名称
     * @return
     */
    public List<Map<String, Object>> queryPageList(Client client, String index, String type, BoolQueryBuilder boolQueryBuilder,
                                                   int pageNo, int pageSize, String sortName){
        SearchResponse actionGet = null;
        SortBuilder dealSorter = SortBuilders.fieldSort(sortName).order(SortOrder.DESC);
        actionGet = client.prepareSearch(index)
                .setTypes(type)
                .setQuery(boolQueryBuilder)
                .setFrom(pageNo - 1).setSize(pageSize).addSort(dealSorter)//从0开始算
                .execute().actionGet();
        SearchHits hits = actionGet.getHits();
        List<Map<String, Object>> matchRsult = new LinkedList<Map<String, Object>>();
        for (SearchHit hit : hits.getHits()){
            matchRsult.add(hit.getSource());
        }
        return matchRsult;
    }
    /**
     * @param boolQueryBuilder  查询参数 build
     * @return
     */
    public long getTotalCount(Client client,String index,String type,BoolQueryBuilder boolQueryBuilder){
        SearchResponse actionGet = null;
        actionGet = client.prepareSearch(index)
                .setTypes(type)
                .setQuery(boolQueryBuilder)
                .execute().actionGet();
        SearchHits hits = actionGet.getHits();
       if(hits != null){
           return hits.totalHits();
       }
        return 0;
    }
    /**
     * @param boolQueryBuilder  查询参数 build
     * @param sortName 排序字段名称
     * @return
     */
    public List<Map<String, Object>> queryList(Client client,String index,String type,BoolQueryBuilder boolQueryBuilder,String sortName,int size){
        SearchResponse actionGet = null;
        SortBuilder dealSorter = null;
        if(sortName != null){
            dealSorter = SortBuilders.fieldSort(sortName).order(SortOrder.DESC);
        }else{
            dealSorter = SortBuilders.fieldSort("_id").order(SortOrder.DESC);
        }
        actionGet = client.prepareSearch(index)
                .setTypes(type)
                .setSize(size)
                .setQuery(boolQueryBuilder)
                .addSort(dealSorter)
                .execute().actionGet();
        SearchHits hits = actionGet.getHits();
        List<Map<String, Object>> matchRsult = new LinkedList<Map<String, Object>>();
        for (SearchHit hit : hits.getHits()){
            Map<String, Object> map = new HashMap<>() ;
            map = hit.getSource();
            map.put("id",hit.getId());
            matchRsult.add(map);
        }
        return matchRsult;
    }
    /**
     * 执行搜索(带分组求和sum)
     * @param queryBuilder 查询内容
     * @param aggsField 要分组的字段
     * @param sumField 要求和的字段  只支持一个字段
     * @return
     */
    public List<Map<String, Object>> searcherByGroup(Client client, String index, String type, BoolQueryBuilder queryBuilder, String aggsField , String sumField) {
        List<Map<String, Object>> list = new ArrayList<>();
        SearchRequestBuilder searchRequestBuilder =
                client.prepareSearch(index)
                .setTypes(type)
                .setQuery(queryBuilder);
        //创建TermsBuilder对象,使用term查询,设置该分组的名称为 name_count,并根据aggsField字段进行分组
        TermsBuilder termsBuilder = AggregationBuilders.terms(aggsField+"_val").field(aggsField);
        SumBuilder ageAgg = AggregationBuilders.sum(sumField+"_count").field(sumField);
        searchRequestBuilder.addAggregation(termsBuilder.subAggregation(ageAgg));
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //执行搜索
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        //解析返回数据,获取分组名称为aggs-class的数据
        Terms terms = searchResponse.getAggregations().get(aggsField+"_val");
        Collection<Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKey().toString();
            if (bucket.getAggregations().asList().get(0) instanceof InternalSum) {//(sum(xx))
                InternalSum count = (InternalSum) bucket.getAggregations().asList().get(0);
                dataMap.put(key, count.value());
            }
        }
        list.add(dataMap);
        return list;
    }
    /**
     * 根据mysql 语句进行分组求和查询
     * @param client
     * @param index 索引名称
     * @param aggsFields 分组字段 支持多个
     * @param filter 条件
     * @param sumField  求和字段
     * @param orderFild 排序字段
     * @param order 排序 asc,desc
     * @return
     */
    public Map<String, Integer> searcherSumByGroupBySql(Client client,String index, String aggsFields ,String filter , String sumField,String orderFild,String order) throws Exception {
        Map<String,Integer> map = new LinkedHashMap<>();
//       String mysql1 = "select org ,sum(result) from quota where quotaCode='depart_treat_count' group by org  ";id=16
        StringBuffer mysql = new StringBuffer("select ");
        mysql.append(aggsFields)
             .append(" ,sum(").append(sumField).append(") ")
             .append(" from ").append(index)
             .append(" where ").append(filter)
             .append(" group by ").append(aggsFields);
        if (StringUtils.isNotEmpty(orderFild) && StringUtils.isNotEmpty(order)){
            mysql.append(" order by ").append(orderFild).append(" ").append(order);
        }
        System.out.println("查询分组 mysql= " + mysql.toString());
        SQLExprParser parser = new ElasticSqlExprParser(mysql.toString());
        SQLExpr expr = parser.expr();
        if (parser.getLexer().token() != Token.EOF) {
            throw new ParserException("illegal sql expr : " + mysql);
        }
        SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
        //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
        Select select = null;
        select = new SqlParser().parseSelect(queryExpr);
        AggregationQueryAction action = null;
        DefaultQueryAction queryAction = null;
        SqlElasticSearchRequestBuilder requestBuilder = null;
        if (select.isAgg) {
            //包含计算的的排序分组的
            action = new AggregationQueryAction(client, select);
            requestBuilder = action.explain();
        } else {
            //封装成自己的Select对象
            queryAction = new DefaultQueryAction(client, select);
            requestBuilder = queryAction.explain();
        }
        //之后就是对ES的操作
        SearchResponse response = (SearchResponse) requestBuilder.get();
        StringTerms stringTerms = (StringTerms) response.getAggregations().asList().get(0);
        Iterator<Terms.Bucket> gradeBucketIt = stringTerms.getBuckets().iterator();
        //里面存放的数据 例  350200-5-2-2    主维度  细维度1  细维度2  值
        //递归解析json
        expainJson(gradeBucketIt, map, null);
        return map;
    }
    /**
     *
     * @param client
     * @param source 表字段组合json格式
     * @return
     * @throws JsonProcessingException
     */
    public boolean save(Client client,String index,String type,String source) throws JsonProcessingException {
        IndexResponse indexResponse = client
                .prepareIndex(index, type, null)
                .setSource(source).get();
        boolean result =  indexResponse.isCreated();
        return result;
    }
    /**
     * 查询后 存在 删除
     * @param boolQueryBuilder
     */
    public synchronized  boolean queryDelete(Client client,String index,String type,BoolQueryBuilder boolQueryBuilder){
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        DeleteRequestBuilder deleteRequestBuilder = null ;
        SearchResponse actionGet = null;
        actionGet = client.prepareSearch(index)
                .setTypes(type)
                .setSize(10000)
                .setQuery(boolQueryBuilder)
                .execute().actionGet();
        SearchHits hits = actionGet.getHits();
        for (SearchHit hit : hits.getHits()){
            deleteRequestBuilder = client.prepareDelete(index, type, hit.getId());
            bulkRequestBuilder.add(deleteRequestBuilder.request());
        }
        //进行批量删除操作
        boolean optFlag = true;
        if(hits.getHits() != null && hits.getHits().length > 0){
            BulkResponse bulkResponse = bulkRequestBuilder.execute().actionGet();
            if (bulkResponse.hasFailures()) {
                optFlag = false;
            }else {
                optFlag = true;
            }
        }
        return  optFlag;
    }
    /**
     * 递归解析json
     *
     * @param gradeBucketIt
     * @param map
     * @param sb
     */
    private void expainJson(Iterator<Terms.Bucket> gradeBucketIt,Map<String,Integer> map, StringBuffer sb) {
        while (gradeBucketIt.hasNext()) {
            Terms.Bucket b =  gradeBucketIt.next();
            if (b.getAggregations().asList().get(0) instanceof StringTerms) {
                StringTerms stringTermsCh = (StringTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = stringTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof LongTerms) {
                LongTerms longTermsCh = (LongTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = longTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof DoubleTerms) {
                DoubleTerms doubleTermsCh = (DoubleTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = doubleTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof InternalValueCount) {//count(8)
                InternalValueCount count = (InternalValueCount) b.getAggregations().asList().get(0);
                StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                map.put(sbTemp.toString() , (int)count.getValue());
            }else if (b.getAggregations().asList().get(0) instanceof InternalSum) {//(sum(xx))
                InternalSum count = (InternalSum) b.getAggregations().asList().get(0);
                StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                map.put(sbTemp.toString() , (int)count.getValue());
            }
        }
    }
    /**
     * 执行sql查询es
     * @param sql
     * @return
     */
    public List<Map<String, Object>> excuteDataModel(String sql) {
        List<Map<String, Object>> returnModels = new ArrayList<>();
        TransportClient client = elasticSearchPool.getClient();
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(client, select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(client, select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            Object queryResult = null;
            if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1 || sql.toUpperCase().indexOf("COUNT") != -1) {
                queryResult = response.getAggregations();
            } else {
                queryResult = response.getHits();
            }
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
            List<String> heads = temp.getHeaders();
            temp.getLines().stream().forEach(one -> {
                try {
                    Map<String, Object> oneMap = new HashMap<String, Object>();
                    for (int i = 0; i < one.size(); i++) {
                        String key = null;
                        Object value = one.get(i);
                        key = heads.get(i);
                        oneMap.put(key, value);
                    }
                    returnModels.add(oneMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnModels;
    }
    public long getCountBySql(String sql) {
        TransportClient client = elasticSearchPool.getClient();
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(client, select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(client, select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            SearchHits hits = response.getHits();
            if(hits != null){
                return hits.totalHits();
            }
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}

+ 59 - 0
svr/svr-quota/src/main/java/com/yihu/quota/etl/util/EsClientUtil.java

@ -0,0 +1,59 @@
package com.yihu.quota.etl.util;
import com.yihu.quota.etl.extract.es.EsExtract;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.net.InetAddress;
/**
* Created by janseny on 2017/8/1
 */
@Component
public class EsClientUtil {
    private Logger logger = LoggerFactory.getLogger(EsExtract.class);
    /**
     * @param host "localhost"
     * @param port 9200
     * @return
     */
    public JestClient getJestClient(String host, Integer port) {
        String hostAddress="http://"+host+":"+port;
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder(hostAddress)
                .multiThreaded(true)
                //.discoveryEnabled(true)
                .readTimeout(60000)//30秒 -60s
                .build());
        return factory.getObject();
    }
    public Client getClient(String host, Integer port,String clusterName) {
        try {
            Settings settings = Settings.settingsBuilder()
                    .put("cluster.name", StringUtils.isEmpty(clusterName)?"elasticsearch":clusterName)
                    .put("client.transport.sniff", false)
                    .build();
            Client client = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

+ 333 - 0
svr/svr-quota/src/main/java/com/yihu/quota/job/EsQuotaJob.java

@ -0,0 +1,333 @@
package com.yihu.quota.job;
import com.yihu.ehr.elasticsearch.ElasticSearchPool;
import com.yihu.quota.dao.jpa.TjQuotaLogDao;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.etl.extract.ExtractHelper;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.etl.save.SaveHelper;
import com.yihu.quota.etl.util.ElasticsearchUtil;
import com.yihu.quota.model.jpa.TjQuotaLog;
import com.yihu.quota.model.jpa.source.TjQuotaDataSource;
import com.yihu.quota.service.source.TjDataSourceService;
import com.yihu.quota.util.SpringUtil;
import com.yihu.quota.vo.QuotaVo;
import com.yihu.quota.vo.SaveModel;
import net.sf.json.JSONObject;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.*;
import org.joda.time.LocalDate;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2017/6/6.
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class EsQuotaJob implements Job {
    private Logger logger = LoggerFactory.getLogger(EsQuotaJob.class);
    private String saasid; // saasid
    private QuotaVo quotaVo = new QuotaVo(); // 指标对象
    private String endTime; // 结束时间
    private String startTime; //开始时间
    private String timeLevel; //时间
    private String executeFlag; // 执行动作 1 手动执行 2 周期执行
    private int haveThreadCount = 0;//已完成线程数
    private int threadCount = 1;//总线程数
    @Autowired
    private TjQuotaLogDao tjQuotaLogDao;
    @Autowired
    private ExtractHelper extractHelper;
    @Autowired
    ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private ElasticSearchPool elasticSearchPool;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private TjDataSourceService dataSourceService;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        TjQuotaLog tjQuotaLog = new TjQuotaLog();
        String time = "";
        try {
            //springz注入
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            initParams(context);
            quotaVo.setExecuteFlag(executeFlag);
            logger.warn("开始执行指标" + quotaVo.getCode());
            tjQuotaLog.setQuotaCode(quotaVo.getCode());
            tjQuotaLog.setSaasId(saasid);
            tjQuotaLog.setStartTime(new Date());
            tjQuotaLog.setStatus( Contant.save_status.executing);  //指标执行中
            tjQuotaLog.setContent( "时间:" + startTime + "到"+ endTime +" , " + "任务执行中。");
            tjQuotaLog = saveLog(tjQuotaLog);
            time = "时间:" + startTime + "到"+ endTime +" , ";
            TjQuotaDataSource quotaDataSource = dataSourceService.findSourceByQuotaCode(quotaVo.getCode());
            if (quotaDataSource == null) {
                throw new Exception("数据源配置错误");
            }
            JSONObject obj = new JSONObject().fromObject(quotaDataSource.getConfigJson());
            EsConfig esConfig = (EsConfig) JSONObject.toBean(obj,EsConfig.class);
            //查询是否已经统计过,如果已统计 先删除后保存
            deleteRecord(quotaVo);
            if(quotaDataSource.getSourceCode().equals("2") && esConfig.getAggregation()!= null && esConfig.getAggregation().equals("list")) {//来源solr
               /* moreThredQuota(tjQuotaLog,esConfig);*/
            }else{
                //统计并保存
                quota(tjQuotaLog, quotaVo);
            }
        } catch (Exception e) {
            //如果出錯立即重新執行
            tjQuotaLog.setStatus(Contant.save_status.fail);
            tjQuotaLog.setEndTime(new Date());
            tjQuotaLog.setContent( time+"统计异常," + e.getMessage());
            saveLog(tjQuotaLog);
            JobExecutionException e2 = new JobExecutionException(e);
            e2.setRefireImmediately(true);
            e.printStackTrace();
        }
    }
    /*
     * solr list 方式 多线程执行指标
     *//*
    public void moreThredQuota(TjQuotaLog tjQuotaLog, EsConfig esConfig){
        try {
            int perCount = Contant.compute.perCount;
            quotaVo.setStart(0);
            quotaVo.setRows(perCount);
            int rows = solrExtract.getExtractTotal(startTime,endTime, esConfig);
            if(rows > perCount*50){
                throw new Exception("数据量过大请缩小抽取时间范围");
            }
            if (rows > perCount) {
                int count  = rows/perCount;
                int remainder = rows % perCount;
                if(remainder != 0){
                    count ++;
                }else {
                    remainder = perCount;
                }
                threadCount = count;
                for (int i = 0; i < count; i++) {
                    //防止过快执行导致参数被覆盖
                    Thread.sleep(1000);
                    final int f = i;//传值用。
                    final TjQuotaLog quotaLogf = tjQuotaLog;//传值用。
                    final QuotaVo quotaVof = quotaVo;//传值用。
                    if (f != 0){
                        quotaVof.setStart(f*perCount);
                    }else {
                        quotaVof.setStart(0);
                    }
                    if(i+1 == count){
                        quotaVof.setRows(remainder);
                    }else {
                        quotaVof.setRows(perCount);
                    }
                    Thread th = new Thread(new Thread(){
                        public synchronized void run(){
                            logger.warn("启动第 "+ (f+1) + " 个线程。 ");//只能访问外部的final变量。
                            quota(quotaLogf, quotaVof);
                        }
                    });
                    Thread.sleep(10000);//延迟10 秒 Es 保存2万条 有时超时,延迟执行减缓个线程同时执行的压力
                    th.start();
                }
            }else {
                //统计并保存
                quota(tjQuotaLog, quotaVo);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/
    /**
     * 统计过程
     */
    public void quota(TjQuotaLog tjQuotaLog,QuotaVo quotaVo) {
        String time = "时间:" + startTime + "到"+ endTime +" , ";
        String status = "";
        String content = "";
        try {
            //抽取数据
            List<SaveModel> dataModels = extract(quotaVo);
            if (dataModels != null && dataModels.size() > 0) {
                //保存数据
                Boolean success = saveData(dataModels,quotaVo);
                status = success ? Contant.save_status.success : Contant.save_status.fail;
                content = success ? time+"统计保存成功" : time+"统计保存失败";
                logger.info(content + dataModels.size());
                haveThreadCount++;
            } else {
                status = Contant.save_status.success;
                content = "没有抽取到数据" + time ;
                haveThreadCount++;
            }
            // 初始执行时,更新该指标为已初始执行过
            if (quotaVo.getExecuteFlag().equals("1")) {
                String sql = "UPDATE tj_quota SET is_init_exec = '1' WHERE id = " + quotaVo.getId();
                jdbcTemplate.update(sql);
            }
        } catch (Exception e) {
            haveThreadCount++;
            tjQuotaLog.setStatus(Contant.save_status.fail);
            tjQuotaLog.setContent(e.getMessage());
            tjQuotaLog = saveLog(tjQuotaLog);
            e.printStackTrace();
        }
        if(threadCount > 1){
            if(haveThreadCount  == threadCount){
                tjQuotaLog.setStatus(Contant.save_status.success);
                tjQuotaLog.setContent(time+"统计保存成功");
                logger.warn("指标" + tjQuotaLog.getQuotaCode() + "统计成功 结束!");
            }else {
                tjQuotaLog.setStatus(Contant.save_status.fail);
                tjQuotaLog.setContent( time+"统计保存失败");
            }
            tjQuotaLog.setEndTime(new Date());
            saveLog(tjQuotaLog);
        }else {
            tjQuotaLog.setStatus(status);
            tjQuotaLog.setContent(content);
            tjQuotaLog.setEndTime(new Date());
            saveLog(tjQuotaLog);
            logger.warn("结束!" + content);
        }
    }
    private void deleteRecord(QuotaVo quotaVo) throws Exception {
        EsConfig esConfig = extractHelper.getEsConfig(quotaVo.getCode());
        EsConfig sourceEsConfig = extractHelper.getDataSourceEsConfig(quotaVo.getCode());
        String start = "";
        String end = "";
        if(sourceEsConfig.getFullQuery() !=null && sourceEsConfig.getFullQuery().equals("true")){
            start = LocalDate.now().toString();
            end = start;
        }else {
            if (!StringUtils.isEmpty(startTime)) {
                start = startTime;
            }
            if (!StringUtils.isEmpty(endTime)) {
                end = endTime;
            }
        }
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        RangeQueryBuilder rangeQuotaTime = QueryBuilders.rangeQuery("quotaDate").gte(start.substring(0, 10)).lte(end.substring(0, 10));
        RangeQueryBuilder rangeCreateTime = QueryBuilders.rangeQuery("createDate").gte(start.substring(0, 10) + "T00:00:00+0800").lte(end.substring(0, 10) + "T23:59:59+0800");
        String quotaCodeTerm = "quotaCode:" + quotaVo.getCode().replaceAll("_", "");
        QueryStringQueryBuilder termQueryQuotaCode = QueryBuilders.queryStringQuery(quotaCodeTerm);
        QueryBuilder qb = QueryBuilders.boolQuery()
                .must(termQueryQuotaCode)
                .must(QueryBuilders.boolQuery()
                        .should(rangeQuotaTime)
                        .should(rangeCreateTime)
                );
        boolQueryBuilder.filter(qb);
        boolean flag = true ;
        Client talClient = elasticSearchPool.getClient();
        Client client = elasticSearchPool.getClient();
        try {
            while (flag){
                long count = elasticsearchUtil.getTotalCount(talClient, esConfig.getIndex() ,esConfig.getType(), boolQueryBuilder);
                if(count != 0){
                    boolean successFlag = elasticsearchUtil.queryDelete(client, esConfig.getIndex() ,esConfig.getType(),boolQueryBuilder);
                    if(!successFlag){
                        throw  new Exception("Elasticsearch 指标统计时原始数据删除失败");
                    }
                }else {
                    flag = false ;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw  new Exception("Elasticsearch 指标统计时原始数据删除异常");
        } finally {
            talClient.close();
            client.close();
            logger.debug(quotaVo.getCode()+" delete success");
        }
    }
    /**
     * 抽取数据
     * @return
     */
    private List<SaveModel> extract(QuotaVo quotaVo) throws Exception {
        return SpringUtil.getBean(ExtractHelper.class).extractData(quotaVo, startTime, endTime, timeLevel, saasid);
    }
    /**
     * 初始化参数
     * @param context
     */
    private void initParams(JobExecutionContext context) {
        JobDataMap map = context.getJobDetail().getJobDataMap();
        Map<String, Object> params = context.getJobDetail().getJobDataMap();
        Object object = map.get("quota");
        if (object != null) {
            BeanUtils.copyProperties(object, this.quotaVo);
        }
        this.saasid = map.getString("saasid");
        // 默认按天,如果指标有配置时间维度,ES抽取过程中维度字典项转换为 SaveModel 时再覆盖。
        this.timeLevel = Contant.main_dimension_timeLevel.day;
        this.executeFlag = map.getString("executeFlag");
        if ("2".equals(executeFlag)) {
            if (StringUtils.isEmpty(map.getString("startTime"))) {
                startTime = Contant.main_dimension_timeLevel.getStartTime(timeLevel);
            } else {
                this.startTime = map.getString("startTime").split("T")[0] + "T00:00:00Z";
            }
            if (StringUtils.isEmpty(map.getString("endTime"))) {
                endTime = LocalDate.now().toString("yyyy-MM-dd'T'00:00:00'Z'");
            } else {
                this.endTime = map.getString("endTime").split("T")[0] + "T23:59:59Z";
            }
        }
    }
    @Transactional
     TjQuotaLog saveLog(TjQuotaLog tjQuotaLog) {
        TjQuotaLog log =  tjQuotaLogDao.save(tjQuotaLog);
        return  log;
    }
    /**
     * 保存数据
     *
     * @param dataModels
     */
    private Boolean saveData(List<SaveModel> dataModels,QuotaVo quotaVo) {
        try {
            return SpringUtil.getBean(SaveHelper.class).save(dataModels, quotaVo);
        } catch (Exception e) {
            logger.error("save error:" + e.getMessage());
        }
        return false;
    }
}

+ 190 - 0
svr/svr-quota/src/main/java/com/yihu/quota/job/EsQuotaPercentJob.java

@ -0,0 +1,190 @@
package com.yihu.quota.job;
import com.yihu.quota.dao.jpa.TjQuotaLogDao;
import com.yihu.quota.etl.Contant;
import com.yihu.quota.etl.extract.ExtractHelper;
import com.yihu.quota.etl.extract.ExtractPercentHelper;
import com.yihu.quota.etl.model.EsConfig;
import com.yihu.quota.etl.save.SaveHelper;
import com.yihu.quota.etl.util.ElasticsearchUtil;
import com.yihu.quota.etl.util.EsClientUtil;
import com.yihu.quota.model.jpa.TjQuotaLog;
import com.yihu.quota.util.SpringUtil;
import com.yihu.quota.vo.QuotaVo;
import com.yihu.quota.vo.SaveModel;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.joda.time.LocalDate;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by janseny on 2017/8/22.
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class EsQuotaPercentJob implements Job {
    private Logger logger = LoggerFactory.getLogger(EsQuotaPercentJob.class);
    private QuotaVo quotaVo = new QuotaVo();//指标对象
    private String endTime;//结束时间
    private String startTime;//开始时间
    private String timeLevel;//时间
    private String molecular;//分子
    private String denominator;//分母
    @Autowired
    private TjQuotaLogDao tjQuotaLogDao;
    @Autowired
    private EsClientUtil esClientUtil;
    @Autowired
    private ExtractHelper extractHelper;
    @Autowired
    ElasticsearchUtil elasticsearchUtil;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            //springz注入
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            initParams(context);
            //统计
            quota();
        } catch (Exception e) {
            //如果出錯立即重新執行
            JobExecutionException e2 = new JobExecutionException(e);
            e2.setRefireImmediately(true);
            e.printStackTrace();
        }
    }
    /**
     * 统计过程
     */
    private void quota() {
        TjQuotaLog tjQuotaLog = new TjQuotaLog();
        tjQuotaLog.setQuotaCode(quotaVo.getCode());
        tjQuotaLog.setStartTime(new Date());
        String message = "";
        try {
            //抽取数据计算数据
            List<SaveModel> dataModels = extract();
            if(dataModels != null && dataModels.size() > 0){
                //查询是否已经统计过,如果已统计 先删除后保存
                EsConfig esConfig = extractHelper.getEsConfig(quotaVo.getCode());
                BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
                QueryStringQueryBuilder termQueryQuotaCode = QueryBuilders.queryStringQuery("quotaCode:" + quotaVo.getCode().replaceAll("_", ""));
                boolQueryBuilder.must(termQueryQuotaCode);
                if( !StringUtils.isEmpty(startTime) ){
                    RangeQueryBuilder rangeQueryStartTime = QueryBuilders.rangeQuery("quotaDate").gte(startTime);
                    boolQueryBuilder.must(rangeQueryStartTime);
                }
                if( !StringUtils.isEmpty(endTime)){
                    RangeQueryBuilder rangeQueryEndTime = QueryBuilders.rangeQuery("quotaDate").lte(endTime);
                    boolQueryBuilder.must(rangeQueryEndTime);
                }
                Client client = esClientUtil.getClient(esConfig.getHost(), esConfig.getPort(), esConfig.getClusterName());
                try {
                    elasticsearchUtil.queryDelete(client,esConfig.getIndex(),esConfig.getType(),boolQueryBuilder);
                }catch (Exception e){
                    e.getMessage();
                }finally {
                    client.close();
                }
                List<SaveModel> dataSaveModels = new ArrayList<>();
                for(SaveModel saveModel :dataModels){
                    if(saveModel.getResult() != null){
                        dataSaveModels.add(saveModel);
                    }
                }
                //保存数据
                Boolean success = saveDate(dataSaveModels);
                tjQuotaLog.setStatus(success ? Contant.save_status.success : Contant.save_status.fail);
                tjQuotaLog.setContent(success?"统计保存成功":"统计数据ElasticSearch保存失败");
            }else {
                tjQuotaLog.setStatus(Contant.save_status.fail);
                tjQuotaLog.setContent("没有抽取到数据");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            message = e.getMessage();
            tjQuotaLog.setStatus(Contant.save_status.fail);
            tjQuotaLog.setContent(message);
        }
        tjQuotaLog.setEndTime(new Date());
        saveLog(tjQuotaLog);
    }
    /**
     * 抽取数据
     *
     * @return
     */
    private List<SaveModel> extract() throws Exception {
        return SpringUtil.getBean(ExtractPercentHelper.class).extractData(quotaVo, startTime, endTime,timeLevel);
    }
    /**
     * 初始化参数
     *
     * @param context
     */
    private void initParams(JobExecutionContext context) {
        JobDataMap map = context.getJobDetail().getJobDataMap();
        this.molecular =  map.getString("molecular");
        this.denominator =  map.getString("denominator");
        this.endTime = map.getString("endTime");
        if (StringUtils.isEmpty(endTime)) {
            endTime = LocalDate.now().toString("yyyy-MM-dd"); //2017-06-01 默认今天
        }
        this.startTime = map.getString("startTime");
        if (StringUtils.isEmpty(startTime)) {
            startTime = Contant.main_dimension_timeLevel.getStartTime(timeLevel);//默认是昨天
        }
        this.timeLevel = (String) map.get("timeLevel");
        if (StringUtils.isEmpty(this.timeLevel)) {
            this.timeLevel = Contant.main_dimension_timeLevel.day;
        }
        Object object =  map.get("quota");
        if(object!=null){
            BeanUtils.copyProperties(object, this.quotaVo);
        }
    }
    @Transactional
    private void saveLog(TjQuotaLog tjQuotaLog) {
        tjQuotaLogDao.save(tjQuotaLog);
    }
    /**
     * 保存数据
     * @param dataModels
     */
    private Boolean saveDate(List<SaveModel> dataModels) {
        try {
            return SpringUtil.getBean(SaveHelper.class).save(dataModels, quotaVo);
        } catch (Exception e) {
            logger.error("save error:" + e.getMessage());
        }
        return false;
    }
}

+ 106 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/RsResourceQuota.java

@ -0,0 +1,106 @@
package com.yihu.quota.model.jpa;
import javax.persistence.*;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2017/12/19.
 */
@Entity
@Table(name="rs_resource_quota")
public class RsResourceQuota {
    private int id;
    private String resourceId;
    private String quotaTypeName;
    private String quotaCode;
    private int quotaChart;
    private int quotaId;
    private Integer pid;
    private List<RsResourceQuota> children;
    private List<Map<String, Object>> mapList;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @Column(name = "resource_id")
    public String getResourceId() {
        return resourceId;
    }
    public void setResourceId(String resourceId) {
        this.resourceId = resourceId;
    }
    @Column(name = "quota_type_name")
    public String getQuotaTypeName() {
        return quotaTypeName;
    }
    public void setQuotaTypeName(String quotaTypeName) {
        this.quotaTypeName = quotaTypeName;
    }
    @Column(name = "quota_code")
    public String getQuotaCode() {
        return quotaCode;
    }
    public void setQuotaCode(String quotaCode) {
        this.quotaCode = quotaCode;
    }
    @Column(name = "quota_chart")
    public int getQuotaChart() {
        return quotaChart;
    }
    public void setQuotaChart(int quotaChart) {
        this.quotaChart = quotaChart;
    }
    @Column(name = "quota_id")
    public int getQuotaId() {
        return quotaId;
    }
    public void setQuotaId(int quotaId) {
        this.quotaId = quotaId;
    }
    @Column(name = "pid")
    public Integer getPid() {
        return pid;
    }
    public void setPid(Integer pid) {
        this.pid = pid;
    }
    @Transient
    public List<RsResourceQuota> getChildren() {
        return children;
    }
    public void setChildren(List<RsResourceQuota> children) {
        this.children = children;
    }
    @Transient
    public List<Map<String, Object>> getMapList() {
        return mapList;
    }
    public void setMapList(List<Map<String, Object>> mapList) {
        this.mapList = mapList;
    }
}

+ 229 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/TjQuota.java

@ -0,0 +1,229 @@
package com.yihu.quota.model.jpa;// default package
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.util.Date;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjQuota entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_quota")
public class TjQuota implements java.io.Serializable {
	// Fields
	private Integer id;
	private String code;
	private String name;
	private String cron;//quartz时间表达式
	private String execType;
	private String jobClazz; //类class
	private String dataLevel;//1 全量  2增量
	private Date createTime;
	private String createUser;
	private String createUserName;
	private Date updateTime;
	private String updateUser;
	private String updateUserName;
	private String status;//1: 正常 0:不可用  -1删除
	private String remark;
	private String resultGetType; // 指标结果获取方式 1:直接库中获取,2:二次统计获取。
	//周期指标执行状态:0未开启,1执行中
	private String jobStatus;
	// Constructors
	/** default constructor */
	public TjQuota() {
	}
	/** minimal constructor */
	public TjQuota(Date createTime, Date updateTime) {
		this.createTime = createTime;
		this.updateTime = updateTime;
	}
	/** full constructor */
	public TjQuota(String code, String name, String jobClazz,
				   Date createTime, String createUser, String createUserName,
				   Date updateTime, String updateUser, String updateUserName,
				   String status, String remark,String dataLevel ,String cron ,String execType, String jobStatus) {
		this.code = code;
		this.name = name;
		this.jobClazz = jobClazz;
		this.createTime = createTime;
		this.createUser = createUser;
		this.createUserName = createUserName;
		this.updateTime = updateTime;
		this.updateUser = updateUser;
		this.updateUserName = updateUserName;
		this.status = status;
		this.jobStatus = jobStatus;
		this.remark = remark;
		this.dataLevel = dataLevel;
		this.cron = cron;
		this.execType = execType;
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "code", length = 100)
	public String getCode() {
		return this.code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Column(name = "name", length = 200)
	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name = "job_clazz", length = 500)
	public String getJobClazz() {
		return this.jobClazz;
	}
	public void setJobClazz(String jobClazz) {
		this.jobClazz = jobClazz;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "create_time", nullable = false, length = 0)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	public Date getCreateTime() {
		return this.createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	@Column(name = "create_user", length = 100)
	public String getCreateUser() {
		return this.createUser;
	}
	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}
	@Column(name = "create_user_name", length = 50)
	public String getCreateUserName() {
		return this.createUserName;
	}
	public void setCreateUserName(String createUserName) {
		this.createUserName = createUserName;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "update_time", nullable = false, length = 0)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	public Date getUpdateTime() {
		return this.updateTime;
	}
	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}
	@Column(name = "update_user", length = 100)
	public String getUpdateUser() {
		return this.updateUser;
	}
	public void setUpdateUser(String updateUser) {
		this.updateUser = updateUser;
	}
	@Column(name = "update_user_name", length = 50)
	public String getUpdateUserName() {
		return this.updateUserName;
	}
	public void setUpdateUserName(String updateUserName) {
		this.updateUserName = updateUserName;
	}
	@Column(name = "status", length = 1)
	public String getStatus() {
		return this.status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	@Column(name = "remark", length = 1500)
	public String getRemark() {
		return this.remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	@Column(name = "cron", length = 100)
	public String getCron() {
		return cron;
	}
	public void setCron(String cron) {
		this.cron = cron;
	}
	@Column(name = "data_level", length = 2)
	public String getDataLevel() {
		return dataLevel;
	}
	public void setDataLevel(String dataLevel) {
		this.dataLevel = dataLevel;
	}
	@Column(name = "exec_type", length = 1)
	public String getExecType() {
		return execType;
	}
	public void setExecType(String execType) {
		this.execType = execType;
	}
	@Column(name = "result_get_type", length = 2)
	public String getResultGetType() {
		return resultGetType;
	}
	public void setResultGetType(String resultGetType) {
		this.resultGetType = resultGetType;
	}
	@Column(name = "job_status", length = 1)
	public String getJobStatus() {
		return jobStatus;
	}
	public void setJobStatus(String jobStatus) {
		this.jobStatus = jobStatus;
	}
}

+ 119 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/TjQuotaGovProvision.java

@ -0,0 +1,119 @@
package com.yihu.quota.model.jpa;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
 * Created by wxw on 2018/3/6.
 */
@Entity
@Table(name = "tj_quota_gov_provision")
public class TjQuotaGovProvision implements Serializable {
    private long id;
    private long population;
    private String gender;
    private String year;
    private String district;
    private long administrativeDivision;
    private Date createDate;
    private String creator;
    private Date modifyDate;
    private String modifier;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    @Column(name = "population")
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    @Column(name = "year")
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    @Column(name = "district")
    public String getDistrict() {
        return district;
    }
    public void setDistrict(String district) {
        this.district = district;
    }
    @Column(name = "administrative_division")
    public long getAdministrativeDivision() {
        return administrativeDivision;
    }
    public void setAdministrativeDivision(long administrativeDivision) {
        this.administrativeDivision = administrativeDivision;
    }
    @Column(name = "create_date", nullable = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @Column(name = "modify_date")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
}

+ 88 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/TjQuotaLog.java

@ -0,0 +1,88 @@
package com.yihu.quota.model.jpa;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.util.Date;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * Created by chenweida on 2017/6/2.
 */
@Entity
@Table(name = "tj_quota_log")
public class TjQuotaLog {
    private Integer id;
    private String saasId;
    private String quotaCode;
    private Date startTime;
    private Date endTime;
    private String content;
    /**
     * 1成功 0失败,2执行中
      */
    private String status;
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getQuotaCode() {
        return quotaCode;
    }
    public void setQuotaCode(String quotaCode) {
        this.quotaCode = quotaCode;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getStartTime() {
        return startTime;
    }
    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getEndTime() {
        return endTime;
    }
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
}

+ 114 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dict/SystemDict.java

@ -0,0 +1,114 @@
package com.yihu.quota.model.jpa.dict;// default package
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * SystemDict entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "system_dict")
public class SystemDict implements java.io.Serializable {
	// Fields
	private Integer id;
	private String saasId;
	private String dictName;
	private String code;
	private String value;
	private String pyCode;
	private Integer sort;
	// Constructors
	/** default constructor */
	public SystemDict() {
	}
	/** minimal constructor */
	public SystemDict(String dictName, String code, String value) {
		this.dictName = dictName;
		this.code = code;
		this.value = value;
	}
	/** full constructor */
	public SystemDict(String saasId, String dictName, String code,
			String value, String pyCode, Integer sort) {
		this.saasId = saasId;
		this.dictName = dictName;
		this.code = code;
		this.value = value;
		this.pyCode = pyCode;
		this.sort = sort;
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "saas_id", length = 100)
	public String getSaasId() {
		return this.saasId;
	}
	public void setSaasId(String saasId) {
		this.saasId = saasId;
	}
	@Column(name = "dict_name", nullable = false, length = 50)
	public String getDictName() {
		return this.dictName;
	}
	public void setDictName(String dictName) {
		this.dictName = dictName;
	}
	@Column(name = "code", nullable = false, length = 50)
	public String getCode() {
		return this.code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Column(name = "value", nullable = false, length = 50)
	public String getValue() {
		return this.value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	@Column(name = "py_code", length = 50)
	public String getPyCode() {
		return this.pyCode;
	}
	public void setPyCode(String pyCode) {
		this.pyCode = pyCode;
	}
	@Column(name = "sort")
	public Integer getSort() {
		return this.sort;
	}
	public void setSort(Integer sort) {
		this.sort = sort;
	}
}

+ 152 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dict/SystemDictList.java

@ -0,0 +1,152 @@
package com.yihu.quota.model.jpa.dict;// default package
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 * SystemDictList entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "system_dict_list")
public class SystemDictList implements java.io.Serializable {
	// Fields
	private Integer id;
	private String dictName;
	private String chineseName;
	private String pyCode;
	private String pid;
	private String remark;
	private String relationTable;
	private String relationColCode;
	private String relationColValue;
	private String relationColExtend;
	// Constructors
	/** default constructor */
	public SystemDictList() {
	}
	/** minimal constructor */
	public SystemDictList(Integer id, String dictName, String chineseName,
			String pid) {
		this.id = id;
		this.dictName = dictName;
		this.chineseName = chineseName;
		this.pid = pid;
	}
	/** full constructor */
	public SystemDictList(Integer id, String dictName, String chineseName,
			String pyCode, String pid, String remark, String relationTable,
			String relationColCode, String relationColValue,
			String relationColExtend) {
		this.id = id;
		this.dictName = dictName;
		this.chineseName = chineseName;
		this.pyCode = pyCode;
		this.pid = pid;
		this.remark = remark;
		this.relationTable = relationTable;
		this.relationColCode = relationColCode;
		this.relationColValue = relationColValue;
		this.relationColExtend = relationColExtend;
	}
	// Property accessors
	@Id
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "dict_name", nullable = false, length = 50)
	public String getDictName() {
		return this.dictName;
	}
	public void setDictName(String dictName) {
		this.dictName = dictName;
	}
	@Column(name = "chinese_name", nullable = false, length = 50)
	public String getChineseName() {
		return this.chineseName;
	}
	public void setChineseName(String chineseName) {
		this.chineseName = chineseName;
	}
	@Column(name = "py_code", length = 50)
	public String getPyCode() {
		return this.pyCode;
	}
	public void setPyCode(String pyCode) {
		this.pyCode = pyCode;
	}
	@Column(name = "pid", nullable = false, length = 50)
	public String getPid() {
		return this.pid;
	}
	public void setPid(String pid) {
		this.pid = pid;
	}
	@Column(name = "remark", length = 200)
	public String getRemark() {
		return this.remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	@Column(name = "relation_table", length = 50)
	public String getRelationTable() {
		return this.relationTable;
	}
	public void setRelationTable(String relationTable) {
		this.relationTable = relationTable;
	}
	@Column(name = "relation_col_code", length = 50)
	public String getRelationColCode() {
		return this.relationColCode;
	}
	public void setRelationColCode(String relationColCode) {
		this.relationColCode = relationColCode;
	}
	@Column(name = "relation_col_value", length = 50)
	public String getRelationColValue() {
		return this.relationColValue;
	}
	public void setRelationColValue(String relationColValue) {
		this.relationColValue = relationColValue;
	}
	@Column(name = "relation_col_extend", length = 50)
	public String getRelationColExtend() {
		return this.relationColExtend;
	}
	public void setRelationColExtend(String relationColExtend) {
		this.relationColExtend = relationColExtend;
	}
}

+ 195 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dimension/TjDimensionMain.java

@ -0,0 +1,195 @@
package com.yihu.quota.model.jpa.dimension;// default package
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.util.Date;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjDimensionMain entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_dimension_main")
public class TjDimensionMain implements java.io.Serializable {
    // Fields
    private Integer id;
    private String code;
    private String name;
    private Date createTime;
    private String createUser;
    private String createUserName;
    private Date updateTime;
    private String updateUser;
    private String updateUserName;
    private Integer status;//1: 正常 0:不可以用 -1 已删除
    private String remark;
    /**
     * 主维度 :
     * 1 时间维度(日)
     * 2 时间维度(周)
     * 3.时间维度(月)
     * 4时间维度(年)
     * 5 行政区划维度(省)
     * 6行政区划维度(市)
     * 7行政区划维度(区县)
     * 8行政区划维度(机构)
     * 9行政区划维度(团队)
     */
    private String type;
    // Constructors
    /**
     * default constructor
     */
    public TjDimensionMain() {
    }
    /**
     * minimal constructor
     */
    public TjDimensionMain(Date createTime, Date updateTime) {
        this.createTime = createTime;
        this.updateTime = updateTime;
    }
    /**
     * full constructor
     */
    public TjDimensionMain(String code, String name, Date createTime,
                           String createUser, String createUserName, Date updateTime,
                           String updateUser, String updateUserName, Integer status,
                           String remark, String type) {
        this.code = code;
        this.name = name;
        this.createTime = createTime;
        this.createUser = createUser;
        this.createUserName = createUserName;
        this.updateTime = updateTime;
        this.updateUser = updateUser;
        this.updateUserName = updateUserName;
        this.status = status;
        this.remark = remark;
        this.type = type;
    }
    // Property accessors
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "code", length = 100)
    public String getCode() {
        return this.code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "name", length = 200)
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "create_time", nullable = false, length = 0)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateTime() {
        return this.createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @Column(name = "create_user", length = 100)
    public String getCreateUser() {
        return this.createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    @Column(name = "create_user_name", length = 50)
    public String getCreateUserName() {
        return this.createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "update_time", nullable = false, length = 0)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getUpdateTime() {
        return this.updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    @Column(name = "update_user", length = 100)
    public String getUpdateUser() {
        return this.updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
    @Column(name = "update_user_name", length = 50)
    public String getUpdateUserName() {
        return this.updateUserName;
    }
    public void setUpdateUserName(String updateUserName) {
        this.updateUserName = updateUserName;
    }
    @Column(name = "status")
    public Integer getStatus() {
        return this.status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    @Column(name = "remark", length = 1500)
    public String getRemark() {
        return this.remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @Column(name = "type", length = 10)
    public String getType() {
        return this.type;
    }
    public void setType(String type) {
        this.type = type;
    }
}

+ 172 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dimension/TjDimensionSlave.java

@ -0,0 +1,172 @@
package com.yihu.quota.model.jpa.dimension;// default package
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.util.Date;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjDimensionSlave entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_dimension_slave")
public class TjDimensionSlave implements java.io.Serializable {
	// Fields
	private Integer id;
	private String code;
	private String name;
	private Integer status;//1: 正常 0:不可以用 -1 已删除
	private String type;//// 维度 :1 性别 2年龄
	private Date createTime;
	private String createUser;
	private String createUserName;
	private Date updateTime;
	private String updateUser;
	private String updateUserName;
	private String remark;
	// Constructors
	/** default constructor */
	public TjDimensionSlave() {
	}
	/** minimal constructor */
	public TjDimensionSlave(Date createTime, Date updateTime) {
		this.createTime = createTime;
		this.updateTime = updateTime;
	}
	/** full constructor */
	public TjDimensionSlave(String code, String name,
			Date createTime, String createUser, String createUserName,
			Date updateTime, String updateUser, String updateUserName,
			String remark) {
		this.code = code;
		this.name = name;
		this.createTime = createTime;
		this.createUser = createUser;
		this.createUserName = createUserName;
		this.updateTime = updateTime;
		this.updateUser = updateUser;
		this.updateUserName = updateUserName;
		this.remark = remark;
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "code", length = 100)
	public String getCode() {
		return this.code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Column(name = "name", length = 200)
	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name = "status")
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "create_time", nullable = false, length = 0)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	public Date getCreateTime() {
		return this.createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	@Column(name = "create_user", length = 100)
	public String getCreateUser() {
		return this.createUser;
	}
	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}
	@Column(name = "create_user_name", length = 50)
	public String getCreateUserName() {
		return this.createUserName;
	}
	public void setCreateUserName(String createUserName) {
		this.createUserName = createUserName;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "update_time", nullable = false, length = 0)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	public Date getUpdateTime() {
		return this.updateTime;
	}
	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}
	@Column(name = "update_user", length = 100)
	public String getUpdateUser() {
		return this.updateUser;
	}
	public void setUpdateUser(String updateUser) {
		this.updateUser = updateUser;
	}
	@Column(name = "update_user_name", length = 50)
	public String getUpdateUserName() {
		return this.updateUserName;
	}
	public void setUpdateUserName(String updateUserName) {
		this.updateUserName = updateUserName;
	}
	@Column(name = "remark", length = 1500)
	public String getRemark() {
		return this.remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
}

+ 84 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dimension/TjQuotaDimensionMain.java

@ -0,0 +1,84 @@
package com.yihu.quota.model.jpa.dimension;// default package
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjQuotaDimensionMain entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_quota_dimension_main")
public class TjQuotaDimensionMain implements java.io.Serializable {
	// Fields
	private Integer id;
	private String quotaCode;
	private String mainCode;
	private String dictSql;
	private String keyVal;
	private String type;
	// Constructors
	/** default constructor */
	public TjQuotaDimensionMain() {
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "quota_code", length = 100)
	public String getQuotaCode() {
		return this.quotaCode;
	}
	public void setQuotaCode(String quotaCode) {
		this.quotaCode = quotaCode;
	}
	@Column(name = "main_code", length = 100)
	public String getMainCode() {
		return this.mainCode;
	}
	public void setMainCode(String mainCode) {
		this.mainCode = mainCode;
	}
	public String getDictSql() {
		return dictSql;
	}
	public void setDictSql(String dictSql) {
		this.dictSql = dictSql;
	}
	@Column(name = "key_val", length = 100)
	public String getKeyVal() {
		return keyVal;
	}
	public void setKeyVal(String keyVal) {
		this.keyVal = keyVal;
	}
	@Transient
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
}

+ 114 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/dimension/TjQuotaDimensionSlave.java

@ -0,0 +1,114 @@
package com.yihu.quota.model.jpa.dimension;// default package
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjQuotaDimensionSlave entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_quota_dimension_slave")
public class TjQuotaDimensionSlave implements java.io.Serializable {
    // Fields
    private Integer id;
    private String quotaCode;
    private String slaveCode;
    private String dictSql;//字典的sql
    private String keyVal;
    private String type;
    private String groupByKey;//group by用的key
    private String converClass;
    // Constructors
    /**
     * default constructor
     */
    public TjQuotaDimensionSlave() {
    }
    /**
     * full constructor
     */
    public TjQuotaDimensionSlave(String quotaCode, String slaveCode) {
        this.quotaCode = quotaCode;
        this.slaveCode = slaveCode;
    }
    // Property accessors
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "quota_code", length = 100)
    public String getQuotaCode() {
        return this.quotaCode;
    }
    public void setQuotaCode(String quotaCode) {
        this.quotaCode = quotaCode;
    }
    @Column(name = "slave_code", length = 100)
    public String getSlaveCode() {
        return this.slaveCode;
    }
    public void setSlaveCode(String slaveCode) {
        this.slaveCode = slaveCode;
    }
    public String getDictSql() {
        return dictSql;
    }
    public void setDictSql(String dictSql) {
        this.dictSql = dictSql;
    }
    @Transient
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Column(name = "key_val", length = 100)
    public String getKeyVal() {
        return keyVal;
    }
    public void setKeyVal(String keyVal) {
        this.keyVal = keyVal;
    }
    public String getGroupByKey() {
        return groupByKey;
    }
    public void setGroupByKey(String groupByKey) {
        this.groupByKey = groupByKey;
    }
    @Column(name = "conver_class", length = 100)
    public String getConverClass() {
        return converClass;
    }
    public void setConverClass(String converClass) {
        this.converClass = converClass;
    }
}

+ 180 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/save/TjDataSave.java

@ -0,0 +1,180 @@
package com.yihu.quota.model.jpa.save;// default package
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.util.Date;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjDataSave entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_data_save")
public class TjDataSave implements java.io.Serializable {
	public static String type_es ="1";
	public static String type_solr="2";
	public static String type_mysql ="3";
	// Fields
	private Integer id;
	private String code;
	private String name;
	private String type;//1:mysql数据库 2:redis 3ES
	private Date createTime;
	private String createUser;
	private String createUserName;
	private Date updateTime;
	private String updateUser;
	private String updateUserName;
	private String status;//1: 正常 0:不可用  -1删除
	private String remark;
	// Constructors
	/** default constructor */
	public TjDataSave() {
	}
	/** minimal constructor */
	public TjDataSave(Date createTime, Date updateTime) {
		this.createTime = createTime;
		this.updateTime = updateTime;
	}
	/** full constructor */
	public TjDataSave(String code, String name, String type,
			Date createTime, String createUser, String createUserName,
			Date updateTime, String updateUser, String updateUserName,
			String status, String remark) {
		this.code = code;
		this.name = name;
		this.type = type;
		this.createTime = createTime;
		this.createUser = createUser;
		this.createUserName = createUserName;
		this.updateTime = updateTime;
		this.updateUser = updateUser;
		this.updateUserName = updateUserName;
		this.status = status;
		this.remark = remark;
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "code", length = 100)
	public String getCode() {
		return this.code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Column(name = "name", length = 200)
	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name = "type", length = 2)
	public String getType() {
		return this.type;
	}
	public void setType(String type) {
		this.type = type;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "create_time", nullable = false, length = 0)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	public Date getCreateTime() {
		return this.createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	@Column(name = "create_user", length = 100)
	public String getCreateUser() {
		return this.createUser;
	}
	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}
	@Column(name = "create_user_name", length = 50)
	public String getCreateUserName() {
		return this.createUserName;
	}
	public void setCreateUserName(String createUserName) {
		this.createUserName = createUserName;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "update_time", nullable = false, length = 0)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	public Date getUpdateTime() {
		return this.updateTime;
	}
	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}
	@Column(name = "update_user", length = 100)
	public String getUpdateUser() {
		return this.updateUser;
	}
	public void setUpdateUser(String updateUser) {
		this.updateUser = updateUser;
	}
	@Column(name = "update_user_name", length = 50)
	public String getUpdateUserName() {
		return this.updateUserName;
	}
	public void setUpdateUserName(String updateUserName) {
		this.updateUserName = updateUserName;
	}
	@Column(name = "status", length = 1)
	public String getStatus() {
		return this.status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	@Column(name = "remark", length = 1500)
	public String getRemark() {
		return this.remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
}

+ 76 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/save/TjQuotaDataSave.java

@ -0,0 +1,76 @@
package com.yihu.quota.model.jpa.save;// default package
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjQuotaDataSave entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_quota_data_save")
public class TjQuotaDataSave implements java.io.Serializable {
	// Fields
	private Integer id;
	private String quotaCode;
	private String saveCode;
	private String configJson;
	private String type;
	// Constructors
	/** default constructor */
	public TjQuotaDataSave() {
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "quota_code", length = 100)
	public String getQuotaCode() {
		return this.quotaCode;
	}
	public void setQuotaCode(String quotaCode) {
		this.quotaCode = quotaCode;
	}
	@Column(name = "save_code", length = 100)
	public String getSaveCode() {
		return this.saveCode;
	}
	public void setSaveCode(String saveCode) {
		this.saveCode = saveCode;
	}
	@Column(name = "config_json", length = 1500)
	public String getConfigJson() {
		return configJson;
	}
	public void setConfigJson(String configJson) {
		this.configJson = configJson;
	}
	@Transient
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
}

+ 173 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/source/TjDataSource.java

@ -0,0 +1,173 @@
package com.yihu.quota.model.jpa.source;// default package
import javax.persistence.*;
import java.util.Date;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjDataSource entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_data_source")
public class TjDataSource implements java.io.Serializable {
	public static String type_es ="1";
	public static String type_solr ="2";
	public static String type_mysql ="3";
	// Fields
	private Integer id;
	private String code;
	private String type;// 1:mysql数据库 2:redis 3 接口
	private String name;
	private Date createTime;
	private String createUser;
	private String createUserName;
	private Date updateTime;
	private String updateUser;
	private String updateUserName;
	private String status;//1: 正常 0:不可用  -1删除
	private String remark;
	// Constructors
	/** default constructor */
	public TjDataSource() {
	}
	/** minimal constructor */
	public TjDataSource(Date createTime, Date updateTime) {
		this.createTime = createTime;
		this.updateTime = updateTime;
	}
	/** full constructor */
	public TjDataSource(String code, String type, String name,
			Date createTime, String createUser, String createUserName,
			Date updateTime, String updateUser, String updateUserName,
			String status, String remark) {
		this.code = code;
		this.type = type;
		this.name = name;
		this.createTime = createTime;
		this.createUser = createUser;
		this.createUserName = createUserName;
		this.updateTime = updateTime;
		this.updateUser = updateUser;
		this.updateUserName = updateUserName;
		this.status = status;
		this.remark = remark;
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "code", length = 100)
	public String getCode() {
		return this.code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Column(name = "type", length = 2)
	public String getType() {
		return this.type;
	}
	public void setType(String type) {
		this.type = type;
	}
	@Column(name = "name", length = 200)
	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "create_time", nullable = false, length = 0)
	public Date getCreateTime() {
		return this.createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	@Column(name = "create_user", length = 100)
	public String getCreateUser() {
		return this.createUser;
	}
	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}
	@Column(name = "create_user_name", length = 50)
	public String getCreateUserName() {
		return this.createUserName;
	}
	public void setCreateUserName(String createUserName) {
		this.createUserName = createUserName;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "update_time", nullable = false, length = 0)
	public Date getUpdateTime() {
		return this.updateTime;
	}
	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}
	@Column(name = "update_user", length = 100)
	public String getUpdateUser() {
		return this.updateUser;
	}
	public void setUpdateUser(String updateUser) {
		this.updateUser = updateUser;
	}
	@Column(name = "update_user_name", length = 50)
	public String getUpdateUserName() {
		return this.updateUserName;
	}
	public void setUpdateUserName(String updateUserName) {
		this.updateUserName = updateUserName;
	}
	@Column(name = "status", length = 1)
	public String getStatus() {
		return this.status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	@Column(name = "remark", length = 1500)
	public String getRemark() {
		return this.remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
}

+ 83 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/jpa/source/TjQuotaDataSource.java

@ -0,0 +1,83 @@
package com.yihu.quota.model.jpa.source;// default package
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
/**
 * TjQuotaDataSource entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "tj_quota_data_source")
public class TjQuotaDataSource implements java.io.Serializable {
	// Fields
	private Integer id;
	private String quotaCode;
	private String sourceCode;
	private String configJson;
	private String code;
	// Constructors
	/** default constructor */
	public TjQuotaDataSource() {
	}
	/** full constructor */
	public TjQuotaDataSource(String quotaCode, String sourceCode,
			String configJson) {
		this.quotaCode = quotaCode;
		this.sourceCode = sourceCode;
		this.configJson = configJson;
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name = "quota_code", length = 100)
	public String getQuotaCode() {
		return this.quotaCode;
	}
	public void setQuotaCode(String quotaCode) {
		this.quotaCode = quotaCode;
	}
	@Column(name = "source_code", length = 100)
	public String getSourceCode() {
		return this.sourceCode;
	}
	public void setSourceCode(String sourceCode) {
		this.sourceCode = sourceCode;
	}
	@Column(name = "config_json", length = 2000)
	public String getConfigJson() {
		return this.configJson;
	}
	public void setConfigJson(String configJson) {
		this.configJson = configJson;
	}
	@Transient
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
}

+ 47 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/rest/HospitalComposeModel.java

@ -0,0 +1,47 @@
package com.yihu.quota.model.rest;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2018/1/16.
 */
public class HospitalComposeModel implements Serializable {
    private String x1;
    private String x2;
    private String name;
    private List<Map<String, Object>> children;
    public String getX1() {
        return x1;
    }
    public void setX1(String x1) {
        this.x1 = x1;
    }
    public String getX2() {
        return x2;
    }
    public void setX2(String x2) {
        this.x2 = x2;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Map<String, Object>> getChildren() {
        return children;
    }
    public void setChildren(List<Map<String, Object>> children) {
        this.children = children;
    }
}

+ 30 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/rest/QuotaReport.java

@ -0,0 +1,30 @@
package com.yihu.quota.model.rest;
import com.yihu.quota.model.jpa.TjQuota;
import java.util.List;
/**
 * Created by janseny on 2017/6/30.
 */
public class QuotaReport {
    private TjQuota tjQuota;
    private List<ResultModel> reultModelList ;
    public TjQuota getTjQuota() {
        return tjQuota;
    }
    public void setTjQuota(TjQuota tjQuota) {
        this.tjQuota = tjQuota;
    }
    public List<ResultModel> getReultModelList() {
        return reultModelList;
    }
    public void setReultModelList(List<ResultModel> reultModelList) {
        this.reultModelList = reultModelList;
    }
}

+ 39 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/rest/QuotaTreeModel.java

@ -0,0 +1,39 @@
package com.yihu.quota.model.rest;
import com.yihu.quota.model.jpa.TjQuota;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2017/12/19.
 */
public class QuotaTreeModel {
    private TjQuota tjQuota;
    private List<Map<String, Object>> mapList;
    private List<TjQuota> childern;
    public TjQuota getTjQuota() {
        return tjQuota;
    }
    public void setTjQuota(TjQuota tjQuota) {
        this.tjQuota = tjQuota;
    }
    public List<Map<String, Object>> getMapList() {
        return mapList;
    }
    public void setMapList(List<Map<String, Object>> mapList) {
        this.mapList = mapList;
    }
    public List<TjQuota> getChildern() {
        return childern;
    }
    public void setChildern(List<TjQuota> childern) {
        this.childern = childern;
    }
}

+ 28 - 0
svr/svr-quota/src/main/java/com/yihu/quota/model/rest/ResultModel.java

@ -0,0 +1,28 @@
package com.yihu.quota.model.rest;
import java.util.List;
/**
 * Created by janseny on 2017/7/2.
 */
public class ResultModel {
    private List<String> cloumns ;//维度对应的字典项名称 如:维度为org时 值为 余干县人民医院 :维度为town时 值为 余干县
    private Object value;
    public List<String> getCloumns() {
        return cloumns;
    }
    public void setCloumns(List<String> cloumns) {
        this.cloumns = cloumns;
    }
    public Object getValue() {
        return value;
    }
    public void setValue(Object value) {
        this.value = value;
    }
}

+ 17 - 0
svr/svr-quota/src/main/java/com/yihu/quota/service/dict/DictService.java

@ -0,0 +1,17 @@
package com.yihu.quota.service.dict;
import com.yihu.quota.dao.jpa.dict.SystemDictDao;
import com.yihu.quota.dao.jpa.dict.SystemDictListDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by chenweida on 2017/6/1.
 */
@Service
public class DictService {
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private SystemDictListDao systemDictListDao;
}

+ 26 - 0
svr/svr-quota/src/main/java/com/yihu/quota/service/dimension/TjDimensionMainService.java

@ -0,0 +1,26 @@
package com.yihu.quota.service.dimension;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionMain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * Created by chenweida on 2017/6/1.
 */
@Service
public class TjDimensionMainService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<TjQuotaDimensionMain> findTjQuotaDimensionMainByQuotaCode(String code) {
        String sql = "SELECT  qdm.*, dm.type FROM   tj_dimension_main dm, tj_quota_dimension_main qdm " +
        "WHERE   dm.`code` = qdm.main_code AND qdm.quota_code = ? order by qdm.id asc";
        List<TjQuotaDimensionMain> quotaDataSources = jdbcTemplate.query(sql, new BeanPropertyRowMapper(TjQuotaDimensionMain.class), code);
        return quotaDataSources;
    }
}

+ 32 - 0
svr/svr-quota/src/main/java/com/yihu/quota/service/dimension/TjDimensionSlaveService.java

@ -0,0 +1,32 @@
package com.yihu.quota.service.dimension;
import com.yihu.quota.model.jpa.dimension.TjQuotaDimensionSlave;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * Created by chenweida on 2017/6/1.
 */
@Service
public class TjDimensionSlaveService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<TjQuotaDimensionSlave> findTjQuotaDimensionSlaveByQuotaCode(String code) {
        String sql = "SELECT " +
                "  qdm.*,dm.type " +
                " FROM " +
                "  tj_dimension_slave dm, " +
                "  tj_quota_dimension_slave qdm " +
                " WHERE " +
                "  dm.`code` = qdm.slave_code " +
                " AND qdm.quota_code = ? order BY" +
                " qdm.id asc ";
        List<TjQuotaDimensionSlave> quotaDataSources = jdbcTemplate.query(sql, new BeanPropertyRowMapper(TjQuotaDimensionSlave.class), code);
        return quotaDataSources;
    }
}

+ 108 - 0
svr/svr-quota/src/main/java/com/yihu/quota/service/job/JobService.java

@ -0,0 +1,108 @@
package com.yihu.quota.service.job;
import com.yihu.quota.dao.jpa.TjQuotaDao;
import com.yihu.quota.etl.extract.es.EsResultExtract;
import com.yihu.quota.model.jpa.TjQuota;
import com.yihu.quota.util.QuartzHelper;
import com.yihu.quota.vo.QuotaVo;
import org.quartz.ObjectAlreadyExistsException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
 * @author chenweida
 */
@Service
public class JobService {
    @Autowired
    private QuartzHelper quartzHelper;
    @Autowired
    private TjQuotaDao quotaDao;
    @Autowired
    private EsResultExtract esResultExtract;
    /**
     * 启动指标任务
     *
     * @param id          指标ID
     * @param executeFlag 执行动作标识,1:初始执行(全量统计),2:立即执行、周期执行(增量统计)
     * @param startDate   抽取数据起始日期。初始执行时为NULL;立即执行时需要传值;周期执行时也为NULL,如果是基础指标周期执行,后续默认赋值昨天开始。
     * @param endDate     抽取数据截止日期。初始执行时无NULL;立即执行时需要传值;周期执行时也为NULL,如果是基础指标周期执行,后续默认赋值昨天截止。
     * @throws Exception
     */
    public void executeJob(Integer id, String executeFlag, String startDate, String endDate) throws Exception {
        TjQuota tjQuota = quotaDao.getOne(id);
        if (tjQuota != null) {
            QuotaVo quotaVo = new QuotaVo();
            BeanUtils.copyProperties(tjQuota, quotaVo);
            Map<String, Object> params = new HashMap<>();
            params.put("quota", quotaVo);
            params.put("executeFlag", executeFlag);
            params.put("startTime", startDate);
            params.put("endTime", endDate);
            String quotaCode = quotaVo.getCode().replace("_", "");
            String quotaCodeImmediately = quotaCode + "immediately";
            boolean existJob = quartzHelper.isExistJob(quotaCode);
            boolean existJobImmediately = quartzHelper.isExistJob(quotaCodeImmediately);
            if (existJob && "0".equals(quotaVo.getJobStatus())) {
                //周期执行jobKey
                quartzHelper.removeJob(quotaCode);
            }
            if (existJobImmediately) {
                //立即执行jobKey
                quartzHelper.removeJob(quotaCodeImmediately);
            }
            //往quartz框架添加任务
            if ((!StringUtils.isEmpty(executeFlag) && executeFlag.equals("1")) || // 初始执行
                    (!StringUtils.isEmpty(tjQuota.getJobClazz()) && tjQuota.getExecType().equals("1"))) { // 立即执行
               try {
                   quartzHelper.startNow(Class.forName(quotaVo.getJobClazz()), quotaCodeImmediately, params);
               }catch (Exception e){
                   throw  new ObjectAlreadyExistsException(quotaCodeImmediately + "," + tjQuota.getName() + "指标正在执行!");
               }
            } else {
                //周期执行指标 更新指标执行状态:0未开启,1执行中
                tjQuota.setJobStatus("1");
                quotaDao.save(tjQuota);
                quartzHelper.addJob(Class.forName(quotaVo.getJobClazz()), quotaVo.getCron(), quotaCode, params);
            }
        }
    }
    /**
     * 停止指标任务
     *
     * @param id 指标ID
     * @throws Exception
     */
    public void removeJob(Integer id) throws Exception {
        TjQuota tjQuota = quotaDao.getOne(id);
        if (tjQuota != null) {
            QuotaVo quotaVo = new QuotaVo();
            BeanUtils.copyProperties(tjQuota, quotaVo);
            String quotaCode = quotaVo.getCode().replace("_", "");
            String quotaCodeImmediately = quotaCode + "immediately";
            boolean existJob = quartzHelper.isExistJob(quotaCode);
            boolean existJobImmediately = quartzHelper.isExistJob(quotaCodeImmediately);
            if (existJob) {
                //周期执行jobKey
                quartzHelper.removeJob(quotaCode);
            }
            if (existJobImmediately) {
                //立即执行jobKey
                quartzHelper.removeJob(quotaCodeImmediately);
            }
            //周期执行指标 更新指标执行状态:0未开启,1执行中
            tjQuota.setJobStatus("0");
            quotaDao.save(tjQuota);
        }
    }
}

+ 0 - 0
svr/svr-quota/src/main/java/com/yihu/quota/service/medicalInsurance/MedicalInsuranceService.java


이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.