Jelajahi Sumber

Merge branch 'master' of chenweida/esb into master

esb 9 tahun lalu
induk
melakukan
52e71588b2
100 mengubah file dengan 9890 tambahan dan 0 penghapusan
  1. 111 0
      Hos-Resource-Cloud/Hos-Resource-Cloud.iml
  2. 298 0
      Hos-Resource-Cloud/pom.xml
  3. 83 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/ApplicationStart.java
  4. 84 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/CheckLoginFilter.java
  5. 59 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/CommonPageController.java
  6. 87 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/ThreadStart.java
  7. 160 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/config/SysConfig.java
  8. 10 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/config/ThreadConfig.java
  9. 92 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/Constants.java
  10. 9 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/DictDataType.java
  11. 12 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/LogicValues.java
  12. 45 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/MetaDataType.java
  13. 21 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/TransformType.java
  14. 21 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/config/ThreadConfig.java
  15. 169 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/controller/DataAcquisitionController.java
  16. 182 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/controller/DatacollectController.java
  17. 208 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/controller/SystemController.java
  18. 26 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/ActionResult.java
  19. 125 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/DataGridResult.java
  20. 37 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/DictItem.java
  21. 39 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/DictionaryResult.java
  22. 56 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/Result.java
  23. 100 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/SimpleChartItem.java
  24. 65 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/TreeResult.java
  25. 61 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/DataAcquistion.java
  26. 35 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/DataSource.java
  27. 103 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/Patient.java
  28. 59 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/PatientIdentity.java
  29. 57 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/RespResult.java
  30. 44 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/SystemParams.java
  31. 45 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/UserInfo.java
  32. 15 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/BaseEntity.java
  33. 157 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDataSet.java
  34. 82 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDataSetT.java
  35. 56 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDict.java
  36. 18 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictItem.java
  37. 93 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictItemT.java
  38. 90 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictT.java
  39. 102 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterMetaData.java
  40. 96 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterMetaDataT.java
  41. 100 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/origin/OrgDataSetT.java
  42. 54 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/origin/OrgDictItemT.java
  43. 45 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/origin/OrgDictT.java
  44. 145 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/origin/OrgMetaDataT.java
  45. 177 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdDataSetT.java
  46. 100 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdDictItemT.java
  47. 92 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdDictT.java
  48. 93 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdInnerVersionT.java
  49. 206 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdMetaDataT.java
  50. 20 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdVersion.java
  51. 93 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdVersionT.java
  52. 29 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/verify/AuthorizationVeryify.java
  53. 15 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/verify/IVerifier.java
  54. 37 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/verify/MetaDataVerify.java
  55. 29 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/verify/RegistrationVerify.java
  56. 182 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/DataAcquisitionManager.java
  57. 140 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/DatacollectManager.java
  58. 282 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/SystemManager.java
  59. 227 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/CrawlerManager.java
  60. 254 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/DBOrigin.java
  61. 213 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/DataCollectDispatcher.java
  62. 172 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/DataSetTransformer.java
  63. 65 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/OriginDateTimeManager.java
  64. 34 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/intf/IDataAcquisitionManager.java
  65. 25 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/intf/IDatacollectManager.java
  66. 27 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/intf/ISystemManager.java
  67. 83 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/patient/PatientCDAIndex.java
  68. 111 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/patient/PatientCDAUpload.java
  69. 326 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/standard/StandardManager.java
  70. 189 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/standard/StandardService.java
  71. 40 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/thread/CrawlerSupplyThread.java
  72. 50 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/thread/CrawlerThread.java
  73. 53 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/thread/StandardUpdateThread.java
  74. 65 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/thread/ThreadManage.java
  75. 140 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/compress/ZipUtil.java
  76. 173 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/compress/Zipper.java
  77. 138 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/BeanProcessorEx.java
  78. 387 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/DBSessionFactory.java
  79. 63 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/DataSourcePool.java
  80. 77 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/JsonHandler.java
  81. 18 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/SystemDataTime.java
  82. 129 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encode/Base64.java
  83. 29 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encode/HexEncode.java
  84. 106 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encode/UnicodeReader.java
  85. 35 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encrypt/DES.java
  86. 75 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encrypt/MD5.java
  87. 110 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encrypt/RSA.java
  88. 247 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/file/FileUtil.java
  89. 338 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/EsbHttp.java
  90. 22 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/HopHostnameVerifier.java
  91. 311 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/HttpClientUtil.java
  92. 246 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/HttpHelper.java
  93. 36 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/Response.java
  94. 35 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/json/JSON.java
  95. 37 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/json/XML2JSON.java
  96. 50 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/log/LogUtil.java
  97. 47 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/operator/BeanUtil.java
  98. 18 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/operator/CollectionUtil.java
  99. 38 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/operator/ConfigureUtil.java
  100. 0 0
      Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/operator/DateUtil.java

+ 111 - 0
Hos-Resource-Cloud/Hos-Resource-Cloud.iml

@ -0,0 +1,111 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
  <component name="FacetManager">
    <facet type="web" name="Web">
      <configuration>
        <descriptors>
          <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/src/main/webapp/WEB-INF/web.xml" />
        </descriptors>
        <webroots>
          <root url="file://$MODULE_DIR$/src/main/webapp" relative="/" />
        </webroots>
      </configuration>
    </facet>
  </component>
  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8" inherit-compiler-output="false">
    <output url="file://$MODULE_DIR$/target/classes" />
    <output-test url="file://$MODULE_DIR$/target/test-classes" />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
      <excludeFolder url="file://$MODULE_DIR$/target" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="library" name="Maven: com.yihu.core:ehr-dbhelper:1.1.6" level="project" />
    <orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.38" level="project" />
    <orderEntry type="library" name="Maven: com.oracle:ojdbc6:11.2.0.3.0" level="project" />
    <orderEntry type="library" name="Maven: org.xerial:sqlite-jdbc:3.8.11.2" level="project" />
    <orderEntry type="library" name="Maven: net.sf.json-lib:json-lib:2.4" level="project" />
    <orderEntry type="library" name="Maven: commons-collections:commons-collections:3.2.1" level="project" />
    <orderEntry type="library" name="Maven: commons-lang:commons-lang:2.5" level="project" />
    <orderEntry type="library" name="Maven: commons-logging:commons-logging:1.1.1" level="project" />
    <orderEntry type="library" name="Maven: net.sf.ezmorph:ezmorph:1.0.6" level="project" />
    <orderEntry type="library" name="Maven: org.json:json:20151123" level="project" />
    <orderEntry type="library" name="Maven: xom:xom:1.2.5" level="project" />
    <orderEntry type="library" name="Maven: xml-apis:xml-apis:1.3.03" level="project" />
    <orderEntry type="library" name="Maven: xerces:xercesImpl:2.8.0" level="project" />
    <orderEntry type="library" name="Maven: xalan:xalan:2.7.0" level="project" />
    <orderEntry type="library" name="Maven: commons-beanutils:commons-beanutils:1.9.2" level="project" />
    <orderEntry type="library" name="Maven: commons-codec:commons-codec:1.10" level="project" />
    <orderEntry type="library" name="Maven: org.apache.commons:commons-dbcp2:2.1" level="project" />
    <orderEntry type="library" name="Maven: org.apache.commons:commons-pool2:2.3" level="project" />
    <orderEntry type="library" name="Maven: commons-configuration:commons-configuration:1.10" level="project" />
    <orderEntry type="library" name="Maven: commons-dbutils:commons-dbutils:1.6" level="project" />
    <orderEntry type="library" name="Maven: dom4j:dom4j:1.6.1" level="project" />
    <orderEntry type="library" name="Maven: net.lingala.zip4j:zip4j:1.3.2" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-aop:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: aopalliance:aopalliance:1.0" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-aspects:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.8.7" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-beans:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-context:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-context-support:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-core:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-expression:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-jdbc:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-tx:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-web:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-webmvc:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-webmvc-portlet:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-websocket:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:4.1.8.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.slf4j:slf4j-nop:1.7.13" level="project" />
    <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.12" level="project" />
    <orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-core:2.4.1" level="project" />
    <orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.4.1" level="project" />
    <orderEntry type="library" name="Maven: log4j:log4j:1.2.17" level="project" />
    <orderEntry type="library" name="Maven: javax.servlet:javax.servlet-api:3.1.0" level="project" />
    <orderEntry type="library" name="Maven: jstl:jstl:1.2" level="project" />
    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.4.6" level="project" />
    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.4.6" level="project" />
    <orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.4.6" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-extras:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-core:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-api:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: commons-digester:commons-digester:2.0" level="project" />
    <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.6" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-request-servlet-wildcard:1.0.6" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-request-servlet:1.0.6" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-request-mustache:1.0.6" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-request-api:1.0.6" level="project" />
    <orderEntry type="library" name="Maven: com.github.spullara.mustache.java:compiler:0.8.4" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-jsp:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-servlet:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-template:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-autotag-core-runtime:1.1.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-request-jsp:1.0.6" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-freemarker:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-request-freemarker:1.0.6" level="project" />
    <orderEntry type="library" name="Maven: org.freemarker:freemarker:2.3.15" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-velocity:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.apache.velocity:velocity-tools:2.0" level="project" />
    <orderEntry type="library" name="Maven: oro:oro:2.0.8" level="project" />
    <orderEntry type="library" name="Maven: org.apache.velocity:velocity:1.6.2" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-request-velocity:1.0.6" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-el:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-mvel:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: org.mvel:mvel2:2.0.11" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-ognl:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: ognl:ognl:2.7.3" level="project" />
    <orderEntry type="library" name="Maven: jboss:javassist:3.7.ga" level="project" />
    <orderEntry type="library" name="Maven: org.apache.tiles:tiles-compat:3.0.5" level="project" />
    <orderEntry type="library" name="Maven: com.google.guava:guava:12.0.1" level="project" />
    <orderEntry type="library" name="Maven: com.google.code.findbugs:jsr305:1.3.9" level="project" />
    <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5.1" level="project" />
    <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpmime:4.5.1" level="project" />
    <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.3" level="project" />
    <orderEntry type="library" name="Maven: org.apache.ant:ant:1.7.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.ant:ant-launcher:1.7.0" level="project" />
  </component>
</module>

+ 298 - 0
Hos-Resource-Cloud/pom.xml

@ -0,0 +1,298 @@
<?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>
    <groupId>ehr</groupId>
    <artifactId>Hos-Resource-Cloud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <aspectj.version>1.8.7</aspectj.version>
        <jackson.version>2.4.6</jackson.version>
        <spring.version>4.1.8.RELEASE</spring.version>
    </properties>
    <!--用于发布到服务器 对应setting的对应server表情里面的id -->
    <distributionManagement>
        <repository>
            <id>Releases</id>
            <name>Releases</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/releases/</url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <name>Snapshots</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
    <dependencies>
        <!--=============数据库驱动 start =============-->
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>ehr-dbhelper</artifactId>
            <version>1.1.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.8.11.2</version>
        </dependency>
        <!--=============数据库驱动 end =============-->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20151123</version>
        </dependency>
        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--=============spring start =============-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <!--=============spring end =============-->
        <!--=============log4j start =============-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.13</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--=============log4j end =============-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <!--=============tilesJSP布局框架 start =============-->
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-extras</artifactId>
            <version>3.0.5</version>
        </dependency>
        <!--=============tiles end =============-->
        <!--=============httpclient start=============-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.3</version>
        </dependency>
        <dependency>
            <groupId>ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.7.0</version>
        </dependency>
        <!--=============httpclient end=============-->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

+ 83 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/ApplicationStart.java

@ -0,0 +1,83 @@
package com.yihu.ehr.common;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.service.thread.CrawlerSupplyThread;
import com.yihu.ehr.service.thread.CrawlerThread;
import com.yihu.ehr.service.thread.StandardUpdateThread;
import com.yihu.ehr.service.thread.ThreadManage;
import com.yihu.ehr.util.log.LogUtil;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
/**
 * 项目启动执行
 * add by hzp at 2016-01-25
 */
public class ApplicationStart implements ServletContextListener {
    private static Properties prop = new Properties();
    private String log4jDirKey = "log4j";
    private static int rebootCount = 0;
    @Override
    public void contextInitialized(ServletContextEvent context) {
        try {
            String home = System.getProperty("catalina.home").replace('\\','/');
            String homeUrl = home.substring(0,home.lastIndexOf('/')+1);
            dbConfig(homeUrl);
            sslConfig(homeUrl);
        } catch (Exception e) {
            System.out.print(e.getStackTrace().toString());
            LogUtil.error(e.getStackTrace().toString());
        }
    }
    /**
     * 修改微服务连接ssl文件
     * @param homeUrl
     */
    private void sslConfig(String homeUrl) throws Exception {
        InputStream in = this.getClass().getResourceAsStream("/config/http.properties");
        prop.load(in);
        String configPath = this.getClass().getClassLoader().getResource("/").getPath()+ "config/http.properties";
        OutputStream fos = new FileOutputStream(configPath);
        String url = homeUrl+"ssl/tomcat.keystore";
        prop.setProperty("sslKeystore",url);
        prop.store(fos,"last update");
        in.close();
        fos.close();
    }
    /**
     * 修改数据库连接字符串
     * @param homeUrl
     */
    private void dbConfig(String homeUrl) throws Exception {
        InputStream in = this.getClass().getResourceAsStream("/config/dbhelper.properties");
        prop.load(in);
        String configPath = this.getClass().getClassLoader().getResource("/").getPath()+ "config/dbhelper.properties";
        OutputStream fos = new FileOutputStream(configPath);
        String url = homeUrl+"db/localDB.db";
        prop.setProperty("defaultName","miniResourceDB");
        prop.setProperty("defaultUri","jdbc:sqlite://"+url);
        prop.store(fos,"last update");
        in.close();
        fos.close();
    }
    @Override
    public void contextDestroyed(ServletContextEvent context) {
    }
}

+ 84 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/CheckLoginFilter.java

@ -0,0 +1,84 @@
package com.yihu.ehr.common;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * 校验用户是否已登录过滤器
 * add by hzp at 2016-03-03
 */
public class CheckLoginFilter implements Filter {
    private FilterConfig filterConfig = null;
    private String redirectURL = null;
    private List notCheckURLList = new ArrayList();
    public CheckLoginFilter() {
    }
    public void destroy() {
        notCheckURLList.clear();
    }
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        Object userInfo = session.getAttribute("userInfo");
        if(!filterList(request) && userInfo==null){
            //重定向到指定页面
            response.sendRedirect(request.getContextPath() + redirectURL);
        }else{
            //继续响应请求
            chain.doFilter(servletRequest, servletResponse);
        }
    }
    public void init(FilterConfig fConfig) throws ServletException {
        this.filterConfig = fConfig;
        redirectURL = filterConfig.getInitParameter("redirectURL");
        String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");
        if(notCheckURLListStr!=null && notCheckURLListStr.length()>0){
            //将字符串转化为list
            String[] list = notCheckURLListStr.split(";");
            for(String str : list)
            {
                notCheckURLList.add(str);
            }
        }
    }
    /**
     * 校验当前请求是否在不过滤的列表中
     * @param request
     * @return
     */
    private boolean filterList(HttpServletRequest request)
    {
        String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
        if(notCheckURLList.contains(uri)) {
            return true;
        }
        else{
            // 不过滤的uri
            String[] notFilter = new String[] {"/develop"};
            for(String s : notFilter)
            {
                if (uri.indexOf(s) == 0)
                {
                    // 如果uri中包含不过滤的uri,则不进行过滤
                    return true;
                }
            }
        }
        return false;
    }
}

+ 59 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/CommonPageController.java

@ -0,0 +1,59 @@
package com.yihu.ehr.common;
import com.yihu.ehr.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 * 数据采集配置页面
 * Created by hzp on 2015/8/12.
 */
@RequestMapping("/")
@Controller("commonPageController")
public class CommonPageController {
    /*
    登录页面
     */
    @RequestMapping("loginPage")
    public String login(Model model) {
        model.addAttribute("contentPage","/common/login");
        return "pageView";
    }
    /*
    首页页面
     */
    @RequestMapping("indexPage")
    public String index(HttpServletRequest request,Model model) {
        try {
            HttpSession session = request.getSession();
            UserInfo user = (UserInfo) session.getAttribute("userInfo");
            model.addAttribute("userName", user.getRealName());
            model.addAttribute("contentPage", "/common/index");
            return "pageView";
        }
        catch (Exception ex)
        {
            System.out.print(ex.getMessage());
            return "error";
        }
    }
    /*
    错误页面
     */
    @RequestMapping("error")
    public String error(Model model) {
        model.addAttribute("errorMessage","");
        return "error";
    }
}

+ 87 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/ThreadStart.java

@ -0,0 +1,87 @@
package com.yihu.ehr.common;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.service.thread.CrawlerSupplyThread;
import com.yihu.ehr.service.thread.CrawlerThread;
import com.yihu.ehr.service.thread.StandardUpdateThread;
import com.yihu.ehr.service.thread.ThreadManage;
import com.yihu.ehr.util.log.LogUtil;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
/**
 * 线程启动执行
 * add by hzp at 2016-03-17
 */
public class ThreadStart implements ServletContextListener {
    private static Properties prop = new Properties();
    private String log4jDirKey = "log4j";
    @Override
    public void contextInitialized(ServletContextEvent context) {
        try {
            String home = System.getProperty("catalina.home").replace('\\','/');
            String homeUrl = home.substring(0,home.lastIndexOf('/')+1);
            crawlerConfig(homeUrl);
            startThread();
        } catch (Exception e) {
            System.out.print(e.getStackTrace().toString());
        }
    }
    @Override
    public void contextDestroyed(ServletContextEvent context) {
    }
    /**
     * 采集配置
     * @param homeUrl
     * @throws Exception
     */
    private void crawlerConfig(String homeUrl) throws Exception {
        System.setProperty(log4jDirKey, homeUrl + "log4j");
        SysConfig.getInstance().setTempFile(homeUrl + "standard");
    }
    /**
     * 启动线程
     */
    private void startThread() {
        try {
            DBHelper db = new DBHelper();
            Object obj = db.scalar("select param_value from system_param where param_key='ORG_CODE'");
            if (obj != null) {
                SysConfig.getInstance().setOrgCode(obj.toString());
            }
            Thread crawlerThread = new Thread(new CrawlerThread());
            Thread crawlerSupplyThread = new Thread(new CrawlerSupplyThread());
            Thread standardUpdateThread = new Thread(new StandardUpdateThread());
            ThreadManage.add(ThreadManage.CRAWLER_THREAD, crawlerThread);
            ThreadManage.add(ThreadManage.CRAWLER_SUPPLY_THREAD, crawlerSupplyThread);
            ThreadManage.add(ThreadManage.STANDARD_UPDATE_THREAD, standardUpdateThread);
            ThreadManage.setCrawlerInterval();
            ThreadManage.setUpdateInterval();
            //启动线程
            crawlerThread.start();
            crawlerSupplyThread.start();
            standardUpdateThread.start();
        }
        catch (Exception e)
        {
            LogUtil.error(e.getStackTrace().toString());
        }
    }
}

+ 160 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/config/SysConfig.java

@ -0,0 +1,160 @@
package com.yihu.ehr.common.config;
import com.yihu.ehr.model.PatientIdentity;
import com.yihu.ehr.util.log.LogUtil;
import com.yihu.ehr.util.operator.StringUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
public class SysConfig {
    public static final String HOS_RESOURCES_CONFIG = "/config/sys.config.xml";
    public static String publicKey;
    public static String orgCode;
    public static String tempFile;
    public static String registerDataSet;
    public static String registerIdCardNo;
    private static volatile SysConfig instance = null;
    private HashMap<String, PatientIdentity> patientIdentityHashMap;
    private SysConfig() {
        patientIdentityHashMap = new HashMap<>();
        init();
    }
    public static SysConfig getInstance() {
        if (instance == null) {
            synchronized (SysConfig.class) {
                if (instance == null) {
                    try {
                        instance = new SysConfig();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return instance;
    }
    public void finalize() throws Throwable {
    }
    public String getTempFile() {
        return this.tempFile;
    }
    public void setTempFile(String tempFile) {
        this.tempFile = tempFile;
    }
    public String getPublicKey() {
        return publicKey;
    }
    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }
    public PatientIdentity getPatientIdentity(String dataSetCode) {
        return patientIdentityHashMap.get(dataSetCode);
    }
    public HashMap<String, PatientIdentity> getPatientIdentityHashMap() {
        return patientIdentityHashMap;
    }
    public String getRegisterDataSet() {
        return registerDataSet;
    }
    public String getRegisterIdCardNo() {
        return registerIdCardNo;
    }
    private Document getDocument() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            InputStream inputStream = SysConfig.class.getResourceAsStream(HOS_RESOURCES_CONFIG);
            document = reader.read(inputStream);
            return document;
        } catch (DocumentException de) {
            LogUtil.fatal("读取classpath下的xml文档路径发生异常");
            return null;
        }
    }
    private void init() {
        try {
            Document document = this.getDocument();
            Element rootElement = null;
            if (document != null) {
                rootElement = document.getRootElement();
            }
            if (rootElement == null) {
                return;
            }
            this.initCrawler(rootElement);
            this.initEventNo(rootElement);
        } catch (Exception e) {
            LogUtil.error(e);
        }
    }
    private void initCrawler(Element rootElement) {
        List queueDataSets = rootElement.element("patient_queue").elements("dataset");
        for (Object obj : queueDataSets) {
            if (obj instanceof Element) {
                Element element = (Element) obj;
                String dataSetCode = element.attributeValue("code");
                String eventNo = element.elementTextTrim("event_no");
                String refTime = element.elementTextTrim("ref_time");
                PatientIdentity patientIdentity = new PatientIdentity(eventNo, refTime);
                patientIdentityHashMap.put(dataSetCode, patientIdentity);
            }
        }
        Element registerDataSet = rootElement.element("register").element("dataset");
        this.registerDataSet = registerDataSet.attributeValue("code");
        this.registerIdCardNo = registerDataSet.elementTextTrim("id_card");
    }
    private void initEventNo(Element rootElement) {
        List eventItems = rootElement.element("event_no").elements("item");
        for (Object obj : eventItems) {
            if (obj instanceof Element) {
                Element element = (Element) obj;
                String eventNoCode = element.getTextTrim();
                PatientIdentity.addEventNoCode(eventNoCode);
            }
        }
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getOrgCode() {
        return orgCode;
    }
    public Boolean isEmptyOrgCode() {
        if (StringUtil.isEmpty(orgCode)) {
            return true;
        } else {
            return false;
        }
    }
}//end SysConfig

+ 10 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/config/ThreadConfig.java

@ -0,0 +1,10 @@
package com.yihu.ehr.common.config;
public class ThreadConfig {
    public static int CRAWLER_THREAD_SLEEP_TIME = 60;
    public static int UPDATE_THREAD_SLEEP_TIME = 60;
    public static int CRAWLER_SUPPLY_THREAD_SLEEP_TIME = 60;
}

+ 92 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/Constants.java

@ -0,0 +1,92 @@
package com.yihu.ehr.common.constants;
/**
 * Created by lingfeng on 2015/6/23.
 */
public class Constants {
    public static final String CREATE_TABLE = " CREATE TABLE ";
    public static final String INSERT_INTO = " INSERT INTO ";
    public static final String ALTER_TABLE = " ALTER TABLE ";
    public static final String SELECT = " SELECT ";
    public static final String UPDATE = "UPDATE ";
    public static final String DELETE = "DELETE ";
    public static final String FROM = " FROM ";
    public static final String WHERE = " WHERE ";
    public static final String BETWEEN = " BETWEEN ";
    public static final String COUNT = " COUNT(*) ";
    public static final String EQUAL_MARK = " = ";
    public static final String GREATER_EQUAL_MARK = " >= ";
    public static final String LESS_EQUAL_MARK = " <= ";
    public static final String GREATER_MARK = " > ";
    public static final String LESS_MARK = " < ";
    public static final String SET = " SET ";
    public static final String AND = " AND ";
    public static final String QUESTION_MARK = " ? ";
    public static final String ADD = " ADD ";
    public static final String NOT_NULL = " NOT NULL ";
    public static final String SINGLE_QUOTE_MARK = "'";
    public static final String BLANK = " ";
    public static final String PRIMARY_KEY = "PRIMARY_KEY ";
    public static final String LEFT_BRACKET = "(";
    public static final String RIGHT_BRACKET = ")";
    public static final String STAR = "*";
    public static final String COMMA = ",";
    public static final String SEMICOLON = ";";
    public static final String OCTOTHORPE = "#";
    public static final String VALUES = " VALUES ";
    public static final String LIKE = " LIKE ";
    public static final String PERCENT = "%";
    public static final String ROW_FORMAT_DYNAMIC = "row_format=dynamic";
    public static final String USERNAME_KEY = "u2akgXkkRRkiiCVR";
    public static final String ACCESS_TOKEN = "accessToken";
    public static final String REFRESH_TOKEN = "refreshToken";
    public static final String TOKEN_FAILD = "tokenFaild";
    public static final String TOKEN_EXPIRED = "tokenExpired";
    public static final String EMPTY = "";
    public static final String CDA_FILE = "CDA_File";
    public static final String STANDARD_ZIP = "standard.zip";
    public static final String DOT = ".";
    public static final String PATIENT_QUEUE = "patient_queue";
    public static final String UPDATE_TYPE = "update";
    public static final String DELETE_TYPE = "delete";
    public static final String ADD_TYPE = "add";
    public static final String TABLE_KEY = "id";
    public static final String FAILURE_FLG = "valid";
    public static final String UNDERLINE = "_";
    public static final String STD_PREFIX = "std_";
    public static final String ADAPTER_PREFIX = "adapter_";
    public static final String ORIGIN_PREFIX = "origin_";
    public static final String CODE_STR = "code";
    public static final String VALUE_STR = "value";
    public static final String OK = "ok";
    public static final String NO = "no";
    public static final Integer NUMBER_ZREO = 0;
    public static final Integer NUMBER_ONE = 1;
    public static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
    public static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
    public static final String SQLSERVER_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    public static final String MYSQL = "mysql";
    public static final String ORACLE = "oracle";
    public static final String SQLSERVER = "sqlserver";
    //===========================开放接口参数 start=============================
    /**
     * 获取就诊病人列表(GetPatientQueue)
     */
    public static final String GETPATIENTQUEUE="01001";
    /**
     *获取就诊病人档案数据集(GetPatientDataset)
     */
    public static final String GETPATIENTDATASET="01002";
    /**
     * 上传就诊病人档案数据集(PostPatientDataset)
     */
    public static final String POSTPATIENTDATASET="01003";
    // 09开头的都是系统级别
    public static final String SYSTEM_ERROR="09000";
    public static final String SYSTEM_PARAMS="09001";
    public static final String SYSTEM_PARAMS_MESSAGE="参数错误";
    //===========================开放接口参数 end=============================
}

+ 9 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/DictDataType.java

@ -0,0 +1,9 @@
package com.yihu.ehr.common.constants;
/**
 * Created by Administrator on 2015/9/16.
 */
public enum DictDataType {
    VALUE, //值
    CODE //编码
}

+ 12 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/LogicValues.java

@ -0,0 +1,12 @@
package com.yihu.ehr.common.constants;
/**
 * Created by HZY on 2016/1/29.
 */
public class LogicValues {
    public static final String LOGIC_OK = "ok";
    public static final String LOGIC_NO = "no";
    public static final String LOGIC_TRUE = "true";
    public static final String LOGIC_FALSE = "false";
}

+ 45 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/MetaDataType.java

@ -0,0 +1,45 @@
package com.yihu.ehr.common.constants;
/**
 * 数据元类型
 *
 * @created Created by Air on 2015/6/9.
 */
public enum MetaDataType {
    /**
     * 字符,不可枚举
     */
    S1,
    /**
     * 字符,枚举<=3个
     */
    S2,
    /**
     * 字符,代码表
     */
    S3,
    /**
     * 布尔,0(False),1(True)
     */
    L,
    /**
     * 数值,
     */
    N,
    /**
     * 日期
     */
    D,
    /**
     * 时间日期
     */
    DT,
    /**
     * 时间
     */
    T,
    /**
     * 二进制
     */
    BY
}

+ 21 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/common/constants/TransformType.java

@ -0,0 +1,21 @@
package com.yihu.ehr.common.constants;
/**
 * @created  Air on 2015/6/8.
 */
public enum TransformType {
    /**
     * 数据集
     */
    DATA_SET_JSON,
    DATA_SET_XML,
    /**
     * CDA
     */
    CDA_JSON,
    CDA_XML,
    /**
     * 非结构化
     */
    DOCUMENT,
}

+ 21 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/config/ThreadConfig.java

@ -0,0 +1,21 @@
package com.yihu.ehr.config;
/**
 * Created by chenweida on 2016/2/27.
 */
public class ThreadConfig {
    public static int LOG_THREAD_SLEEP_TIME = 30;
    public static String LOG_THREAD_URL = "";
    public static String LOG_THREAD_USERNAME = "user";
    public static String LOG_THREAD_PASSWORD = "standard";
    public static int SQL_THREAD_SLEEP_TIME = 30;
    public static int UPDATE_THREAD_SLEEP_TIME = 30;
    public static String UPDATE_THREAD_GETUPDATEFLAG;
    public static String UPDATE_THREAD_DOWNUPDATEWAR;
    public static String TOMCAT_SERVICENAME = "tomcat8-esb-service";
}

+ 169 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/controller/DataAcquisitionController.java

@ -0,0 +1,169 @@
package com.yihu.ehr.controller;
import com.yihu.ehr.common.constants.Constants;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.framework.model.Result;
import com.yihu.ehr.model.DataAcquistion;
import com.yihu.ehr.model.RespResult;
import com.yihu.ehr.service.intf.IDataAcquisitionManager;
import com.yihu.ehr.util.operator.StringUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2016/3/18.
 */
@Controller
@RequestMapping("/dataAcquisition")
public class DataAcquisitionController {
    @Autowired
    private IDataAcquisitionManager dataAcquisitionManager;
    private DBHelper db = new DBHelper();
    @RequestMapping(value = "/getData")
    @ResponseBody
    public RespResult getData(HttpServletRequest request) throws Exception {
        RespResult r = new RespResult();
        try {
            String transactionCode = request.getParameter("transactionCode");
            //判断transactionCode是否错误
            if (StringUtil.isEmpty(transactionCode)) {
                r.setRespCode(Constants.SYSTEM_ERROR);
                r.setRespMessage("transactionCode为空");
                return r;
            }
            //根据transactionCode查找数据库
            List<JSONObject> list = db.query("select * from data_acquisition where transactioncode='" + transactionCode + "'");
            if (list == null && list.size() == 0) {
                r.setRespCode(Constants.SYSTEM_ERROR);
                r.setRespMessage("transactionCode不存在");
                return r;
            }
            //得到参数
            Map<String, String[]> paramsMap = request.getParameterMap();
            Map<String, Object> params = new HashMap<String, Object>();
            for (Map.Entry<String, String[]> a : paramsMap.entrySet()) {
                params.put(a.getKey(), a.getValue()[0]);
            }
            JSONObject jo = list.get(0);
            r.setData(dataAcquisitionManager.gate(jo, params));
            //根据参数选择业务函数
            r.setTransactionCode(transactionCode);
        } catch (Exception e) {
            r.setRespCode(Constants.SYSTEM_ERROR);
            r.setRespMessage(e.getMessage());
        }
        return r;
    }
    /*
   系统参数页面
    */
    @RequestMapping("/dataAcquisitionManager")
    public String paramManager(Model model) {
        try {
            model.addAttribute("contentPage", "/datacquisition/dataAcquistion");
            return "partView";
        } catch (Exception ex) {
            model.addAttribute("errorMessage", ex.getMessage());
            return "error";
        }
    }
    @RequestMapping("getDataAcquisition")
    @ResponseBody
    public Result getDataAcquisition(int page, int rows) {
        try {
            return dataAcquisitionManager.getDataAcquisition(page, rows);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    @RequestMapping("editorDataAcq")
    public String editorDataAcq(Model model, String dataId) {
        try {
            //是否编辑
            if (dataId != null && dataId.length() > 0) {
                //获取菜单信息
                DataAcquistion jsonS = dataAcquisitionManager.getDataAcquisitionById(dataId);
                model.addAttribute("model", jsonS);
            }
            model.addAttribute("contentPage", "datacquisition/editorDataAcq");
            return "pageView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "datacquisition/editorDataAcq");
            return "pageView";
        }
    }
    @RequestMapping("addDataAcquisition")
    @ResponseBody
    public Result addDataAcquisition(HttpServletRequest request) {
        try {
            String url = request.getParameter("url");
            String request_type = request.getParameter("request_type");
            String transactioncode = request.getParameter("transactioncode");
            String url_type = request.getParameter("url_type");
            String name = request.getParameter("name");
            if (dataAcquisitionManager.getDataAcquisitionByCode(transactioncode) != null) {
                return Result.error("接口代码已经存在");
            }
            if (dataAcquisitionManager.getDataAcquisitionByName(name) != null) {
                return Result.error("接口名称已经存在");
            }
            return dataAcquisitionManager.addDataAcquisition(url, request_type, transactioncode, url_type, name);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }
    @RequestMapping("updateDataAcquisition")
    @ResponseBody
    public Result updateDataAcquisition(HttpServletRequest request) {
        try {
            String url = request.getParameter("url");
            String id = request.getParameter("id");
            String request_type = request.getParameter("request_type");
            String transactioncode = request.getParameter("transactioncode");
            String url_type = request.getParameter("url_type");
            String name = request.getParameter("name");
            if (dataAcquisitionManager.getDataAcquisitionByCode(transactioncode, id) != null) {
                return Result.error("接口代码已经存在");
            }
            if (dataAcquisitionManager.getDataAcquisitionByName(name, id) != null) {
                return Result.error("接口名称已经存在");
            }
            return dataAcquisitionManager.updateDataAcquisition(url, request_type, transactioncode, url_type, name, id);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }
    @RequestMapping("deleteDataAcquisition")
    @ResponseBody
    public Result deleteDataAcquisition(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            return dataAcquisitionManager.deleteAataAcquisition(id);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }
}

+ 182 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/controller/DatacollectController.java

@ -0,0 +1,182 @@
package com.yihu.ehr.controller;
import com.yihu.ehr.framework.model.Result;
import com.yihu.ehr.model.DataSource;
import com.yihu.ehr.service.intf.IDatacollectManager;
import com.yihu.ehr.service.intf.ISystemManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 数据采集配置页面
 * Created by hzp on 2015/8/12.
 */
@RequestMapping("/datacollect")
@Controller("datacollectController")
public class DatacollectController {
    @Autowired
    private IDatacollectManager datacollect;
    @Autowired
    private ISystemManager system;
    /******************************** 页面 **********************************/
    /*
    采集标准页面
     */
    @RequestMapping("stdManager")
    public String stdManager(Model model)
    {
        try{
            model.addAttribute("contentPage","/datacollect/stdManager");
            return "partView";
        }
        catch (Exception ex)
        {
            model.addAttribute("errorMessage",ex.getMessage());
            return "error";
        }
    }
    /*
    任务跟踪页面
     */
    @RequestMapping("trackJob")
    public String trackJob(Model model)
    {
        try{
            //判断是否已配数据源
            DataSource source = system.getDataSource();
            if(source!=null)
            {
                model.addAttribute("hadSource", "1");
            }
            else{
                model.addAttribute("hadSource", "0");
            }
            model.addAttribute("contentPage", "/datacollect/trackJob");
            return "partView";
        }
        catch (Exception ex)
        {
            model.addAttribute("errorMessage",ex.getMessage());
            return "error";
        }
    }
    /*
    任务补采页面
     */
    @RequestMapping("repeatJob")
    public String repeatJob(Model model)
    {
        try{
            model.addAttribute("contentPage", "/datacollect/repeatJob");
            return "partView";
        }
        catch (Exception ex)
        {
            model.addAttribute("errorMessage",ex.getMessage());
            return "error";
        }
    }
    /*************************** 操作 *******************************************/
    /*
    获取数据集
     */
    @RequestMapping("getDataset")
    @ResponseBody
    public Result getDataset(String name) {
        try {
            return datacollect.getDataset(name);
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    /*
        获取数据元
    */
    @RequestMapping("getMetadata")
    @ResponseBody
    public Result getMetadata(String name,String adapterDatasetId,int page,int rows) {
        try {
            return datacollect.getMetadata(name,adapterDatasetId,page,rows);
        }
        catch (Exception ex)
        {
            return Result.error(ex.getMessage());
        }
    }
    /*
        获取任务跟踪
    */
    @RequestMapping("getJobLog")
    @ResponseBody
    public Result getJobLog(String patientId,String eventNo,String status,int page,int rows) {
        try {
            return datacollect.getJobLog(patientId, eventNo,status,page, rows);
        }
        catch (Exception ex)
        {
            return Result.error(ex.getMessage());
        }
    }
    /*
        获取任务补采记录
    */
    @RequestMapping("getJobRepeat")
    @ResponseBody
    public Result getJobRepeat(int page,int rows) {
        try {
            return datacollect.getJobRepeat(page,rows);
        }
        catch (Exception ex)
        {
            return Result.error(ex.getMessage());
        }
    }
    /*
        新增任务补采
    */
    @RequestMapping("addJobRepeat")
    @ResponseBody
    public Result addJobRepeat(String startTime,String endTime)
    {
        try {
            return datacollect.addJobRepeat(startTime, endTime);
        }
        catch (Exception ex)
        {
            return Result.error(ex.getMessage());
        }
    }
    /*
        删除任务补采
    */
    @RequestMapping("deleteJobRepeat")
    @ResponseBody
    public Result deleteJobRepeat(String id)
    {
        try {
            return datacollect.deleteJobRepeat(id);
        } catch (Exception ex)
        {
            return Result.error(ex.getMessage());
        }
    }
}

File diff ditekan karena terlalu besar
+ 208 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/controller/SystemController.java


+ 26 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/ActionResult.java

@ -0,0 +1,26 @@
package com.yihu.ehr.framework.model;
/**
 * Created by chenweida on 2015/12/15.
 */
public class ActionResult extends Result {
    private Object data;
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public ActionResult()
    {}
    public ActionResult(boolean successFlg,String message){
        super.setSuccessFlg(successFlg);
        super.setMessage(message);
    }
}

+ 125 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/DataGridResult.java

@ -0,0 +1,125 @@
package com.yihu.ehr.framework.model;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.dbhelper.common.DBList;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.Serializable;
import java.util.List;
/**
 * ���VO
 * @author cwd
 *
 */
public class DataGridResult extends Result implements Serializable{
		private int pageSize = 10;
		private int currPage = 1;
		private int totalPage;
		private int totalCount;
		private List detailModelList;
	public DataGridResult()
	{
	}
	public DataGridResult(int pageSize, int currPage) {
		this.pageSize = pageSize;
		this.currPage = currPage;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getCurrPage() {
		return currPage;
	}
	public void setCurrPage(int currPage) {
		this.currPage = currPage;
	}
	public int getTotalPage() {
		if (totalCount % pageSize == 0) {
			totalPage = totalCount / pageSize;
		} else {
			totalPage = totalCount / pageSize + 1;
		}
		return totalPage;
	}
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
	public int getStart() {
		if (currPage != 0) {
			return (currPage - 1) * pageSize;
		}
		return 0;
	}
	public int getEnd() {
		if (currPage != 0) {
			return currPage * pageSize;
		}
		return 0;
	}
	public long getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public List getDetailModelList() {
		return detailModelList;
	}
	public void setDetailModelList(List detailModelList) {
		this.detailModelList = detailModelList;
	}
	public static DataGridResult fromJson(String json)
	{
		return (DataGridResult) JSONObject.toBean(JSONObject.fromObject(json), DataGridResult.class);
	}
	public String toJson(){
		return "{\"successFlg\":true,\"pageSize\":"+pageSize+",\"currPage\""+currPage+",\"totalPage\":"+totalPage+",\"totalCount\":"+totalCount+",\"detailModelList\":"+detailModelList.toString()+"}";
	}
	public static DataGridResult fromDBList(DBList list)
	{
		DataGridResult re = new DataGridResult();
		if(list.getPage()!=null)
			re.setCurrPage(list.getPage());
		if(list.getSize()!=null)
			re.setPageSize(list.getSize());
		if(list.getCount()!=null)
			re.setTotalCount(list.getCount());
		if(list.getList()!=null)
			re.setDetailModelList(JSONArray.fromObject(list.getList().toString()));
		return re;
	}
}

+ 37 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/DictItem.java

@ -0,0 +1,37 @@
package com.yihu.ehr.framework.model;
/**
 * 字典项
 * Created by hzp on 2016/1/15
 */
public class DictItem {
        private String value;
        private String code;
        private String extend;
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
        public String getCode() {
            return code;
        }
        public void setCode(String code) {
            this.code = code;
        }
        public String getExtend() {
            return extend;
        }
        public void setExtend(String extend) {
            this.extend = extend;
        }
}

+ 39 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/DictionaryResult.java

@ -0,0 +1,39 @@
package com.yihu.ehr.framework.model;
import java.util.List;
/**
 * 返回字典对象
 * Created by chenweida on 2016/1/13.
 */
public class DictionaryResult extends Result {
    private String name;
    private List<DictItem> detailModelList;
    public DictionaryResult()
    {}
    public DictionaryResult(String name)
    {
        this.name=name;
    }
    public List<DictItem> getDetailModelList() {
        return detailModelList;
    }
    public void setDetailModelList(List<DictItem> detailModelList) {
        this.detailModelList = detailModelList;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

+ 56 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/Result.java

@ -0,0 +1,56 @@
package com.yihu.ehr.framework.model;
/**
 * Created by chenweida on 2015/12/11.
 */
public class Result {
    private boolean successFlg = true;
    private String message;
    private int errorCode;
    public boolean isSuccessFlg() {
        return successFlg;
    }
    public void setSuccessFlg(boolean successFlg) {
        this.successFlg = successFlg;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public int getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
    /**
     * ������Ϣ
     * @return
     */
    public static Result error(String message) {
        Result re= new Result();
        re.successFlg = false;
        re.message = message;
        return re;
    }
    /**
     * �ɹ���Ϣ
     * @return
     */
    public static Result success(String message) {
        Result re= new Result();
        re.successFlg = true;
        re.message = message;
        return re;
    }
}

+ 100 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/SimpleChartItem.java

@ -0,0 +1,100 @@
package com.yihu.ehr.framework.model;
/**
 * 简单表单数据项
 * Created by hzp on 2016/1/15
 */
public class SimpleChartItem {
    private String x;
    private Float y1;
    private Float y2;
    private Float y3;
    private Float y4;
    private Float y5;
    private Float y6;
    private Float y7;
    private Float y8;
    private Float y9;
    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
    public Float getY1() {
        return y1;
    }
    public void setY1(Float y1) {
        this.y1 = y1;
    }
    public Float getY2() {
        return y2;
    }
    public void setY2(Float y2) {
        this.y2 = y2;
    }
    public Float getY3() {
        return y3;
    }
    public void setY3(Float y3) {
        this.y3 = y3;
    }
    public Float getY4() {
        return y4;
    }
    public void setY4(Float y4) {
        this.y4 = y4;
    }
    public Float getY5() {
        return y5;
    }
    public void setY5(Float y5) {
        this.y5 = y5;
    }
    public Float getY6() {
        return y6;
    }
    public void setY6(Float y6) {
        this.y6 = y6;
    }
    public Float getY7() {
        return y7;
    }
    public void setY7(Float y7) {
        this.y7 = y7;
    }
    public Float getY8() {
        return y8;
    }
    public void setY8(Float y8) {
        this.y8 = y8;
    }
    public Float getY9() {
        return y9;
    }
    public void setY9(Float y9) {
        this.y9 = y9;
    }
}

+ 65 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/framework/model/TreeResult.java

@ -0,0 +1,65 @@
package com.yihu.ehr.framework.model;
import java.io.Serializable;
/**
 * Created by chenweida on 2015/12/17.
 */
public class TreeResult extends Result implements Serializable {
    String id;//节点IP
    String pid;//父节点IP
    String text;//显示的名字
    String code;//1是类别 2是接口
    String type;//类别
    String icon;//图标类
    public String getId() {
        return id;
    }
    public String getPid() {
        return pid;
    }
    public void setPid(String pid) {
        this.pid = pid;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getType() {
        return type;
    }
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public void setType(String type) {
        this.type = type;
    }
}

+ 61 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/DataAcquistion.java

@ -0,0 +1,61 @@
package com.yihu.ehr.model;
/**
 * Created by chenweida on 2016/3/28.
 */
public class DataAcquistion {
    private String id;
    private String url;
    private String name;
    private String transactioncode;
    private String request_type;
    private String url_type;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTransactioncode() {
        return transactioncode;
    }
    public void setTransactioncode(String transactioncode) {
        this.transactioncode = transactioncode;
    }
    public String getRequest_type() {
        return request_type;
    }
    public void setRequest_type(String request_type) {
        this.request_type = request_type;
    }
    public String getUrl_type() {
        return url_type;
    }
    public void setUrl_type(String url_type) {
        this.url_type = url_type;
    }
}

+ 35 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/DataSource.java

@ -0,0 +1,35 @@
package com.yihu.ehr.model;
/**
 * Created by hzp on 2016/2/26.
 */
public class DataSource {
    private String id;
    private String name;
    private String config;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getConfig() {
        return config;
    }
    public void setConfig(String config) {
        this.config = config;
    }
}

+ 103 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/Patient.java

@ -0,0 +1,103 @@
package com.yihu.ehr.model;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.14 10:12
 */
public class Patient {
    private String patientId;
    private String eventNo;
    private String localCardNo;
    private String idCard;
    private String orgCode;
    private String latestTime;
    private String referenceTime;
    private String reUploadFlg;
    private String jobTimeStamp;
    private String failType; //采集失败类型
    public Patient() {
    }
    public String getPatientId() {
        return patientId;
    }
    public void setPatientId(String patientId) {
        this.patientId = patientId;
    }
    public String getEventNo() {
        return eventNo;
    }
    public void setEventNo(String eventNo) {
        this.eventNo = eventNo;
    }
    public String getLocalCardNo() {
        return localCardNo;
    }
    public void setLocalCardNo(String localCardNo) {
        this.localCardNo = localCardNo;
    }
    public String getIdCard() {
        return idCard;
    }
    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getLatestTime() {
        return latestTime;
    }
    public void setLatestTime(String latestTime) {
        this.latestTime = latestTime;
    }
    public String getReferenceTime() {
        return referenceTime;
    }
    public void setReferenceTime(String referenceTime) {
        this.referenceTime = referenceTime;
    }
    public String getJobTimeStamp() {
        return jobTimeStamp;
    }
    public void setJobTimeStamp(String jobTimeStamp) {
        this.jobTimeStamp = jobTimeStamp;
    }
    public String getReUploadFlg() {
        return reUploadFlg;
    }
    public void setReUploadFlg(String reUploadFlg) {
        this.reUploadFlg = reUploadFlg;
    }
    public String getFailType() {
        return failType;
    }
    public void setFailType(String failType) {
        this.failType = failType;
    }
}

+ 59 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/PatientIdentity.java

@ -0,0 +1,59 @@
package com.yihu.ehr.model;
import java.util.HashSet;
import java.util.Set;
/**
 * 病人身份标识
 * 病人ID, 事件号(门诊号,住院号等),卡号,身份证号
 * 目前使用的是病人ID和事件号
 *
 * @author Air
 * @version 1.0
 * @created 2015.06.16 16:29
 */
public class PatientIdentity {
    public static final String PATIENT_ID = "PATIENT_ID";
    public static final String LOCAL_CARD_NO = "CARD_NO";
    public static final String ID_CARD = "DE02_01_030_00";
    public static Set<String> EVENT_NO_SET = new HashSet<>();
    private String eventNoCode;
    private String refTimeCode;
    public PatientIdentity(String eventNoCode, String refTimeCode) {
        this.eventNoCode = eventNoCode;
        this.refTimeCode = refTimeCode;
        EVENT_NO_SET.add(eventNoCode);
    }
    public static String getPatientIDCode() {
        return PATIENT_ID;
    }
    public static String getLocalCardNoCode() {
        return LOCAL_CARD_NO;
    }
    public static String getIdCardCode() {
        return ID_CARD;
    }
    public static Set<String> getEventNoSet() {
        return EVENT_NO_SET;
    }
    public static void addEventNoCode(String eventNoCode) {
        EVENT_NO_SET.add(eventNoCode);
    }
    public String getEventNoCode() {
        return eventNoCode;
    }
    public String getRefTimeCode() {
        return refTimeCode;
    }
}

+ 57 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/RespResult.java

@ -0,0 +1,57 @@
package com.yihu.ehr.model;
/**
 * Created by chenweida on 2016/3/21.
 * 开放接口返回的实体类
 */
public class RespResult {
    String transactionCode;
    String respCode="10000";
    String respMessage="成功";
    String page;
    String data;
    public String getTransactionCode() {
        return transactionCode;
    }
    public void setTransactionCode(String transactionCode) {
        this.transactionCode = transactionCode;
    }
    public String getRespCode() {
        return respCode;
    }
    public void setRespCode(String respCode) {
        this.respCode = respCode;
    }
    public String getRespMessage() {
        return respMessage;
    }
    public void setRespMessage(String respMessage) {
        this.respMessage = respMessage;
    }
    public String getPage() {
        return page;
    }
    public void setPage(String page) {
        this.page = page;
    }
    public String getData() {
        return data;
    }
    public void setData(String data) {
        this.data = data;
    }
}

+ 44 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/SystemParams.java

@ -0,0 +1,44 @@
package com.yihu.ehr.model;
/**
 * Created by hzp on 2016/2/26.
 */
public class SystemParams {
    private String orgCode;
    private String orgName;
    private String interval;
    private String updateInterval;
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    public String getInterval() {
        return interval;
    }
    public void setInterval(String interval) {
        this.interval = interval;
    }
    public String getUpdateInterval() {
        return updateInterval;
    }
    public void setUpdateInterval(String updateInterval) {
        this.updateInterval = updateInterval;
    }
}

+ 45 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/UserInfo.java

@ -0,0 +1,45 @@
package com.yihu.ehr.model;
/**
 * 用户信息
 * Created by hzp on 2016/3/3.
 */
public class UserInfo {
    private String loginCode;
    private String realName;
    private String orgCode;
    private String orgName;
    public String getLoginCode() {
        return loginCode;
    }
    public void setLoginCode(String loginCode) {
        this.loginCode = loginCode;
    }
    public String getRealName() {
        return realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
}

+ 15 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/BaseEntity.java

@ -0,0 +1,15 @@
package com.yihu.ehr.model.entity;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
/**
 * Created by lingfeng on 2016/3/2.
 */
public class BaseEntity {
    protected static DBHelper db;
    public void setDBHelper(DBHelper db) {
        if (this.db == null) {
            this.db = db;
        }
    }
}

+ 157 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDataSet.java

@ -0,0 +1,157 @@
package com.yihu.ehr.model.entity.adapter;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.model.PatientIdentity;
import com.yihu.ehr.model.entity.BaseEntity;
import com.yihu.ehr.model.entity.standard.StdMetaDataT;
import com.yihu.ehr.util.operator.CollectionUtil;
import org.json.JSONObject;
import java.util.*;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 11:29
 */
public class AdapterDataSet extends BaseEntity {
    private List<AdapterMetaData> adapterMetaDataList;
    private AdapterDataSetT adapterDataSetT;
    private Map<String, AdapterMetaData> adapterMetaDataMap;
    private List<StdMetaDataT> stdMetaDataList;
    private Map<String, StdMetaDataT> stdMetaDataMap;
    private String eventNoCode;
    public AdapterDataSet(AdapterDataSetT adapterDataSetT, DBHelper db) {
        setDBHelper(db);
        this.adapterDataSetT = adapterDataSetT;
        getAdapterMetaDataList();
        getAdapterMetaDataMap();
        getStdMetaDataList();
        getStdMetaDataMap();
    }
    public AdapterDataSetT getAdapterDataSetT() {
        return adapterDataSetT;
    }
    public List<AdapterMetaData> getAdapterMetaDataList() {
        if (CollectionUtil.isEmpty(adapterMetaDataList)) {
            adapterMetaDataList = new ArrayList<>();
            List<JSONObject> adapterMetaDataTList = db.query( "select id, std_metadata_id, std_metadata_code, org_metadata_code from adapter_metadata where adapter_dataset_id = ?", adapterDataSetT.getId());
            if (!CollectionUtil.isEmpty(adapterMetaDataTList)) {
                for (JSONObject json : adapterMetaDataTList) {
                    AdapterMetaDataT adapterMetaDataT = new AdapterMetaDataT();
                    adapterMetaDataT.setId(json.getInt("id"));
                    adapterMetaDataT.setStdMetadataId(json.getInt("std_metadata_id"));
                    adapterMetaDataT.setStdMetadataCode(json.getString("std_metadata_code"));
                    if (!json.isNull("org_metadata_code")) {
                        adapterMetaDataT.setOrgMetadataCode(json.getString("org_metadata_code"));
                    }
                    adapterMetaDataList.add(new AdapterMetaData(adapterMetaDataT, db));
                }
            }
        }
        return adapterMetaDataList;
    }
    public List<StdMetaDataT> getStdMetaDataList() {
        if (CollectionUtil.isEmpty(stdMetaDataList)) {
            stdMetaDataList = new ArrayList<>();
            List<JSONObject> stdMetaDataTList = db.query( "select id, code, dict_code from std_metadata where dataset_id = ?", adapterDataSetT.getStdDatasetId());
            if (!CollectionUtil.isEmpty(stdMetaDataTList)) {
                for (JSONObject json : stdMetaDataTList) {
                    StdMetaDataT stdMetaDataT = new StdMetaDataT();
                    stdMetaDataT.setId(json.getInt("id"));
                    stdMetaDataT.setCode(json.getString("code"));
                    if (!json.isNull("dict_code")) {
                        stdMetaDataT.setDictCode(json.getString("dict_code"));
                    }
                    stdMetaDataList.add(stdMetaDataT);
                }
            }
        }
        return stdMetaDataList;
    }
    public Map<String, AdapterMetaData> getAdapterMetaDataMap() {
        if (CollectionUtil.isEmpty(adapterMetaDataList)) {
            getAdapterMetaDataList();
        }
        if (!CollectionUtil.isEmpty(adapterMetaDataList)) {
            if (adapterMetaDataMap == null) {
                adapterMetaDataMap = new HashMap<>();
                for (AdapterMetaData adapterMetaData : adapterMetaDataList) {
                    adapterMetaDataMap.put(adapterMetaData.getAdapterMetaDataT().getStdMetadataCode(), adapterMetaData);
                }
            }
        }
        return adapterMetaDataMap;
    }
    public Map<String, StdMetaDataT> getStdMetaDataMap() {
        if (CollectionUtil.isEmpty(stdMetaDataList)) {
            getStdMetaDataList();
        }
        if (!CollectionUtil.isEmpty(stdMetaDataList)) {
            if (stdMetaDataMap == null) {
                stdMetaDataMap = new HashMap<>();
                for (StdMetaDataT stdMetaDataT : stdMetaDataList) {
                    stdMetaDataMap.put(stdMetaDataT.getCode(), stdMetaDataT);
                }
            }
        }
        return stdMetaDataMap;
    }
    public StdMetaDataT getStdMetaData(String code) {
        if (getStdMetaDataMap() != null) {
            return getStdMetaDataMap().get(code);
        }
        return null;
    }
    public boolean isHavePatientID() {
        return findPatientIdentity(PatientIdentity.getPatientIDCode());
    }
    public boolean isHaveEventNo() {
        Set<String> eventNoSet = PatientIdentity.getEventNoSet();
        for (String eventNo : eventNoSet) {
            if (findPatientIdentity(eventNo)) {
                eventNoCode = eventNo;
                return true;
            }
        }
        return false;
    }
    public boolean isHaveLocalCardNo() {
        return findPatientIdentity(PatientIdentity.getLocalCardNoCode());
    }
    public boolean isHaveIdCard() {
        return findPatientIdentity(PatientIdentity.getIdCardCode());
    }
    public boolean findPatientIdentity(String code) {
        if (getStdMetaData(code) == null) {
            return false;
        }
        return true;
    }
    public String getEventNoCode() {
        return eventNoCode;
    }
}

+ 82 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDataSetT.java

@ -0,0 +1,82 @@
package com.yihu.ehr.model.entity.adapter;
/**
 * 适配数据集
 *
 * @author Airhead
 * @version 1.0
 * @created 08-6月-2015 10:25:34
 */
public class AdapterDataSetT {
    private int id;
    private String orgDatasetCode;
    private Integer stdDatasetId;
    private String stdDatasetCode;
    private Integer orgDatasetId;
    private String orgDatasetName;
    private String stdDatasetName;
    public AdapterDataSetT() {
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getOrgDatasetCode() {
        return orgDatasetCode;
    }
    public void setOrgDatasetCode(String orgDatasetCode) {
        this.orgDatasetCode = orgDatasetCode;
    }
    public Integer getStdDatasetId() {
        return stdDatasetId;
    }
    public void setStdDatasetId(Integer stdDatasetId) {
        this.stdDatasetId = stdDatasetId;
    }
    public Integer getOrgDatasetId() {
        return orgDatasetId;
    }
    public void setOrgDatasetId(Integer orgDatasetId) {
        this.orgDatasetId = orgDatasetId;
    }
    public String getStdDatasetCode() {
        return stdDatasetCode;
    }
    public void setStdDatasetCode(String stdDatasetCode) {
        this.stdDatasetCode = stdDatasetCode;
    }
    public String getOrgDatasetName() {
        return orgDatasetName;
    }
    public void setOrgDatasetName(String orgDatasetName) {
        this.orgDatasetName = orgDatasetName;
    }
    public String getStdDatasetName() {
        return stdDatasetName;
    }
    public void setStdDatasetName(String stdDatasetName) {
        this.stdDatasetName = stdDatasetName;
    }
    public void finalize() throws Throwable {
    }
}//end AdapterDataSetT

+ 56 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDict.java

@ -0,0 +1,56 @@
package com.yihu.ehr.model.entity.adapter;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.model.entity.BaseEntity;
import org.json.JSONObject;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 11:31
 */
public class AdapterDict extends BaseEntity {
    public static final String INVALID_ADAPTER_DICT = "";   //"Invalid Adapter";
    private AdapterDictT adapterDictT;
    public AdapterDict(AdapterDictT adapterDictT, DBHelper db) {
        setDBHelper(db);
        this.adapterDictT = adapterDictT;
    }
    public Boolean isValidAdapterDict() {
        return adapterDictT != null;
    }
    public String getStdDictItemValueByCode(String orgItemCode) {
        JSONObject json = db.load("select std_dict_item_value from adapter_dict_item where adapter_dict_id = ? and org_dict_item_code = ?", adapterDictT.getId(), orgItemCode);
        if (json == null || json.isNull("std_dict_item_value")) {
            return new String(INVALID_ADAPTER_DICT);
        }
        return json.getString("std_dict_item_value");
    }
    public String getStdDictItemCodeByValue(String orgItemValue) {
        JSONObject json = db.load("select std_dict_item_code from adapter_dict_item where adapter_dict_id = ? and org_dict_item_value = ?", adapterDictT.getId(), orgItemValue);
        if (json == null || json.isNull("std_dict_item_code")) {
            return new String(INVALID_ADAPTER_DICT);
        }
        return json.getString("std_dict_item_code");
    }
    public String getStdDictItemCodeByCode(String orgItemCode) {
        JSONObject json = db.load("select std_dict_item_code from adapter_dict_item where adapter_dict_id = ? and org_dict_item_code = ?", adapterDictT.getId(), orgItemCode);
        if (json == null || json.isNull("std_dict_item_code")) {
            return new String(INVALID_ADAPTER_DICT);
        }
        return json.getString("std_dict_item_code");
    }
    public String getStdDictItemValueByValue(String orgItemValue) {
        JSONObject json = db.load("select std_dict_item_value from adapter_dict_item where adapter_dict_id = ? and org_dict_item_value = ?", adapterDictT.getId(), orgItemValue);
        if (json == null || json.isNull("std_dict_item_value")) {
            return new String(INVALID_ADAPTER_DICT);
        }
        return json.getString("std_dict_item_value");
    }
}

+ 18 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictItem.java

@ -0,0 +1,18 @@
package com.yihu.ehr.model.entity.adapter;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.model.entity.BaseEntity;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 11:33
 */
public class AdapterDictItem extends BaseEntity {
    private AdapterDictItemT adapterDictItemT;
    public AdapterDictItem(AdapterDictItemT adapterDictItemT, DBHelper db) {
        setDBHelper(db);
        this.adapterDictItemT = adapterDictItemT;
    }
}

+ 93 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictItemT.java

@ -0,0 +1,93 @@
package com.yihu.ehr.model.entity.adapter;
/**
 * 适配字典编码项
 *
 * @author Airhead
 * @version 1.0
 * @created 08-6月-2015 10:25:34
 */
public class AdapterDictItemT {
	private int id;
	private Integer stdDictItemId;
	private Integer orgDictItemId;
	private Integer adapterDictId;
	private String orgDictItemCode;
	private String orgDictItemValue;
	private String stdDictItemCode;
	private String stdDictItemValue;
	private Integer schemeId;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Integer getStdDictItemId() {
		return stdDictItemId;
	}
	public void setStdDictItemId(Integer stdDictItemId) {
		this.stdDictItemId = stdDictItemId;
	}
	public Integer getOrgDictItemId() {
		return orgDictItemId;
	}
	public void setOrgDictItemId(Integer orgDictItemId) {
		this.orgDictItemId = orgDictItemId;
	}
	public Integer getAdapterDictId() {
		return adapterDictId;
	}
	public void setAdapterDictId(Integer adapterDictId) {
		this.adapterDictId = adapterDictId;
	}
	public String getOrgDictItemCode() {
		return orgDictItemCode;
	}
	public void setOrgDictItemCode(String orgDictItemCode) {
		this.orgDictItemCode = orgDictItemCode;
	}
	public String getOrgDictItemValue() {
		return orgDictItemValue;
	}
	public void setOrgDictItemValue(String orgDictItemValue) {
		this.orgDictItemValue = orgDictItemValue;
	}
	public String getStdDictItemCode() {
		return stdDictItemCode;
	}
	public void setStdDictItemCode(String stdDictItemCode) {
		this.stdDictItemCode = stdDictItemCode;
	}
	public String getStdDictItemValue() {
		return stdDictItemValue;
	}
	public void setStdDictItemValue(String stdDictItemValue) {
		this.stdDictItemValue = stdDictItemValue;
	}
	public Integer getSchemeId() {
		return schemeId;
	}
	public void setSchemeId(Integer schemeId) {
		this.schemeId = schemeId;
	}
}//end AdapterDictItemT

+ 90 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictT.java

@ -0,0 +1,90 @@
package com.yihu.ehr.model.entity.adapter;
/**
 * 适配字典
 *
 * @author Airhead
 * @version 1.0
 * @created 08-6月-2015 10:25:34
 */
public class AdapterDictT {
    private int id;
    private Integer stdDictId;
    private Integer orgDictId;
    private Integer schemeId;
    private String stdDictCode;
    private String orgDictCode;
    private String orgDictName;
    private String stdDictName;
    public AdapterDictT() {
    }
    public void finalize() throws Throwable {
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Integer getStdDictId() {
        return stdDictId;
    }
    public void setStdDictId(Integer stdDictId) {
        this.stdDictId = stdDictId;
    }
    public Integer getOrgDictId() {
        return orgDictId;
    }
    public void setOrgDictId(Integer orgDictId) {
        this.orgDictId = orgDictId;
    }
    public Integer getSchemeId() {
        return schemeId;
    }
    public void setSchemeId(Integer schemeId) {
        this.schemeId = schemeId;
    }
    public String getStdDictCode() {
        return stdDictCode;
    }
    public void setStdDictCode(String stdDictCode) {
        this.stdDictCode = stdDictCode;
    }
    public String getOrgDictCode() {
        return orgDictCode;
    }
    public void setOrgDictCode(String orgDictCode) {
        this.orgDictCode = orgDictCode;
    }
    public String getOrgDictName() {
        return orgDictName;
    }
    public void setOrgDictName(String orgDictName) {
        this.orgDictName = orgDictName;
    }
    public String getStdDictName() {
        return stdDictName;
    }
    public void setStdDictName(String stdDictName) {
        this.stdDictName = stdDictName;
    }
}//end AdapterDictT

+ 102 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterMetaData.java

@ -0,0 +1,102 @@
package com.yihu.ehr.model.entity.adapter;
import com.yihu.ehr.common.constants.DictDataType;
import com.yihu.ehr.common.constants.MetaDataType;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.model.entity.BaseEntity;
import com.yihu.ehr.model.entity.standard.StdMetaDataT;
import com.yihu.ehr.util.operator.StringUtil;
import org.json.JSONObject;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 11:31
 */
public class AdapterMetaData extends BaseEntity {
    private AdapterMetaDataT adapterMetaDataT;
    private AdapterDict adapterDict;
    private StdMetaDataT stdMetaDataT;
    public AdapterMetaData(AdapterMetaDataT adapterMetaDataT, DBHelper db) {
        setDBHelper(db);
        this.adapterMetaDataT = adapterMetaDataT;
    }
    public AdapterMetaDataT getAdapterMetaDataT() {
        return adapterMetaDataT;
    }
    public AdapterDict getAdapterDict() {
        if (adapterDict == null) {
            StdMetaDataT metaDataT = getStdMetaDataT();
            if (!StringUtil.isEmpty(metaDataT.getDictCode())) {
                JSONObject json = db.load("select id, std_dict_code, std_dict_id, org_dict_code,org_dict_id from adapter_dict where std_dict_code = ?", metaDataT.getDictCode());
                if (json != null) {
                    AdapterDictT adapterDictT = new AdapterDictT();
                    adapterDictT.setId(json.getInt("id"));
                    adapterDictT.setStdDictCode(json.getString("std_dict_code"));
                    if (!json.isNull("org_dict_code")) {
                        adapterDictT.setOrgDictCode(json.getString("org_dict_code"));
                    }
                    adapterDictT.setStdDictId(json.getInt("std_dict_id"));
                    if (!json.isNull("org_dict_id")) {
                        adapterDictT.setOrgDictId(json.getInt("org_dict_id"));
                    }
                    adapterDict = new AdapterDict(adapterDictT, db);
                }
            }
        }
        return adapterDict;
    }
    public StdMetaDataT getStdMetaDataT() {
        if (stdMetaDataT == null) {
            JSONObject json = db.load("select id, code, dict_code, dict_value_type, type from std_metadata where id = ?", adapterMetaDataT.getStdMetadataId());
            if (json != null) {
                stdMetaDataT = new StdMetaDataT();
                stdMetaDataT.setId(json.getInt("id"));
                if (!json.isNull("code")) {
                    stdMetaDataT.setCode(json.getString("code"));
                }
                if (!json.isNull("type")) {
                    stdMetaDataT.setType(json.getString("type"));
                }
                if (!json.isNull("dict_code")) {
                    stdMetaDataT.setDictCode(json.getString("dict_code"));
                }
                if (!json.isNull("dict_value_type") && json.getString("dict_value_type").length()>0) {
                    stdMetaDataT.setDictValueType(json.getInt("dict_value_type"));
                }
            }
            return stdMetaDataT;
        }
        return stdMetaDataT;
    }
    public DictDataType getOrgDictDataType() {
        Integer orgDictDataType = adapterMetaDataT.getOrgDictDataType();
        if (orgDictDataType == null){
            return DictDataType.VALUE;
        }
        return DictDataType.values()[orgDictDataType];
    }
    public DictDataType getStdDictDataType() {
        if (stdMetaDataT == null) {
            getStdMetaDataT();
        }
        String dictCode = stdMetaDataT.getDictCode();
        String type = stdMetaDataT.getType();
        int dictValueType;
        if (!StringUtil.isEmpty(dictCode) && (type.equals(MetaDataType.S2.name()) || type.equals(MetaDataType.S3.name()))) {
            dictValueType = DictDataType.CODE.ordinal();
        } else {
            dictValueType = DictDataType.VALUE.ordinal();
        }
        return DictDataType.values()[dictValueType];
    }
}

+ 96 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterMetaDataT.java

@ -0,0 +1,96 @@
package com.yihu.ehr.model.entity.adapter;
/**
 * 适配数据元
 *
 * @author Airhead
 * @version 1.0
 * @created 08-6月-2015 10:25:34
 */
public class AdapterMetaDataT {
    private int id;
    private Integer stdMetadataId;
    private Integer orgMetadataId;
    private String orgMetadataCode;
    private Integer adapterDatasetId;
    private String stdMetadataCode;
    private Integer orgDictDataType;
    private String stdMetadataName;
    private String orgMetadataName;
    public void finalize() throws Throwable {
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Integer getStdMetadataId() {
        return stdMetadataId;
    }
    public void setStdMetadataId(Integer stdMetadataId) {
        this.stdMetadataId = stdMetadataId;
    }
    public Integer getOrgMetadataId() {
        return orgMetadataId;
    }
    public void setOrgMetadataId(Integer orgMetadataId) {
        this.orgMetadataId = orgMetadataId;
    }
    public String getOrgMetadataCode() {
        return orgMetadataCode;
    }
    public void setOrgMetadataCode(String orgMetadataCode) {
        this.orgMetadataCode = orgMetadataCode;
    }
    public Integer getAdapterDatasetId() {
        return adapterDatasetId;
    }
    public void setAdapterDatasetId(Integer adapterDatasetId) {
        this.adapterDatasetId = adapterDatasetId;
    }
    public String getStdMetadataCode() {
        return stdMetadataCode;
    }
    public void setStdMetadataCode(String stdMetadataCode) {
        this.stdMetadataCode = stdMetadataCode;
    }
    public Integer getOrgDictDataType() {
        return orgDictDataType;
    }
    public void setOrgDictDataType(Integer orgDictDataType) {
        this.orgDictDataType = orgDictDataType;
    }
    public String getStdMetadataName() {
        return stdMetadataName;
    }
    public void setStdMetadataName(String stdMetadataName) {
        this.stdMetadataName = stdMetadataName;
    }
    public String getOrgMetadataName() {
        return orgMetadataName;
    }
    public void setOrgMetadataName(String orgMetadataName) {
        this.orgMetadataName = orgMetadataName;
    }
}//end AdapterMetaDataT

+ 100 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/origin/OrgDataSetT.java

@ -0,0 +1,100 @@
package com.yihu.ehr.model.entity.origin;
/**
 * 数据集
 *
 * @created Created by Air on 2015/6/3.
 */
public class OrgDataSetT {
    private int id;
    private String name;
    private String code;
    private String publisher;
    private String keyWord;
    private String lang;
    private String catalog;
    private String summary;
    private Integer valid;
    private String refStandard;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getPublisher() {
        return publisher;
    }
    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }
    public String getKeyWord() {
        return keyWord;
    }
    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }
    public String getLang() {
        return lang;
    }
    public void setLang(String lang) {
        this.lang = lang;
    }
    public String getCatalog() {
        return catalog;
    }
    public void setCatalog(String catalog) {
        this.catalog = catalog;
    }
    public String getSummary() {
        return summary;
    }
    public void setSummary(String summary) {
        this.summary = summary;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public String getRefStandard() {
        return refStandard;
    }
    public void setRefStandard(String refStandard) {
        this.refStandard = refStandard;
    }
}

+ 54 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/origin/OrgDictItemT.java

@ -0,0 +1,54 @@
package com.yihu.ehr.model.entity.origin;
/**
 * 标准字典项
 *
 * @created Created by Air on 2015/6/3.
 */
public class OrgDictItemT {
    private int id;
    private String value;
    private String code;
    private Integer valid;
    private Integer dictId;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public Integer getDictId() {
        return dictId;
    }
    public void setDictId(Integer dictId) {
        this.dictId = dictId;
    }
}

+ 45 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/origin/OrgDictT.java

@ -0,0 +1,45 @@
package com.yihu.ehr.model.entity.origin;
/**
 * 标准字典
 *
 * @created Created by Air on 2015/6/3.
 */
public class OrgDictT {
    private int id;
    private String name;
    private String code;
    private Integer valid;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
}

+ 145 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/origin/OrgMetaDataT.java

@ -0,0 +1,145 @@
package com.yihu.ehr.model.entity.origin;
/**
 * 标准元数据
 *
 * @created Created by Air on 2015/6/3.
 */
public class OrgMetaDataT {
    private int id;
    private String name;
    private String code;
    private int datasetId;
    private String deCode;
    private String definition;
    private String type;
    private String format;
    private String dictCode;
    private Integer valid;
    private Integer nullable;
    private Integer dictValueType;
    private String columnName;
    private String columnType;
    private Integer primaryKey;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public int getDatasetId() {
        return datasetId;
    }
    public void setDatasetId(int datasetId) {
        this.datasetId = datasetId;
    }
    public String getDeCode() {
        return deCode;
    }
    public void setDeCode(String deCode) {
        this.deCode = deCode;
    }
    public String getDefinition() {
        return definition;
    }
    public void setDefinition(String definition) {
        this.definition = definition;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getFormat() {
        return format;
    }
    public void setFormat(String format) {
        this.format = format;
    }
    public String getDictCode() {
        return dictCode;
    }
    public void setDictCode(String dictCode) {
        this.dictCode = dictCode;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public Integer getNullable() {
        return nullable;
    }
    public void setNullable(Integer nullable) {
        this.nullable = nullable;
    }
    public Integer getDictValueType() {
        return dictValueType;
    }
    public void setDictValueType(Integer dictValueType) {
        this.dictValueType = dictValueType;
    }
    public String getColumnName() {
        return columnName;
    }
    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }
    public String getColumnType() {
        return columnType;
    }
    public void setColumnType(String columnType) {
        this.columnType = columnType;
    }
    public Integer getPrimaryKey() {
        return primaryKey;
    }
    public void setPrimaryKey(Integer primaryKey) {
        this.primaryKey = primaryKey;
    }
}

+ 177 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdDataSetT.java

@ -0,0 +1,177 @@
package com.yihu.ehr.model.entity.standard;
import com.yihu.ehr.common.constants.Constants;
/**
 * 数据集
 *
 * @created Created by Air on 2015/6/3.
 */
public class StdDataSetT {
    private int id;
    private String name;
    private String code;
    private String publisher;
    private String keyWord;
    private String lang;
    private String catalog;
    private String summary;
    private String version;
    private Integer valid;
    private String innerVersion;
    private String refStandard;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getPublisher() {
        return publisher;
    }
    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }
    public String getKeyWord() {
        return keyWord;
    }
    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }
    public String getLang() {
        return lang;
    }
    public void setLang(String lang) {
        this.lang = lang;
    }
    public String getCatalog() {
        return catalog;
    }
    public void setCatalog(String catalog) {
        this.catalog = catalog;
    }
    public String getSummary() {
        return summary;
    }
    public void setSummary(String summary) {
        this.summary = summary;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public String getInnerVersion() {
        return innerVersion;
    }
    public void setInnerVersion(String innerVersion) {
        this.innerVersion = innerVersion;
    }
    public String getRefStandard() {
        return refStandard;
    }
    public void setRefStandard(String publisherCode) {
        this.refStandard = publisherCode;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StdDataSetT that = (StdDataSetT) o;
        if (id != that.id) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (code != null ? !code.equals(that.code) : that.code != null) return false;
        if (publisher != null ? !publisher.equals(that.publisher) : that.publisher != null) return false;
        if (keyWord != null ? !keyWord.equals(that.keyWord) : that.keyWord != null) return false;
        if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false;
        if (catalog != null ? !catalog.equals(that.catalog) : that.catalog != null) return false;
        if (summary != null ? !summary.equals(that.summary) : that.summary != null) return false;
        if (version != null ? !version.equals(that.version) : that.version != null) return false;
        if (valid != null ? !valid.equals(that.valid) : that.valid != null) return false;
        if (innerVersion != null ? !innerVersion.equals(that.innerVersion) : that.innerVersion != null) return false;
        if (refStandard != null ? !refStandard.equals(that.refStandard) : that.refStandard != null)
            return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (code != null ? code.hashCode() : 0);
        result = 31 * result + (publisher != null ? publisher.hashCode() : 0);
        result = 31 * result + (keyWord != null ? keyWord.hashCode() : 0);
        result = 31 * result + (lang != null ? lang.hashCode() : 0);
        result = 31 * result + (catalog != null ? catalog.hashCode() : 0);
        result = 31 * result + (summary != null ? summary.hashCode() : 0);
        result = 31 * result + (version != null ? version.hashCode() : 0);
        result = 31 * result + (valid != null ? valid.hashCode() : 0);
        result = 31 * result + (innerVersion != null ? innerVersion.hashCode() : 0);
        result = 31 * result + (refStandard != null ? refStandard.hashCode() : 0);
        return result;
    }
    public StdDataSetT emptyTransform() {
        if (name == null) name = Constants.EMPTY;
        if (code == null) code = Constants.EMPTY;
        if (publisher == null) publisher = Constants.EMPTY;
        if (keyWord == null) keyWord = Constants.EMPTY;
        if (lang == null) lang = Constants.EMPTY;
        if (catalog == null) catalog = Constants.EMPTY;
        if (summary == null) summary = Constants.EMPTY;
        if (version == null) version = Constants.EMPTY;
        if (innerVersion == null) innerVersion = Constants.EMPTY;
        if (refStandard == null) refStandard = Constants.EMPTY;
        return this;
    }
}

+ 100 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdDictItemT.java

@ -0,0 +1,100 @@
package com.yihu.ehr.model.entity.standard;
/**
 * 标准字典项
 *
 * @created Created by Air on 2015/6/3.
 */
public class StdDictItemT {
    private int id;
    private String value;
    private String code;
    private Integer valid;
    private String version;
    private Integer dictId;
    private String innerVersion;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public String getInnerVersion() {
        return innerVersion;
    }
    public void setInnerVersion(String innerVersion) {
        this.innerVersion = innerVersion;
    }
    public Integer getDictId() {
        return dictId;
    }
    public void setDictId(Integer dictId) {
        this.dictId = dictId;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StdDictItemT that = (StdDictItemT) o;
        if (id != that.id) return false;
        if (value != null ? !value.equals(that.value) : that.value != null) return false;
        if (code != null ? !code.equals(that.code) : that.code != null) return false;
        if (valid != null ? !valid.equals(that.valid) : that.valid != null) return false;
        if (version != null ? !version.equals(that.version) : that.version != null) return false;
        if (innerVersion != null ? !innerVersion.equals(that.innerVersion) : that.innerVersion != null) return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (value != null ? value.hashCode() : 0);
        result = 31 * result + (code != null ? code.hashCode() : 0);
        result = 31 * result + (valid != null ? valid.hashCode() : 0);
        result = 31 * result + (version != null ? version.hashCode() : 0);
        result = 31 * result + (innerVersion != null ? innerVersion.hashCode() : 0);
        return result;
    }
}

+ 92 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdDictT.java

@ -0,0 +1,92 @@
package com.yihu.ehr.model.entity.standard;
/**
 * 标准字典
 *
 * @created Created by Air on 2015/6/3.
 */
public class StdDictT {
    private int id;
    private String name;
    private String code;
    private String version;
    private Integer valid;
    private String innerVersion;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public String getInnerVersion() {
        return innerVersion;
    }
    public void setInnerVersion(String innerVersion) {
        this.innerVersion = innerVersion;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StdDictT stdDictT = (StdDictT) o;
        if (id != stdDictT.id) return false;
        if (name != null ? !name.equals(stdDictT.name) : stdDictT.name != null) return false;
        if (code != null ? !code.equals(stdDictT.code) : stdDictT.code != null) return false;
        if (version != null ? !version.equals(stdDictT.version) : stdDictT.version != null) return false;
        if (valid != null ? !valid.equals(stdDictT.valid) : stdDictT.valid != null) return false;
        if (innerVersion != null ? !innerVersion.equals(stdDictT.innerVersion) : stdDictT.innerVersion != null)
            return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (code != null ? code.hashCode() : 0);
        result = 31 * result + (version != null ? version.hashCode() : 0);
        result = 31 * result + (valid != null ? valid.hashCode() : 0);
        result = 31 * result + (innerVersion != null ? innerVersion.hashCode() : 0);
        return result;
    }
}

+ 93 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdInnerVersionT.java

@ -0,0 +1,93 @@
package com.yihu.ehr.model.entity.standard;
import java.sql.Timestamp;
/**
 * 标准版本
 *
 * @created Created by Air on 2015/6/3.
 */
public class StdInnerVersionT {
    private String id;
    private String code;
    private String comment;
    private Integer valid;
    private Integer type;
    private Timestamp validDate;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getComment() {
        return comment;
    }
    public void setComment(String comment) {
        this.comment = comment;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public Timestamp getValidDate() {
        return validDate;
    }
    public void setValidDate(Timestamp validDate) {
        this.validDate = validDate;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StdInnerVersionT that = (StdInnerVersionT) o;
        if (id != that.id) return false;
        if (code != null ? !code.equals(that.code) : that.code != null) return false;
        if (comment != null ? !comment.equals(that.comment) : that.comment != null) return false;
        if (valid != null ? !valid.equals(that.valid) : that.valid != null) return false;
        if (type != null ? !type.equals(that.type) : that.type != null) return false;
        if (validDate != null ? !validDate.equals(that.validDate) : that.validDate != null) return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result = (code != null ? code.hashCode() : 0);
        result = 31 * result + (id != null ? id.hashCode() : 0);
        result = 31 * result + (comment != null ? comment.hashCode() : 0);
        result = 31 * result + (valid != null ? valid.hashCode() : 0);
        result = 31 * result + (type != null ? type.hashCode() : 0);
        result = 31 * result + (validDate != null ? validDate.hashCode() : 0);
        return result;
    }
}

+ 206 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdMetaDataT.java

@ -0,0 +1,206 @@
package com.yihu.ehr.model.entity.standard;
/**
 * 标准元数据
 *
 * @created Created by Air on 2015/6/3.
 */
public class StdMetaDataT {
    private int id;
    private String name;
    private String code;
    private int datasetId;
    private String deCode;
    private String definition;
    private String type;
    private String format;
    private String dictCode;
    private String version;
    private Integer valid;
    private Integer nullable;
    private String innerVersion;
    private Integer dictValueType;
    private String columnName;
    private String columnType;
    private Integer primaryKey;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public int getDatasetId() {
        return datasetId;
    }
    public void setDatasetId(int datasetId) {
        this.datasetId = datasetId;
    }
    public String getDeCode() {
        return deCode;
    }
    public void setDeCode(String innerCode) {
        this.deCode = innerCode;
    }
    public String getDefinition() {
        return definition;
    }
    public void setDefinition(String definition) {
        this.definition = definition;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getFormat() {
        return format;
    }
    public void setFormat(String format) {
        this.format = format;
    }
    public String getDictCode() {
        return dictCode;
    }
    public void setDictCode(String dictId) {
        this.dictCode = dictId;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public Integer getNullable() {
        return nullable;
    }
    public void setNullable(Integer nullable) {
        this.nullable = nullable;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public String getInnerVersion() {
        return innerVersion;
    }
    public void setInnerVersion(String innerVersion) {
        this.innerVersion = innerVersion;
    }
    public Integer getDictValueType() {
        return dictValueType;
    }
    public void setDictValueType(Integer dictValueType) {
        this.dictValueType = dictValueType;
    }
    public String getColumnName() {
        return columnName;
    }
    public void setColumnName(String column) {
        this.columnName = column;
    }
    public String getColumnType() {
        return columnType;
    }
    public void setColumnType(String columnType) {
        this.columnType = columnType;
    }
    public Integer getPrimaryKey() {
        return primaryKey;
    }
    public void setPrimaryKey(Integer primaryKey) {
        this.primaryKey = primaryKey;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StdMetaDataT that = (StdMetaDataT) o;
        if (id != that.id) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (code != null ? !code.equals(that.code) : that.code != null) return false;
        if (deCode != null ? !deCode.equals(that.deCode) : that.deCode != null) return false;
        if (definition != null ? !definition.equals(that.definition) : that.definition != null) return false;
        if (type != null ? !type.equals(that.type) : that.type != null) return false;
        if (format != null ? !format.equals(that.format) : that.format != null) return false;
        if (dictCode != null ? !dictCode.equals(that.dictCode) : that.dictCode != null) return false;
        if (version != null ? !version.equals(that.version) : that.version != null) return false;
        if (valid != null ? !valid.equals(that.valid) : that.valid != null) return false;
        if (dictValueType != null ? !dictValueType.equals(that.dictValueType) : that.dictValueType != null)
            return false;
        if (nullable != null ? !nullable.equals(that.nullable) : that.nullable != null) return false;
        if (innerVersion != null ? !innerVersion.equals(that.innerVersion) : that.innerVersion != null) return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (code != null ? code.hashCode() : 0);
        result = 31 * result + (deCode != null ? deCode.hashCode() : 0);
        result = 31 * result + (definition != null ? definition.hashCode() : 0);
        result = 31 * result + (type != null ? type.hashCode() : 0);
        result = 31 * result + (format != null ? format.hashCode() : 0);
        result = 31 * result + (dictCode != null ? dictCode.hashCode() : 0);
        result = 31 * result + (version != null ? version.hashCode() : 0);
        result = 31 * result + (valid != null ? valid.hashCode() : 0);
        result = 31 * result + (nullable != null ? nullable.hashCode() : 0);
        result = 31 * result + (dictValueType != null ? dictValueType.hashCode() : 0);
        result = 31 * result + (innerVersion != null ? innerVersion.hashCode() : 0);
        return result;
    }
}

+ 20 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdVersion.java

@ -0,0 +1,20 @@
package com.yihu.ehr.model.entity.standard;
import com.yihu.ehr.model.entity.BaseEntity;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 15:25
 */
public class StdVersion extends BaseEntity {
    private StdVersionT stdVersionT;
    public StdVersion(StdVersionT stdVersionT) {
        this.stdVersionT = stdVersionT;
    }
    public StdVersionT getStdVersionT(){
        return stdVersionT;
    }
}

+ 93 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/entity/standard/StdVersionT.java

@ -0,0 +1,93 @@
package com.yihu.ehr.model.entity.standard;
import java.sql.Timestamp;
/**
 * 标准版本
 *
 * @created Created by Air on 2015/6/3.
 */
public class StdVersionT {
    private int id;
    private String code;
    private String comment;
    private Integer valid;
    private Integer type;
    private Timestamp validDate;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getComment() {
        return comment;
    }
    public void setComment(String comment) {
        this.comment = comment;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public Timestamp getValidDate() {
        return validDate;
    }
    public void setValidDate(Timestamp validDate) {
        this.validDate = validDate;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StdVersionT that = (StdVersionT) o;
        if (id != that.id) return false;
        if (code != null ? !code.equals(that.code) : that.code != null) return false;
        if (comment != null ? !comment.equals(that.comment) : that.comment != null) return false;
        if (valid != null ? !valid.equals(that.valid) : that.valid != null) return false;
        if (type != null ? !type.equals(that.type) : that.type != null) return false;
        if (validDate != null ? !validDate.equals(that.validDate) : that.validDate != null) return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (code != null ? code.hashCode() : 0);
        result = 31 * result + (comment != null ? comment.hashCode() : 0);
        result = 31 * result + (valid != null ? valid.hashCode() : 0);
        result = 31 * result + (type != null ? type.hashCode() : 0);
        result = 31 * result + (validDate != null ? validDate.hashCode() : 0);
        return result;
    }
}

+ 29 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/verify/AuthorizationVeryify.java

@ -0,0 +1,29 @@
package com.yihu.ehr.model.verify;
/**
 * @author Airhead
 * @version 1.0
 * @created 22-5-2015 11:24:23
 */
public class AuthorizationVeryify implements IVerifier {
	public AuthorizationVeryify(){
	}
	public void finalize() throws Throwable {
	}
	/**
	 *
	 */
	public boolean check(){
		return false;
	}
	@Override
	public String getErrorInfo() {
		return null;
	}
}//end AuthorizationVeryify

+ 15 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/verify/IVerifier.java

@ -0,0 +1,15 @@
package com.yihu.ehr.model.verify;
/**
 * @author Airhead
 * @version 1.0
 * @created 22-5-2015 11:24:26
 */
public interface IVerifier {
    /**
     */
    boolean check();
    String getErrorInfo();
}

+ 37 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/verify/MetaDataVerify.java

@ -0,0 +1,37 @@
package com.yihu.ehr.model.verify;
import com.yihu.ehr.model.entity.standard.StdMetaDataT;
/**
 * @author Airhead
 * @version 1.0
 * @created 22-5-2015 11:24:25
 */
public class MetaDataVerify implements IVerifier {
    private StdMetaDataT stdMetaDataT;
    private String value;
    private String errorInfo;
    public MetaDataVerify(StdMetaDataT stdMetaDataT, String value) {
        this.stdMetaDataT = stdMetaDataT;
        this.value = value;
    }
    public void finalize() throws Throwable {
    }
    /**
     * 目前不做任何数据校验
     * 必要时根据StdMetaData的type, format内容做校验
     */
    public boolean check() {
        return true;
    }
    @Override
    public String getErrorInfo() {
        return errorInfo;
    }
}//end MetaDataVerify

+ 29 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/model/verify/RegistrationVerify.java

@ -0,0 +1,29 @@
package com.yihu.ehr.model.verify;
/**
 * @author Airhead
 * @version 1.0
 * @created 22-5-2015 11:24:26
 */
public class RegistrationVerify implements IVerifier {
	public RegistrationVerify(){
	}
	public void finalize() throws Throwable {
	}
	/**
	 *
	 */
	public boolean check(){
		return false;
	}
	@Override
	public String getErrorInfo() {
		return null;
	}
}//end RegistrationVerify

+ 182 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/DataAcquisitionManager.java

@ -0,0 +1,182 @@
package com.yihu.ehr.service;
import com.yihu.ehr.dbhelper.common.DBList;
import com.yihu.ehr.dbhelper.common.DBQuery;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.framework.model.DataGridResult;
import com.yihu.ehr.framework.model.Result;
import com.yihu.ehr.model.DataAcquistion;
import com.yihu.ehr.service.intf.IDataAcquisitionManager;
import com.yihu.ehr.util.httpclient.HttpHelper;
import com.yihu.ehr.util.json.JSON;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.Map;
import java.util.UUID;
/**
 * Created by chenweida on 2016/3/18.
 */
@Service("dataAcquisitionManager")
public class DataAcquisitionManager implements IDataAcquisitionManager {
    DBQuery query = new DBQuery();
    DBHelper db = new DBHelper();
    @Override
    public String gate(JSONObject jo, Map<String, Object> params) {
        String responMsg = "";
        String path = (String) jo.get("url");
        String requestType = (String) jo.get("request_type");//1是查询 2是文件上传
        String urlType = (String) jo.get("url_type");//1是post 2是 get
        //判断是http请求还是https
        responMsg = getResponMsg(path, requestType, urlType, params);
        return responMsg;
    }
    @Override
    public Result getDataAcquisition(int page, int size) throws Exception {
        String sql = "select * from data_acquisition where 1=1";
        DBList list = query.queryBySql(sql, page, size);
        return DataGridResult.fromDBList(list);
    }
    @Override
    public DataAcquistion getDataAcquisitionById(String dataId) throws Exception {
        String sql = "select * from data_acquisition where id='" + dataId + "'";
        DBList list = query.queryBySql(sql);
        if (list != null && list.getList().size() > 0) {
            DataAcquistion d = new DataAcquistion();
            d.setId((String) list.getList().get(0).get("id"));
            d.setName((String) list.getList().get(0).get("name"));
            d.setRequest_type((String) list.getList().get(0).get("request_type"));
            d.setTransactioncode((String) list.getList().get(0).get("transactioncode"));
            d.setUrl((String) list.getList().get(0).get("url"));
            d.setUrl_type((String) list.getList().get(0).get("url_type"));
            return d;
        } else {
            return null;
        }
    }
    @Override
    public Result addDataAcquisition(String url, String request_type, String transactioncode, String url_type, String name) throws Exception {
        String sql = "insert into data_acquisition (id,url,request_type,transactioncode,url_type,name) values " +
                "('" + UUID.randomUUID() + "'," +
                " '" + url + "' ," +
                " '" + request_type + "' ," +
                " '" + transactioncode + "' ," +
                " '" + url_type + "' ," +
                " '" + name + "' " +
                ")";
        db.execute(sql);
        return Result.success("保存成功");
    }
    @Override
    public Result getDataAcquisitionByCode(String transactioncode) throws Exception {
        String sql = "select * from data_acquisition where transactioncode='" + transactioncode + "'";
        DBList list = query.queryBySql(sql);
        if (list.getList() != null && list.getList().size() > 0) {
            return DataGridResult.fromDBList(list);
        } else {
            return null;
        }
    }
    @Override
    public Object getDataAcquisitionByName(String name) throws Exception {
        String sql = "select * from data_acquisition where name='" + name + "'";
        DBList list = query.queryBySql(sql);
        if (list.getList() != null && list.getList().size() > 0) {
            return DataGridResult.fromDBList(list);
        } else {
            return null;
        }
    }
    @Override
    public Object getDataAcquisitionByCode(String transactioncode, String id) throws Exception {
        String sql = "select * from data_acquisition where transactioncode='" + transactioncode + "' and id !='" + id + "'";
        DBList list = query.queryBySql(sql);
        if (list.getList() != null && list.getList().size() > 0) {
            return DataGridResult.fromDBList(list);
        } else {
            return null;
        }
    }
    @Override
    public Object getDataAcquisitionByName(String name, String id) throws Exception {
        String sql = "select * from data_acquisition where name='" + name + "' and id !='" + id + "'";
        DBList list = query.queryBySql(sql);
        if (list.getList() != null && list.getList().size() > 0) {
            return DataGridResult.fromDBList(list);
        } else {
            return null;
        }
    }
    @Override
    public Result updateDataAcquisition(String url, String request_type, String transactioncode, String url_type, String name, String id) throws Exception {
        String sql = "update data_acquisition set " +
                " url= '" + url + "' ," +
                " request_type='" + request_type + "' ," +
                " transactioncode='" + transactioncode + "' ," +
                " url_type='" + url_type + "' ," +
                " name='" + name + "' where id='" + id + "'";
        db.execute(sql);
        return Result.success("更新成功");
    }
    @Override
    public Result deleteAataAcquisition(String id) throws Exception {
        String sql = "delete from data_acquisition  where id='" + id + "'";
        db.execute(sql);
        return Result.success("删除成功");
    }
    private String getResponMsg(String path, String requestType, String urlType, Map<String, Object> params) {
        //1是拉推数据
        String responseMsg = "";
        if ("1".equals(requestType)) {
            if ("1".equals(urlType)) {
                //post
                responseMsg = HttpHelper.post(path, params).getBody();
            } else if ("2".equals(urlType)) {
                //get
                responseMsg = HttpHelper.get(path, params).getBody();
            }
            //2文件上传
        } else if ("2".equals(requestType)) {
            /*
            if ("1".equals(urlType)) {
                //post
                responseMsg = HttpHelper.post(path, params).getBody();
            } else if ("2".equals(urlType)) {
                //get
                responseMsg = HttpHelper.get(path, params).getBody();
            }
            */
            File f = JSON.json2File(params);
            //文件上传
           // if ("1".equals(urlType)) {
                //post
            //    responseMsg = HttpHelper.postFile(path, null, f).getBody();
            //}
            responseMsg = HttpHelper.postFile(path, null, f).getBody();
            //删除文件
            f.delete();
        }
        return responseMsg;
    }
}

+ 140 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/DatacollectManager.java

@ -0,0 +1,140 @@
package com.yihu.ehr.service;
import com.yihu.ehr.dbhelper.common.DBList;
import com.yihu.ehr.dbhelper.common.DBQuery;
import com.yihu.ehr.dbhelper.common.QueryCondition;
import com.yihu.ehr.dbhelper.common.QueryEntity;
import com.yihu.ehr.dbhelper.common.enums.Logical;
import com.yihu.ehr.dbhelper.common.enums.Operation;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.framework.model.DataGridResult;
import com.yihu.ehr.framework.model.Result;
import com.yihu.ehr.service.intf.IDatacollectManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;
/**
 * 采集管理
 * Created by HZP on 2016/02/26.
 */
@Service("datacollectManager")
public class DatacollectManager implements IDatacollectManager {
    DBQuery query = new DBQuery();
    DBHelper db = new DBHelper();
    /*
    获取数据集
     */
    @Override
    public DataGridResult getDataset(String name) throws Exception
    {
        String sql = "select * from adapter_dataset where org_dataset_id is not null";
        if(name!=null&&name.length()>0)
        {
            sql += " and (org_dataset_code like '%"+name+"%' or org_dataset_name like '%"+name+"%')";
        }
        DBList list = query.queryBySql(sql);
        return DataGridResult.fromDBList(list);
    }
    /*
        获取数据元
    */
    @Override
    public DataGridResult getMetadata(String name,String adapterDatasetId,int page,int size) throws Exception
    {
        String sql = "select a.*,b.definition,b.type,b.format from adapter_metadata a left join org_metadata b on a.org_metadata_id = b.id where a.org_metadata_id is not null";
        if(adapterDatasetId!=null&& adapterDatasetId.length()>0)
        {
            sql += " and a.adapter_dataset_id = '"+adapterDatasetId+"'";
        }
        if(name!=null&&name.length()>0)
        {
            sql += " and (a.org_metadata_code like '%"+name+"%' or a.org_metadata_name like '%"+name+"%')";
        }
        DBList list = query.queryBySql(sql,page,size);
        return DataGridResult.fromDBList(list);
    }
    /*
       获取跟踪数据
    */
    @Override
    public DataGridResult getJobLog(String patientId,String eventNo,String status,int page,int size) throws Exception
    {
        String sql = "select * from task_track where 1=1";
        if(patientId!=null&& patientId.length()>0)
        {
            sql += " and patient_id = '"+patientId+"'";
        }
        if(eventNo!=null&& eventNo.length()>0)
        {
            sql += " and event_no = '"+eventNo+"'";
        }
        if(status!=null&& status.length()>0)
        {
            sql += " and status = '"+status+"'";
        }
        DBList list = query.queryBySql(sql,page,size);
        return DataGridResult.fromDBList(list);
    }
    /*
       获取补采数据
    */
    @Override
    public DataGridResult getJobRepeat(int page,int size) throws Exception
    {
        String sql = "select * from crawler_supply where 1=1 and start_time is not null and end_time is not null";
        DBList list = query.queryBySql(sql,page,size);
        return DataGridResult.fromDBList(list);
    }
    /*
    新增补采
     */
    @Override
    @Transactional
    public Result addJobRepeat(String startTime,String endTime) throws Exception
    {
        String sql = "insert into crawler_supply (id,start_time,end_time,status) values ('"+ UUID.randomUUID() +"','"+startTime+"','"+endTime+"','0')";
        if(db.execute(sql))
        {
            return Result.success("保存成功!");
        }
        else{
            return Result.error(db.errorMessage);
        }
    }
    /*
    删除补采
     */
    @Override
    @Transactional
    public Result deleteJobRepeat(String id) throws Exception
    {
        String sql = "delete from crawler_supply where id = '"+id+"'";
        if(db.execute(sql))
        {
            return Result.success("删除成功!");
        }
        else{
            return Result.error(db.errorMessage);
        }
    }
}

+ 282 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/SystemManager.java

@ -0,0 +1,282 @@
package com.yihu.ehr.service;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.common.config.ThreadConfig;
import com.yihu.ehr.dbhelper.common.enums.CommonEnum;
import com.yihu.ehr.dbhelper.jdbc.DBDriver;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.framework.model.Result;
import com.yihu.ehr.model.DataSource;
import com.yihu.ehr.model.SystemParams;
import com.yihu.ehr.model.UserInfo;
import com.yihu.ehr.service.intf.ISystemManager;
import com.yihu.ehr.service.thread.StandardUpdateThread;
import com.yihu.ehr.service.thread.ThreadManage;
import com.yihu.ehr.util.httpclient.EsbHttp;
import com.yihu.ehr.util.httpclient.Response;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
/**
 * 总平台交互
 * Created by HZP on 2016/02/26.
 */
@Service("systemManager")
public class SystemManager implements ISystemManager {
    DBHelper db = new DBHelper();
    /*
    获取系统参数
     */
    @Override
    public SystemParams getSystemParams() throws Exception {
        List<JSONObject> list = db.query("select * from system_param");
        SystemParams re = new SystemParams();
        if (list != null) {
            for (JSONObject obj : list) {
                String key = obj.getString("param_key");
                String value = obj.getString("param_value");
                if (key.equals("ORG_CODE")) {
                    re.setOrgCode(value);
                } else if (key.equals("ORG_NAME")) {
                    re.setOrgName(value);
                } else if (key.equals("INTERVAL")) {
                    re.setInterval(value);
                } else if (key.equals("UPDATE_INTERVAL")) {
                    re.setUpdateInterval(value);
                }
            }
        }
        return re;
    }
    /*
    根据名称获取系统参数
     */
    @Override
    public String getSystemParam(String name) throws Exception {
        Object obj = db.scalar("select param_value from system_param where param_key='" + name + "'");
        if (obj != null) {
            return obj.toString();
        } else {
            return "";
        }
    }
    /*
    获取数据源
     */
    @Override
    public DataSource getDataSource() throws Exception {
        //第一行
        return db.load(DataSource.class, "select * from system_datasource");
    }
    /*
    新增系统参数
    */
    private void addSystemParams(String key, String value) throws Exception {
        String sql = "insert into system_param (id,param_key,param_value) values ('" + UUID.randomUUID() + "','" + key + "','" + value + "')";
        if (!db.execute(sql)) {
            throw new Exception(db.errorMessage);
        }
    }
    /*
    保存系统参数
     */
    @Transactional
    private void saveSystemParams(String key, String value) throws Exception {
        Object obj = db.scalar("select 1 from system_param where param_key='" + key + "'");
        if (obj==null) {
            addSystemParams(key, value);
        } else {
            String sql = "update system_param set param_value = '" + value + "' where param_key='" + key + "'";
            if (!db.execute(sql)) {
                throw new Exception(db.errorMessage);
            }
        }
    }
    /*
     保存系统参数
    */
    @Override
    @Transactional
    public Result saveParams(String interval, String updateInterval) throws Exception {
        //采集频率
        saveSystemParams("INTERVAL", interval);
        ThreadConfig.CRAWLER_THREAD_SLEEP_TIME = Integer.parseInt(interval);
        //更新频率
        saveSystemParams("UPDATE_INTERVAL", updateInterval);
        ThreadConfig.UPDATE_THREAD_SLEEP_TIME = Integer.parseInt(updateInterval);
        return Result.success("保存成功!");
    }
    /*
    保存数据源
     */
    @Override
    @Transactional
    public Result saveDataSource(String id, String name, String config) throws Exception {
        String sql = "insert into system_datasource (id,name,config) values ('" + UUID.randomUUID() + "','" + name + "','" + config + "')";
        if (id != null && id.length() > 0) {
            sql = "update system_datasource set name = '" + name + "',config='" + config + "' where id='" + id + "'";
        }
        if (db.execute(sql)) {
            return Result.success("保存成功!");
        } else {
            return Result.error(db.errorMessage);
        }
    }
    /*
    测试数据源
     */
    @Override
    public Result testDataSource(String uri) {
        try {
            DBDriver.registerDriver(uri);
            Connection conn = DriverManager.getConnection(uri);
            if(conn!=null) {
                String message="连接测试成功!";
                if(conn.isClosed())
                {
                    message = "连接测试失败!";
                }
                conn.close();
                return Result.success(message);
            }
            else {
                return Result.error("连接测试失败!");
            }
        }
        catch (Exception ex)
        {
            return Result.error(ex.getMessage());
        }
    }
    /*
    登录操作
    */
    @Override
    public Result loginAction(HttpSession session, String user, String password) {
        try {
            //特殊用户
            if (user.equals("admin") && password.equals("JKZL")) {
                UserInfo obj = new UserInfo();
                obj.setLoginCode("admin");
                obj.setRealName("管理员");
                obj.setOrgCode("JKZL");
                obj.setOrgName("健康之路");
                session.setAttribute("userInfo", obj);
                return Result.success("登录成功!");
            }
            //根据用户名/密码到总平台校验
            Response response = EsbHttp.loginAction(user, password);
            if (response != null && response.getStatusCode() == 200) {
                JSONObject obj = new JSONObject(response.getBody());
                if (obj.has("token"))//登录成功
                {
                    String token = obj.getString("token");
                    //获取用户信息
                    Response re = EsbHttp.getUserInfo(user, token);
                    if (re != null && re.getStatusCode() == 200) {
                        JSONObject userObject = new JSONObject(re.getBody());
                        UserInfo userInfo = new UserInfo();
                        userInfo.setLoginCode(user);
                        userInfo.setRealName(userObject.getString("realName"));
                        String orgCode = "";
                        String orgName = "";
                        if(userObject.has("organization") && !userObject.get("organization").equals(null)) {
                            JSONObject orgInfo = userObject.getJSONObject("organization");
                            orgCode = orgInfo.getString("orgCode");
                            orgName = orgInfo.getString("fullName");
                            userInfo.setOrgCode(orgCode);
                            userInfo.setOrgName(orgName);
                        }
                        else{
                            return Result.error("该用户未配置机构!");
                        }
                        session.setAttribute("userInfo", userInfo);
                        //判断组织编码是否为空
                        String orgCodeOld = this.getSystemParam("ORG_CODE");
                        if (orgCodeOld==null || orgCodeOld.length() == 0) {
                            this.saveSystemParams("FINGER_PRINT", UUID.randomUUID().toString());
                            this.saveSystemParams("ORG_CODE", orgCode);
                            this.saveSystemParams("ORG_NAME", orgName);
                            //启动标准
                            SysConfig.getInstance().setOrgCode(orgCode);
                            Thread standardUpdateThread = new Thread(new StandardUpdateThread());
                            ThreadManage.add(ThreadManage.STANDARD_UPDATE_THREAD, standardUpdateThread);
                            ThreadManage.setUpdateInterval();
                            if (!standardUpdateThread.isAlive()) {
                                standardUpdateThread.start();
                            }
                            return Result.success("登录成功!");
                        }
                        else {
                            if (orgCodeOld.equals(orgCode)) {
                                return Result.success("登录成功!");
                            } else {
                                return Result.error("机构编码不一致!");
                            }
                        }
                    }
                    else{
                        return Result.error("获取用户信息失败!");
                    }
                }
                else {
                    if(obj.has("message"))
                    {
                        return Result.error("登录失败!"+obj.getString("message"));
                    }
                    else{
                        return Result.error("登录失败!");
                    }
                }
            }
            else {
                String msg = "登录失败。";
                if (response != null)
                {
                    msg +="(错误代码:"+ response.getStatusCode() + ",错误信息:"+response.getBody()+")";
                }
                return Result.error(msg);
            }
        }
        catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
}

+ 227 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/CrawlerManager.java

@ -0,0 +1,227 @@
package com.yihu.ehr.service.crawler;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.common.constants.Constants;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.model.DataSource;
import com.yihu.ehr.model.Patient;
import com.yihu.ehr.model.entity.adapter.AdapterDataSet;
import com.yihu.ehr.model.entity.adapter.AdapterDataSetT;
import com.yihu.ehr.util.db.DBSessionFactory;
import com.yihu.ehr.util.httpclient.EsbHttp;
import com.yihu.ehr.util.log.LogUtil;
import com.yihu.ehr.util.operator.*;
import org.json.JSONObject;
import java.sql.SQLException;
import java.util.*;
/**
 * 标准管理,负责版本的升级,解包及相关安全
 *
 * @created Created by Air on 2015/6/3.
 */
public class CrawlerManager {
    private DBHelper db;
    private static volatile CrawlerManager instance;
    private static DataCollectDispatcher dispatch;
    private List<AdapterDataSet> adapterDataSetList;
    private List<DataSource> dataSourceList;
    private List<Patient> patientList;
    public CrawlerManager() {
        db = new DBHelper();
        dispatch = DataCollectDispatcher.getInstance();
    }
    public void finalize() throws Throwable {
    }
    public static CrawlerManager getInstance() {
        if (instance == null) {
            synchronized (CrawlerManager.class) {
                if (instance == null) {
                    try {
                        instance = new CrawlerManager();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return instance;
    }
    public void dataCrawlerFrequency() {
        List<JSONObject> versionList = db.query("select code from std_inner_version order by code desc");
        if(versionList==null)
        {
            LogUtil.info("标准数据还未初始化,请确认!");
            return;
        }
        String uuid = UUID.randomUUID().toString();
        Date lastCralwerTime = DateUtil.getSysDateTime();
        lastCralwerTime = DateUtil.formatYMDToYMDHMS(lastCralwerTime.toString());
        JSONObject json = db.load("select param_value from system_param where param_key = 'LAST_TIME'");
        if (!json.isNull("param_value") && !StringUtil.isEmpty(json.getString("param_value"))) {
            lastCralwerTime = DateUtil.formatYMDToYMDHMS(json.getString("param_value"));
        }
        Date current = DateUtil.fromatDateToTimestamp(DateUtil.getSysDateTime());
        db.execute("update system_param set param_value = '" + current.toString() + "'  where param_key = 'LAST_TIME'");
        LogUtil.info("采集任务开始!任务ID:" + uuid + ",采集时间:" + lastCralwerTime + "~" + current);
        if ((current.getTime() - lastCralwerTime.getTime()) <= 0) {
            LogUtil.info("采集不予执行,时间间隔小于或等于0!任务ID:" + uuid + ",采集时间:" + lastCralwerTime + "~" + current);
            return;
        }
        String message = dataCrawler(lastCralwerTime, current, uuid, 0);
        LogUtil.info("采集任务结束!任务ID:" + uuid + ",采集时间:" + lastCralwerTime + "~" + current + "\n" +message);
    }
    public void dataCrawlerSupply() {
        List<JSONObject> versionList = db.query("select code from std_inner_version order by code desc");
        if(versionList==null)
        {
            LogUtil.info("标准数据还未初始化,请确认!");
            return;
        }
        List<JSONObject> jsonList = db.query("select * from crawler_supply where status != 1");
        if (!CollectionUtil.isEmpty(jsonList)) {
            for (JSONObject json : jsonList) {
                String id = json.getString("id");
                db.execute("update crawler_supply set status = 2 where id = '"+id+"'");
                Date startTime = DateUtil.formatYMDToYMDHMS(json.getString("start_time"));
                Date endTime = DateUtil.formatYMDToYMDHMS(json.getString("end_time"));
                String message = "";
                if(startTime!=null && endTime!=null) {
                    LogUtil.info("补采任务开始!任务ID:" + id + ",采集时间:" + startTime + "~" + endTime);
                    if ((endTime.getTime() - startTime.getTime()) <= 0) {
                        LogUtil.info("补采任务提前结束,时间间隔小于或等于0!任务ID:" + id + ",采集时间:" + startTime + "~" + endTime);
                        changeFillMiningStatus(json, "补采任务提前结束,时间间隔小于或等于0!");
                        return;
                    }
                    message = dataCrawler(startTime, endTime, id, 1);
                    LogUtil.info("补采任务结束!任务ID:" + id + ",采集时间:" + startTime + "~" + endTime + "\n" + message);
                }
                else{
                    message = "采集时间范围:" + startTime + "~" + endTime + "无效!";
                    LogUtil.info(message);
                }
                if (!StringUtil.isEmpty(message)) {
                    changeFillMiningStatus(json, message);
                }
            }
        }
    }
    public void changeFillMiningStatus(JSONObject json, String message) {
        String id = json.getString("id");
        db.execute("update crawler_supply set status = 1 where id = '"+id+"'");
        if (!json.isNull("remote_id") && !StringUtil.isEmpty(json.getString("remote_id"))) {
            EsbHttp.changeFillMiningStatus(json.getString("remote_id"), message, "1");
        }
    }
    public synchronized String dataCrawler(Date begin, Date end, String taskId, int type) {
        if (SysConfig.getInstance().isEmptyOrgCode()) {
            return "本次任务执行失败,机构代码为空";
        }
        Integer count = 0;
        Integer totalCount = 0;
        getAdapterDataSetList();
        getDataSourceList();
        Map<String, Object> condition = new HashMap<>();
        condition.put("beginDate", begin);
        condition.put("endDate", end);
        condition.put("orgCode", SysConfig.getInstance().orgCode);
        Map<String, DBSessionFactory> dataSourceMap = new HashMap<>();
        try {
            if (!CollectionUtil.isEmpty(dataSourceList)) {
                for (DataSource dataSource : dataSourceList) {
                    String name = dataSource.getName();
                    String config = dataSource.getConfig();
                    DBSessionFactory.addDataSource(name, config);
                    DBSessionFactory dbSessionFactory = new DBSessionFactory(name);
                    dataSourceMap.put(dataSource.getId(), dbSessionFactory);
                }
                patientList = dispatch.getPatientQueue(condition, adapterDataSetList, dataSourceMap);
                if (!CollectionUtil.isEmpty(patientList)) {
                    totalCount = patientList.size();
                    for (Patient patient : patientList) {
                        String token;
                        try {
                            token = EsbHttp.getToken();
                        } catch (Exception e) {
                            LogUtil.error("本次任务执行失败,获取token失败!");
                            return "本次任务执行失败,获取token失败!";
                        }
                        if (type == 1) {
                            patient.setReUploadFlg(StringUtil.toString(true));
                        } else {
                            patient.setReUploadFlg(StringUtil.toString(false));
                        }
                        LogUtil.trace("采集->注册->打包上传,任务ID:"+taskId+",patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo());
                        // COLLECT->REGISTER->UPLOAD
                        Boolean result = dispatch.collectData(patient, adapterDataSetList, dataSourceMap, token);
                        SqlCreate sqlCreate = new SqlCreate();
                        sqlCreate.setTableName("task_track");
                        Map<String, String> keyValueMap = new HashMap<>();
                        UUID uuid = UUID.randomUUID();
                        keyValueMap.put("id", Constants.SINGLE_QUOTE_MARK + uuid.toString() + Constants.SINGLE_QUOTE_MARK);
                        keyValueMap.put("patient_id", Constants.SINGLE_QUOTE_MARK + patient.getPatientId() + Constants.SINGLE_QUOTE_MARK);
                        keyValueMap.put("event_no", Constants.SINGLE_QUOTE_MARK + patient.getEventNo() + Constants.SINGLE_QUOTE_MARK);
                        keyValueMap.put("crawler_time", Constants.SINGLE_QUOTE_MARK + DateUtil.getCurrentString(DateUtil.DEFAULT_YMDHMSDATE_FORMAT) + Constants.SINGLE_QUOTE_MARK);
                        if (result) {
                            keyValueMap.put("status", "1");
                            ++count;
                        } else {
                            keyValueMap.put("status", "0");
                        }
                        sqlCreate.setKeyValueMap(keyValueMap);
                        db.execute(sqlCreate.insertDataByKeyValue());
                    }
                }
            }
        } catch (Exception e) {
            LogUtil.error(e);
            return null;
        } finally {
            for(String key : dataSourceMap.keySet()) {
                DBSessionFactory dbSessionFactory = dataSourceMap.get(key);
                try {
                    dbSessionFactory.close();
                } catch (SQLException e) {
                    LogUtil.error(e);
                    return null;
                }
            }
        }
        String message = "本次采集病人共" + totalCount + "条,成功采集信息"+ count + "条";
        LogUtil.info(message);
        return message;
    }
    public void getAdapterDataSetList() {
        adapterDataSetList = new ArrayList<>();
        List<JSONObject> dataSetList = db.query("select id, std_dataset_id, std_dataset_code, org_dataset_code from adapter_dataset");
        for (JSONObject json : dataSetList) {
            AdapterDataSetT datasetT = new AdapterDataSetT();
            datasetT.setId(json.getInt("id"));
            datasetT.setStdDatasetCode(json.getString("std_dataset_code"));
            datasetT.setStdDatasetId(json.getInt("std_dataset_id"));
            if (!json.isNull("org_dataset_code")) {
                datasetT.setOrgDatasetCode(json.getString("org_dataset_code"));
            }
            adapterDataSetList.add(new AdapterDataSet(datasetT, db));
        }
    }
    public void getDataSourceList() {
        dataSourceList = db.query(DataSource.class, "select * from system_datasource");
    }
}

+ 254 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/DBOrigin.java

@ -0,0 +1,254 @@
package com.yihu.ehr.service.crawler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.common.constants.LogicValues;
import com.yihu.ehr.model.DataSource;
import com.yihu.ehr.model.Patient;
import com.yihu.ehr.model.PatientIdentity;
import com.yihu.ehr.model.entity.adapter.AdapterDataSet;
import com.yihu.ehr.model.entity.adapter.AdapterMetaData;
import com.yihu.ehr.model.entity.standard.StdMetaDataT;
import com.yihu.ehr.service.standard.StandardManager;
import com.yihu.ehr.util.db.BeanProcessorEx;
import com.yihu.ehr.util.db.DBSessionFactory;
import com.yihu.ehr.util.log.LogUtil;
import com.yihu.ehr.util.operator.CollectionUtil;
import com.yihu.ehr.util.operator.DateUtil;
import com.yihu.ehr.util.operator.SqlCreate;
import com.yihu.ehr.util.operator.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.sql.SQLException;
import java.util.*;
public class DBOrigin {
    public DBOrigin() {
    }
    public void finalize() throws Throwable {
    }
    public ObjectNode fecthData(Patient patient, DBSessionFactory dbSessionFactory, AdapterDataSet adapterDataSet) {
        try {
            List<AdapterMetaData> metaDataList = adapterDataSet.getAdapterMetaDataList();
            if (CollectionUtil.isEmpty(metaDataList)) {
                LogUtil.error("标准适配错误,请确认!平台数据集编码:"+ adapterDataSet.getAdapterDataSetT().getStdDatasetCode());
                return null;
            }
            SqlCreate sqlCreate = new SqlCreate();
            List<String> itemList = new ArrayList<>();
            Map<String, String> itemTagMap = new HashMap<>();
            List<String> conditionList = new ArrayList<>();
            ArrayList<String> tagList = new ArrayList<>();
            StandardManager standardManager = StandardManager.getInstance();
            String innerVersion = standardManager.getCurrentVersion();
            if (StringUtil.isEmpty(innerVersion)){
                LogUtil.error("本地标准版本信息有误,请检查 std_inner_version表数据是否正常:");
                return null;
            }
            for (AdapterMetaData metaData : metaDataList) {
                String stdCode = metaData.getAdapterMetaDataT().getStdMetadataCode();
                String orgCode = metaData.getAdapterMetaDataT().getOrgMetadataCode();
                if (stdCode != null && orgCode !=null) {
                    itemList.add(orgCode);
                    tagList.add(stdCode);
                    itemTagMap.put(orgCode, stdCode);
                }
            }
            sqlCreate.setTableName(adapterDataSet.getAdapterDataSetT().getOrgDatasetCode());
            sqlCreate.setItemList(itemList);
            ArrayList<Object> arrayList = new ArrayList<>();
            boolean patientId = true;
            if (adapterDataSet.isHavePatientID()) {
                StdMetaDataT stdMetaDataT = adapterDataSet.getStdMetaDataMap().get(PatientIdentity.getPatientIDCode());
                conditionList.add(sqlCreate.equalCondition(stdMetaDataT.getCode()));
                arrayList.add(patient.getPatientId());
            } else {
                patientId = false;
            }
            boolean eventNo = true;
            if (adapterDataSet.isHaveEventNo()) {
                StdMetaDataT stdMetaDataT = adapterDataSet.getStdMetaDataMap().get(adapterDataSet.getEventNoCode());
                conditionList.add(sqlCreate.equalCondition(stdMetaDataT.getCode()));
                arrayList.add(patient.getEventNo());
            } else {
                eventNo = false;
            }
            if (!patientId && !eventNo) {
                LogUtil.error("采集病人数据集至少需要一项病人标识.数据集名:" + adapterDataSet.getAdapterDataSetT().getStdDatasetCode());
                throw new Exception("采集病人数据集至少需要一项病人标识.数据集名:" + adapterDataSet.getAdapterDataSetT().getStdDatasetCode());
            }
            sqlCreate.setConditionList(conditionList);
            ObjectNode jsonObject = null;
            try {
                jsonObject = dbSessionFactory.queryForJson("data", sqlCreate.selectAllData(), arrayList.toArray());
                JsonNode data = jsonObject.get("data");
                if (data == null || ((ArrayNode) data).size() == 0) {
                    return null;
                }
                JSONArray jsonArray = new JSONArray();
                for(int i=0;i<data.size();i++)
                {
                    JsonNode o = data.get(i);
                    JSONObject json = new JSONObject();
                    Iterator fileNames = o.fieldNames();
                    while (fileNames.hasNext()) {
                        String fieldName = (String)fileNames.next();
                        if (!StringUtil.isEmpty(itemTagMap.get(fieldName))) {
                            json.put(itemTagMap.get(fieldName), o.get(fieldName).asText());
                        }
                    }
                    if (json.keySet().size() != itemTagMap.keySet().size()) {
                        LogUtil.info("适配数据元数量与机构提供数据元不一致,请确认!");
                        LogUtil.info("视图提供数据元:" + json.keySet().toString() + "适配数据元:" + itemList.toString());
                    }
                    jsonArray.add(json);
                }
                ObjectMapper mapper = new ObjectMapper();
                //JSON ----> JsonNode
                JsonNode jsonNode = mapper.readTree(jsonArray.toString());
                jsonObject.put("data", jsonNode);
            } catch (Exception e) {
                LogUtil.error("数据库执行异常,无对应表视图:" + sqlCreate.selectAllData());
                LogUtil.error(e);
                return null;
            }
            jsonObject.put("code", adapterDataSet.getAdapterDataSetT().getStdDatasetCode());
            jsonObject.put("patient_id", patient.getPatientId());
            jsonObject.put("event_no", patient.getEventNo());
            String agencyCode = patient.getOrgCode();
            jsonObject.put("org_code", agencyCode);
            jsonObject.put("inner_version", innerVersion);
            jsonObject.put("create_date", DateUtil.toString(new Date(), DateUtil.DEFAULT_YMDHMSDATE_FORMAT));
            jsonObject.put("event_time", patient.getReferenceTime());//DateUtil.toString(patient.getReferenceTime(), DateUtil.DEFAULT_YMDHMSDATE_FORMAT)
            if (StringUtil.isEmpty(patient.getReUploadFlg())) {
                jsonObject.put("reUploadFlg", LogicValues.LOGIC_FALSE);
            } else {
                jsonObject.put("reUploadFlg", patient.getReUploadFlg());
            }
            return jsonObject;
        } catch (Exception e) {
            LogUtil.error(e);
        }
        return null;
    }
    public List<Patient> getPatientList(DBSessionFactory dbSessionFactory, String datasourceId, AdapterDataSet adapterDataSet, Map<String, Object> condition) {
        try {
            String orgCode = StringUtil.toString(condition.get("orgCode"));
            SqlCreate sqlCreate = new SqlCreate();
            List<String> itemList = new ArrayList<>();
            List<String> conditionList = new ArrayList<>();
            PatientIdentity patientIdentity = SysConfig.getInstance().getPatientIdentity(adapterDataSet.getAdapterDataSetT().getStdDatasetCode());
            Map<String, String> propertyMap = new HashMap<>();
            Object[] param = new Object[condition.size() - 1];
            Integer count = 0;
            Date beginDate = (Date) condition.get("beginDate");
            beginDate = OriginDateTimeManager.getInstance().getRealTime(this, dbSessionFactory, datasourceId, beginDate);
            Date endDate = (Date) condition.get("endDate");
            endDate = OriginDateTimeManager.getInstance().getRealTime(this, dbSessionFactory, datasourceId, endDate);
            String patientId = (String) condition.get("patientId");
            String eventNo = (String) condition.get("eventNo");
            if (adapterDataSet.isHavePatientID()) {
                StdMetaDataT stdMetaDataT = adapterDataSet.getStdMetaData(PatientIdentity.getPatientIDCode());
                itemList.add(stdMetaDataT.getCode());
                propertyMap.put(stdMetaDataT.getCode().toUpperCase(), "patientId");
                if (!StringUtil.isEmpty(patientId)) {
                    param[count++] = patientId;
                    conditionList.add(sqlCreate.likeCondition(stdMetaDataT.getCode()));
                }
            } else {
                throw new Exception("采集病人列表数据集必须有patient_id.");
            }
            if (adapterDataSet.isHaveEventNo()) {
                StdMetaDataT stdMetaDataT = adapterDataSet.getStdMetaData(patientIdentity.getEventNoCode());
                itemList.add(stdMetaDataT.getCode());
                propertyMap.put(stdMetaDataT.getCode().toUpperCase(), "eventNo");
                if (!StringUtil.isEmpty(eventNo)) {
                    param[count++] = eventNo;
                    conditionList.add(sqlCreate.likeCondition(stdMetaDataT.getCode()));
                }
            } else {
                throw new Exception("采集病人列表数据集必须有event_no.");
            }
            StdMetaDataT stdRefMetaData = adapterDataSet.getStdMetaData(patientIdentity.getRefTimeCode());
            if (stdRefMetaData == null) {
                throw new Exception("采集病人列表数据集必须有采集时间.");
            }
            itemList.add(stdRefMetaData.getCode());
            propertyMap.put(stdRefMetaData.getCode().toUpperCase(), "referenceTime");
            itemList.add("'" + orgCode + "' orgCode");
            propertyMap.put(orgCode.toUpperCase(), "orgCode");
            sqlCreate.setItemList(itemList);
            sqlCreate.setTableName(adapterDataSet.getAdapterDataSetT().getOrgDatasetCode());
            conditionList.add(sqlCreate.greaterAndEqualCondition(stdRefMetaData.getCode()));
            conditionList.add(sqlCreate.lessCondition(stdRefMetaData.getCode()));
            sqlCreate.setConditionList(conditionList);
            sqlCreate.selectData();
            BeanProcessorEx beanProcessor = new BeanProcessorEx(propertyMap);
            List<Patient> patientList = null;
            try {
                param[count++] = beginDate;
                param[count++] = endDate;
                patientList = dbSessionFactory.queryForBeanList(Patient.class, beanProcessor, sqlCreate.selectData(), param);
            } catch (Exception e) {
                LogUtil.fatal("采集病人列表异常,等待下一次采集:"+ sqlCreate.selectData() + param);
                LogUtil.error(e);
                return null;
            }
            if (patientList == null) {
                return new ArrayList<>();
            }
            return patientList;
        } catch (Exception e) {
            LogUtil.fatal("采集病人列表异常,等待下一次采集");
            LogUtil.error(e);
            return null;
        }
    }
    public boolean clearData(Patient patient, DataSource dataSource, AdapterDataSet adapterDataSet) {
        return false;
    }
    public Date getServerDateTime(DBSessionFactory dbSessionFactory) {
        try {
            try {
                return dbSessionFactory.getSystemDateTime();
            } catch (SQLException e) {
                LogUtil.error(e);
            }
        } catch (Exception e) {
            LogUtil.error(e);
        }
        return null;
    }
}//end DBOrigin

+ 213 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/DataCollectDispatcher.java

@ -0,0 +1,213 @@
package com.yihu.ehr.service.crawler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.common.constants.Constants;
import com.yihu.ehr.model.Patient;
import com.yihu.ehr.model.PatientIdentity;
import com.yihu.ehr.model.entity.adapter.AdapterDataSet;
import com.yihu.ehr.service.patient.PatientCDAIndex;
import com.yihu.ehr.service.patient.PatientCDAUpload;
import com.yihu.ehr.util.db.DBSessionFactory;
import com.yihu.ehr.util.file.FileUtil;
import com.yihu.ehr.util.httpclient.EsbHttp;
import com.yihu.ehr.util.log.LogUtil;
import com.yihu.ehr.util.operator.CollectionUtil;
import com.yihu.ehr.util.operator.StringUtil;
import java.io.IOException;
import java.util.*;
public class DataCollectDispatcher {
    public static String registerMethod;
    private static DataCollectDispatcher ourInstance = new DataCollectDispatcher();
    private DataCollectDispatcher() {
    }
    public static DataCollectDispatcher getInstance() {
        return ourInstance;
    }
    public void finalize() throws Throwable {
    }
    /**
     * @param patient 病人
     * @return true-采集成功,false-采集失败
     */
    public Boolean collectData(Patient patient, List<AdapterDataSet> adapterDataSetList, Map<String, DBSessionFactory> dataSourceMap, String token) {
        Boolean result = true;
        Map<String, AdapterDataSet> dataSetMap = new HashMap<>();
        List<ObjectNode> dataList = new ArrayList<>();
        try {
            for (String key : dataSourceMap.keySet()) {
                DBOrigin dataCollector = new DBOrigin();
                if (dataCollector == null) {
                    LogUtil.fatal("采集数据:无法获取采集数据源.");
                    continue;
                }
                for (AdapterDataSet adapterDataSet : adapterDataSetList) {
                    //采集病人信息
                    ObjectNode jsonObject = dataCollector.fecthData(patient, dataSourceMap.get(key), adapterDataSet);
                    if (jsonObject == null) {
                        continue;
                    }
                    if (jsonObject != null && !StringUtil.isEmpty(jsonObject)) {
                        dataSetMap.put(adapterDataSet.getAdapterDataSetT().getStdDatasetCode(), adapterDataSet);
                        dataList.add(jsonObject);
                    }
                    //注册病人
                    if (SysConfig.getInstance().getRegisterDataSet().equals(adapterDataSet.getAdapterDataSetT().getStdDatasetCode())) {
                        if (!StringUtil.isEmpty(jsonObject.get("data")) && !StringUtil.isEmpty(jsonObject.get("data").get(0))) {
                            if (!StringUtil.isEmpty(jsonObject.get("data").get(0).get(SysConfig.getInstance().getRegisterIdCardNo()))) {
                                register(patient, StringUtil.toString(jsonObject), token);
                            }
                        }
                    }
                }
            }
            LogUtil.info("采集病人成功,patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo());
        } catch (Exception e) {
            LogUtil.error("采集病人失败,patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo());
            LogUtil.error(e);
            result = false;
        }
        //上传档案
        try {
            if (!CollectionUtil.isEmpty(dataList)) {
                if (!upload(dataList, patient, dataSetMap, token)) {
                    result = false;
                }
            }
        } catch (Exception e) {
            result = false;
            LogUtil.error("档案上传失败,patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo());
        }
        return result;
    }
    public Boolean upload(List<ObjectNode> dataList, Patient patient, Map<String, AdapterDataSet> dataSetMap, String token) {
        Boolean result = true;
        try {
            DataSetTransformer dataTransformer = new DataSetTransformer();
            for (ObjectNode data : dataList) {
                dataTransformer.setData(data);
                if (!toFile(dataTransformer, patient, "origin")) {
                    LogUtil.fatal("存储原始文件失败:patient_id=" + patient.getPatientId()
                            +"event_no=" + patient.getEventNo());
                    result = false;
                    break;
                }
                dataTransformer.transfer(dataSetMap);
                if (!toFile(dataTransformer, patient, "standard")) {
                    LogUtil.fatal("存储标准文件失败:patient_id=" + patient.getPatientId()
                            + "event_no=" + patient.getEventNo());
                    result = false;
                    break;
                }
            }
            PatientCDAUpload patientCDAUpload = new PatientCDAUpload();
            if (!patientCDAUpload.upload(patient, token)) {
                result = false;
            }
        } catch (Exception e) {
            result = false;
        }
        return result;
    }
    public boolean toFile(DataSetTransformer dataTransformer, Patient patient, String fileName) {
        ObjectNode jsonObject = dataTransformer.getJsonObject();
        PatientCDAIndex patientCDAIndex = new PatientCDAIndex(patient);
        String filePath = patientCDAIndex.createDataIndex(fileName, PatientCDAIndex.FileType.JSON);
        boolean writeFile = false;
        try {
            writeFile = FileUtil.writeFile(filePath, jsonObject.toString(), "UTF-8");
        } catch (IOException e) {
            LogUtil.fatal("存储临时文件失败.");
            LogUtil.error(e);
        }
        return writeFile;
    }
    /**
     * @param patient
     * @return boolean
     * 注册不是否成功 统一返回true
     */
    public Boolean register(Patient patient, String data, String token) {
        return EsbHttp.register(patient, data, token);
    }
    /**
     * @param condition 查询条件
     * @return 病人列表
     */
    public List<Patient> getPatientQueue(Map<String, Object> condition, List<AdapterDataSet> adapterDataSetList, Map<String, DBSessionFactory> dataSourceMap) {
        List<Patient> patientList = new ArrayList<>();
        DBOrigin dbOrigin = new DBOrigin();
        for(String key : dataSourceMap.keySet()) {
            DBSessionFactory dbSessionFactory = dataSourceMap.get(key);
            for (AdapterDataSet adapterDataSet : adapterDataSetList) {
                PatientIdentity patientIdentity = SysConfig.getInstance().getPatientIdentity(adapterDataSet.getAdapterDataSetT().getStdDatasetCode());
                if (patientIdentity == null) {
                    continue;
                }
                List<Patient> patients = dbOrigin.getPatientList(dbSessionFactory, key, adapterDataSet, condition);
                if (patients == null) {
                    return null;
                }
                if (patients.size() > 0) {
                    patientList.addAll(patients);
                }
            }
        }
        return patientList;
    }
    /**
     * 解析病人索引信息
     *
     * @param patientInfo 病人索引信息
     * @return
     */
    public Patient parsePatient(String patientInfo) throws IOException {
        Patient patient = null;
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        patient = new Patient();
        patient = mapper.readValue(patientInfo, Patient.class);
        return patient;
    }
    /**
     * 解析token内容
     *
     * @param responToken
     * @return
     */
    public Map<String, Object> parseToken(String responToken) {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> tokenMap = null;
        try {
            Map<String, Object> map = mapper.readValue(responToken, Map.class);
            String code = (String) map.get("code");
            if (Constants.OK.equals(code)) {
                tokenMap = (Map<String, Object>) map.get("result");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tokenMap;
    }
}//end DataCollectDispatcher

+ 172 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/DataSetTransformer.java

@ -0,0 +1,172 @@
package com.yihu.ehr.service.crawler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.ehr.common.constants.DictDataType;
import com.yihu.ehr.common.constants.TransformType;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.model.Patient;
import com.yihu.ehr.model.entity.adapter.AdapterDataSet;
import com.yihu.ehr.model.entity.adapter.AdapterDict;
import com.yihu.ehr.model.entity.adapter.AdapterMetaData;
import com.yihu.ehr.service.standard.StandardManager;
import java.util.Iterator;
import java.util.Map;
/**
 * 目前只处理json格式
 * <p>
 * json 格式
 * {
 * "inner_version":"xxxxx",
 * "patient_id":"xxxx",
 * "event_no":"xxxx",
 * "code":"dataset_code",
 * "org_code":"xxxx"
 * "data":
 * [{"metadata_code1":"5","metadata_code2":"6"},
 * [{"metadata_code1":"1","metadata_code2":"2"}]}
 * <p>
 * Created by Air on 2015/6/4.
 */
public class DataSetTransformer {
    private ObjectNode jsonObject;
    private Patient patient;
    private static DBHelper db;
    public ObjectNode getJsonObject() {
        return jsonObject;
    }
    public DataSetTransformer() {
        if (db == null) {
            db = new DBHelper();
        }
    }
    public boolean transfer(Map<String, AdapterDataSet> dataSetMap) {
        if (jsonObject != null) {
            String dataSetCode = jsonObject.get("code").asText();
            ArrayNode jsonArray = (ArrayNode) jsonObject.get("data");
            AdapterDataSet adapterDataSet = dataSetMap.get(dataSetCode);
            boolean transfer = transferJson(jsonArray, adapterDataSet);
            return transfer;
        }
        return false;
    }
    public String getData() {
        //确保文档有版本信息
        StandardManager standardManager = StandardManager.getInstance();
        jsonObject.put("inner_version", standardManager.getCurrentVersion());
        return jsonObject.asText();
    }
    public void setData(ObjectNode data) {
        jsonObject = data;
        setPatient();
    }
    public TransformType getTransformType() {
        return TransformType.DATA_SET_JSON;
    }
    /**
     * json 格式
     * {
     * "inner_version":"xxxxx",
     * "patient_id":"xxxx",
     * "event_no":"xxxx",
     * "code":"dataset_code",
     * "data":
     * [{"metadata_code1":"5","metadata_code2":"6"},
     * [{"metadata_code1":"1","metadata_code2":"2"}]}
     *
     * @param jsonArray
     * @param adapterDataSet
     * @return
     */
    public boolean transferJson(ArrayNode jsonArray, AdapterDataSet adapterDataSet) {
        for (Object objectRow : jsonArray) {
            if (objectRow instanceof JsonNode) {
                transferJsonRow((ObjectNode) objectRow, adapterDataSet);
            }
        }
        return false;
    }
    public void transferJsonRow(ObjectNode jsonObject, AdapterDataSet adapterDataSet) {
        Iterator<Map.Entry<String, JsonNode>> fields = jsonObject.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> next = fields.next();
            String key = next.getKey();
            JsonNode jsonNode = next.getValue();
            String value = jsonNode.asText();
            String stdValue = transferElem(adapterDataSet, key, value);
            if (jsonNode instanceof ObjectNode) {
                ObjectNode objectNode = (ObjectNode) next;
                objectNode.put(key, stdValue);
            }
        }
    }
    /**
     * @param adapterDataSet 数据集编码
     * @param code        数据元编码
     * @param data        数据
     * @return String 标准值
     * @modify 2015.09.16 airhead 增加值与编码转换
     */
    public String transferElem(AdapterDataSet adapterDataSet, String code, String data) {
        Map<String, AdapterMetaData> adapterMetaDataMap = adapterDataSet.getAdapterMetaDataMap();
        AdapterMetaData adapterMetaData = adapterMetaDataMap.get(code);
        AdapterDict adapterDict = adapterMetaData.getAdapterDict();
//        StdMetaDataT metaDataT = adapterMetaData.getStdMetaDataT();
//        if (adapterDict == null || !adapterDict.isValidAdapterDict()) {
//            MetaDataVerify metaDataVerify = new MetaDataVerify(metaDataT, data);
//            boolean check = metaDataVerify.check();
//            if (!check) {
//                LogUtil.fatal("保存:数据元校验错误." + metaDataVerify.getErrorInfo());
//                return null;    //未校验成功数据,清空
//            }
//
//            return data;
//        }
        if (adapterDict == null) {
            return data;
        }
        String stdData = null;
        DictDataType stdDictDataType = adapterMetaData.getStdDictDataType();
        DictDataType orgDictDataType = adapterMetaData.getOrgDictDataType();
        if (stdDictDataType == DictDataType.VALUE) {
            if (orgDictDataType == DictDataType.VALUE) {
                stdData = adapterDict.getStdDictItemValueByValue(data);
            } else if (orgDictDataType == DictDataType.CODE) {
                stdData = adapterDict.getStdDictItemValueByCode(data);
            }
        } else if (stdDictDataType == DictDataType.CODE) {
            if (orgDictDataType == DictDataType.VALUE) {
                stdData = adapterDict.getStdDictItemCodeByValue(data);
            } else if (orgDictDataType == DictDataType.CODE) {
                stdData = adapterDict.getStdDictItemCodeByCode(data);
            }
        }
        return stdData;
    }
    /**
     * 根据DataSet信息构造Patient
     */
    private void setPatient() {
        patient = new Patient();
        patient.setPatientId(jsonObject.get("patient_id").asText());
        patient.setEventNo(jsonObject.get("event_no").asText());
        patient.setOrgCode(jsonObject.get("org_code").asText());
    }
}

+ 65 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/crawler/OriginDateTimeManager.java

@ -0,0 +1,65 @@
package com.yihu.ehr.service.crawler;
import com.yihu.ehr.util.db.DBSessionFactory;
import com.yihu.ehr.util.operator.DateUtil;
import java.util.Date;
import java.util.HashMap;
public class OriginDateTimeManager {
    private static OriginDateTimeManager ourInstance = new OriginDateTimeManager();
    private static Long age = (24 * 60 * 60 * 1000L);    //过期时间,按秒,默认1天
    private HashMap<String, Long> originTimeDiff;
    private HashMap<String, Date> lastUpdate;
    private OriginDateTimeManager() {
        originTimeDiff = new HashMap<>();
        lastUpdate = new HashMap<>();
    }
    public static OriginDateTimeManager getInstance() {
        return ourInstance;
    }
    public Date getRealTime(DBOrigin dataOrigin, DBSessionFactory dbSessionFactory, String datasourceId, Date date) throws Exception {
        if (isExpire(datasourceId)) {
            updateDiff(dataOrigin, dbSessionFactory, datasourceId);
        }
        Long diff = originTimeDiff.get(datasourceId);
        if (diff == null) {
            throw new Exception("时间同步计算异常.");
        }
        long realTime = date.getTime() + diff;
        Date realdate = DateUtil.getSysDateTime();
        realdate.setTime(realTime);
        realdate = DateUtil.formatYMDToYMDHMS(realdate.toString());
        return realdate;
    }
    private boolean isExpire(String id) {
        Date now = new Date();
        Date last = lastUpdate.get(id);
        if (last == null) {
            return true;
        }
        Long diff = now.getTime() - last.getTime();
        return diff > age;
    }
    private void updateDiff(DBOrigin dataOrigin, DBSessionFactory dbSessionFactory, String datasourceId) {
        Date selfNow = DateUtil.getSysDateTime();
        Date originNow = dataOrigin.getServerDateTime(dbSessionFactory);        //暂时忽略获取时间误差,目前业务逻辑 selfNow < originNow 不会影响采集
        if (originNow == null) {
            return;
        }
        Long diff = selfNow.getTime() - originNow.getTime();
        lastUpdate.put(datasourceId, selfNow);
        originTimeDiff.put(datasourceId, diff);
    }
}

+ 34 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/intf/IDataAcquisitionManager.java

@ -0,0 +1,34 @@
package com.yihu.ehr.service.intf;
import com.yihu.ehr.framework.model.Result;
import com.yihu.ehr.model.DataAcquistion;
import org.json.JSONObject;
import java.util.Map;
/**
 * Created by chenweida on 2016/3/18.
 */
public interface IDataAcquisitionManager {
    String gate(JSONObject jo, Map<String,Object> params);
    Result getDataAcquisition(int page, int rows) throws  Exception;
    DataAcquistion getDataAcquisitionById(String dataId)throws  Exception;
    Result addDataAcquisition(String url, String request_type, String transactioncode, String url_type, String name)throws  Exception;
    Result getDataAcquisitionByCode(String transactioncode)throws  Exception;
    Object getDataAcquisitionByName(String name)throws  Exception;
    Object getDataAcquisitionByCode(String transactioncode, String id)throws  Exception;
    Object getDataAcquisitionByName(String name, String id)throws  Exception;
    Result updateDataAcquisition(String url, String request_type, String transactioncode, String url_type, String name, String id)throws  Exception;
    Result deleteAataAcquisition(String id)throws  Exception;
}

+ 25 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/intf/IDatacollectManager.java

@ -0,0 +1,25 @@
package com.yihu.ehr.service.intf;
import com.yihu.ehr.framework.model.DataGridResult;
import com.yihu.ehr.framework.model.Result;
import com.yihu.ehr.model.DataSource;
import com.yihu.ehr.model.SystemParams;
/**
 * Created by HZP on 2016/02/26.
 */
public interface IDatacollectManager {
    DataGridResult getDataset(String name) throws Exception;
    DataGridResult getMetadata(String name,String datasetId,int page,int size) throws Exception;
    DataGridResult getJobLog(String parentId,String eventNo,String status,int page,int size) throws Exception;
    DataGridResult getJobRepeat(int page,int size) throws Exception;
    Result addJobRepeat(String startTime,String endTime) throws Exception;
    Result deleteJobRepeat(String id) throws Exception;
}

+ 27 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/intf/ISystemManager.java

@ -0,0 +1,27 @@
package com.yihu.ehr.service.intf;
import com.yihu.ehr.framework.model.Result;
import com.yihu.ehr.model.DataSource;
import com.yihu.ehr.model.SystemParams;
import javax.servlet.http.HttpSession;
/**
 * Created by HZP on 2016/02/26.
 */
public interface ISystemManager {
    SystemParams getSystemParams() throws Exception;
    String getSystemParam(String name) throws Exception;
    DataSource getDataSource() throws Exception;
    Result saveParams(String interval,String updateInterval) throws Exception;
    Result saveDataSource(String id,String name,String config) throws Exception;
    Result testDataSource(String uri) throws Exception;
    Result loginAction(HttpSession session ,String user,String password) throws Exception;
}

+ 83 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/patient/PatientCDAIndex.java

@ -0,0 +1,83 @@
package com.yihu.ehr.service.patient;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.model.Patient;
import java.util.UUID;
/**
 * 病人文件索引类,用于生成文件路径,不确保文件路径存在
 *
 * @author Air
 * @version 1.0
 * @created 2015.07.01 18:06
 */
public class PatientCDAIndex {
    private Patient patient;
    public PatientCDAIndex(Patient patient) {
        this.patient = patient;
    }
    public String getDirectory() {
        String dir = SysConfig.getInstance().getTempFile();
        return dir + "/" + patient.getOrgCode() + "/" + patient.getOrgCode() + "-" + patient.getPatientId() + "-" + patient.getEventNo();
    }
    /**
     * 生成病人档案目录
     * orgCode-pateintId-eventNo/data
     *
     * @return
     */
    public String getDataDirectory() {
        return getDirectory() + "/" + IndexType.DATA;
    }
    public String createIndex(String indexType, String fileType) {
        UUID uuid = UUID.randomUUID();
        String index = uuid.toString();
        String dir = getDirectory() + "/" + indexType;
        return dir + "/" + index + fileType;
    }
    public String createDataSetIndex(String indexType, String fileType) {
        UUID uuid = UUID.randomUUID();
        String index = "dataset_index";
        String dir = getDirectory() + "/" + IndexType.DATA + "/" +indexType;
        return dir + "/" + index + fileType;
    }
    /**
     * 生成最终病人档案目录
     * data/cda
     * data/origin
     * data/standard
     *
     * @param indexType
     * @param fileType
     * @return
     */
    public String createDataIndex(String indexType, String fileType) {
        return createIndex(IndexType.DATA + "/" + indexType, fileType);
    }
    public class FileType {
        public final static String XML = ".xml";
        public final static String JSON = ".json";
        public final static String ZIP = ".zip";
    }
    public class IndexType {
        public final static String DATA = "data";   //病人档案数据目录
        public final static String CDA = "cda";     //病人cda档案目录
        public final static String STANDARD = "standard";   //病人标准档案目录
        public final static String ORIGIN = "origin";   //病人原始档案目录
        public final static String ZIP = "zip";         //病人压缩包目录
        public final static String DOCUMENT = "document";
    }
}

+ 111 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/patient/PatientCDAUpload.java

@ -0,0 +1,111 @@
package com.yihu.ehr.service.patient;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.model.Patient;
import com.yihu.ehr.util.compress.Zipper;
import com.yihu.ehr.util.encrypt.RSA;
import com.yihu.ehr.util.file.FileUtil;
import com.yihu.ehr.util.httpclient.EsbHttp;
import com.yihu.ehr.util.log.LogUtil;
import java.io.File;
import java.security.Key;
import java.util.UUID;
/**
 * 档案上传
 *
 * @author Air
 * @version 1.0
 * @created 2015.07.06 15:58
 */
public class PatientCDAUpload {
    public static String uploadMethod;
    /**
     * @param patient
     * @return
     * @modify 2015.09.15 airhead 修订删除目录
     * @modify 2015.09.19 airhead 修复无文档问题及错误信息
     */
    public Boolean upload(Patient patient, String token) {
        ZipFile zipFile = zip(patient);
        try {
            if (zipFile == null || zipFile.file == null) {
                LogUtil.fatal("压缩病人档案失败,病人文档未生成,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo());
                return false;
            }
            boolean result = upload(patient, zipFile, token);
            if (!result) {
                LogUtil.fatal("上传病人档案失败,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo());
                return result;
            }
            LogUtil.trace(zipFile.directory);
            result = FileUtil.deleteDirectory(new File(zipFile.directory));
            if (!result) {
                LogUtil.fatal("删除临时文件失败,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo());
                return result;
            }
        } catch (Exception e) {
            FileUtil.deleteDirectory(new File(zipFile.directory));
            return false;
        }
        return true;
    }
    /**
     * @param patient
     * @return
     * @modify 从data目录生成zip数据
     */
    public ZipFile zip(Patient patient) {
        try {
            PatientCDAIndex patientCDAIndex = new PatientCDAIndex(patient);
            String dataDirectory = patientCDAIndex.getDataDirectory();
            String filePath = patientCDAIndex.createIndex(PatientCDAIndex.IndexType.ZIP, PatientCDAIndex.FileType.ZIP);
            UUID uuidPwd = UUID.randomUUID();
            String pwd = uuidPwd.toString();
            String PublicKey = SysConfig.getInstance().getPublicKey();
            if(PublicKey== null ||  PublicKey.length() == 0) {
                PublicKey = EsbHttp.getPublicKey();
                SysConfig.getInstance().setPublicKey(PublicKey);
            }
            Key key = RSA.genPublicKey(PublicKey);
            if (key == null) {
                LogUtil.fatal("压缩文件错误,获取公钥错误.");
                return null;
            }
            ZipFile zipFile = new ZipFile();
            zipFile.encryptPwd = RSA.encrypt(pwd, key);
            Zipper zipper = new Zipper();
            zipFile.file = zipper.zipFile(new File(dataDirectory), filePath, pwd);
            zipFile.dataDirectory = dataDirectory;
            zipFile.directory = patientCDAIndex.getDirectory();
            return zipFile;
        } catch (Exception e) {
            LogUtil.error("从data目录生成zip数据时,压缩文件异常");
            LogUtil.error(e);
        }
        return null;
    }
    private boolean upload(Patient patient, ZipFile zipFile, String token) {
        return EsbHttp.upload(patient, zipFile.file, zipFile.encryptPwd, token);
    }
    private class ZipFile {
        public File file;
        public String encryptPwd;
        public String directory;
        public String dataDirectory;
    }
}

+ 326 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/standard/StandardManager.java

@ -0,0 +1,326 @@
package com.yihu.ehr.service.standard;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.common.constants.Constants;
import com.yihu.ehr.util.compress.Zipper;
import com.yihu.ehr.util.encrypt.RSA;
import com.yihu.ehr.util.httpclient.EsbHttp;
import com.yihu.ehr.util.httpclient.HttpClientUtil;
import com.yihu.ehr.util.httpclient.Response;
import com.yihu.ehr.util.log.LogUtil;
import com.yihu.ehr.util.operator.SqlCreate;
import com.yihu.ehr.util.operator.StringUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONObject;
import java.io.File;
import java.security.Key;
import java.util.*;
public class StandardManager {
    public static String versionMethod;
    public static String downMethod;
    private static volatile StandardManager instance;
    private SysConfig sysConfig;
    private File[] zipFiles;
    private String localVersion;
    public StandardManager(){
        sysConfig = SysConfig.getInstance();
    }
    public static StandardManager getInstance() {
        if (instance == null) {
            synchronized (StandardManager.class) {
                if (instance == null) {
                    try {
                        instance = new StandardManager();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return instance;
    }
    public Boolean isDataInit() {
        try {
            if (StringUtil.isEmpty(getCurrentVersion())) {
                return false;
            }
        } catch (Exception e) {
            LogUtil.fatal("检查标准版本是否需要更新异常:");
            LogUtil.error(e);
        }
        return true;
    }
    public Boolean checkUpdate(String remoteVersion) {
        try {
            if (StringUtil.isEmpty(remoteVersion)) {
                LogUtil.warn("总支撑平台尚无可用版本进行标准升级");
                return false;
            }
            String localVersion = getCurrentVersion();
            if (StringUtil.isEmpty(localVersion)) {
                return true;
            }
            if (localVersion.equals(remoteVersion)) {
                LogUtil.info("当前版本号与远程最新版本号一致,无需进行标准更新");
            }
            return !localVersion.equals(remoteVersion);
        } catch (Exception e) {
            LogUtil.fatal("检查标准版本是否需要更新异常:");
            LogUtil.error(e);
        }
        return false;
    }
    public boolean update() {
        if (sysConfig.isEmptyOrgCode()) {
            LogUtil.fatal("当前机构代码为空,版本无法更新,请确认!");
            return false;
        }
        String remoteVersion = getRemoteVersion(sysConfig.getOrgCode());
        if (checkUpdate(remoteVersion)) {
            String encryptPwd = download(remoteVersion, sysConfig.getOrgCode());
            if (StringUtil.isEmpty(encryptPwd)) {
                LogUtil.fatal("下载标准包错误.");
                return false;
            }
            versionUpdate(encryptPwd);
            localVersion = remoteVersion;
        }
        return true;
    }
    /**
     * 获取当前自版本号
     *
     * @return String
     */
    public synchronized String getCurrentVersion() {
        if (StringUtil.isEmpty(localVersion)){
            localVersion = new StandardService().getCurrentVersion();
        }
        return localVersion;
    }
    private String getRemoteVersion(String orgCode) {
        return EsbHttp.getRemoteVersion(orgCode);
    }
    /**
     * 版本升级
     *
     * @return boolean
     */
    private boolean versionUpdate(String encryptPwd) {
        boolean result;
        result = unpack(encryptPwd);
        if (!result) {
            LogUtil.fatal("标准包解压错误.");
            return false;
        }
        result = validateFile();
        if (!result) {
            LogUtil.fatal("下载版本文件缺失,不能执行适配方案");
            return false;
        }
        result = new StandardService().genData(zipFiles);
        if (!result) {
            LogUtil.fatal("生成标准数据失败.");
            return false;
        }
        return true;
    }
    private String download(String remoteVersion, String orgCode) {
        Response response = EsbHttp.download(remoteVersion, orgCode);
        try {
            if (response != null && response.getStatusCode() == 200) {
                JSONObject re = new JSONObject(response.getBody());
                if (re.has("password")&&re.has("url")) {
                    String encryptPwd = re.getString("password");
                    String zipContent = re.getString("url");
                    String downloadFilePath = SysConfig.getInstance().getTempFile() + "/" + Constants.STANDARD_ZIP;
                    //boolean writeFile = FileUtil.writeFile(downloadFilePath, zipContent, "UTF-8");
                    HttpClientUtil.downLoadFile(downloadFilePath,zipContent,"","");
                    return encryptPwd;
                }
                else{
                    LogUtil.fatal("获取标准包失败");
                    return null;
                }
            }
            else{
                LogUtil.fatal("下载标准包失败,网络错误或者服务器不可用.");
                return null;
            }
        } catch (Exception e) {
            LogUtil.fatal("下载标准包异常:");
            LogUtil.error(e);
        }
        return null;
    }
    private boolean unpack(String encryptPwd) {
        try {
            String publicKey = sysConfig.getPublicKey();
            if(publicKey==null ||publicKey.length()==0)
            {
                publicKey = EsbHttp.getPublicKey();
                sysConfig.setPublicKey(publicKey);
            }
            Key key = RSA.genPublicKey(publicKey);
            if (key == null) {
                LogUtil.fatal("解压文件错误,获取公钥错误.");
                return false;
            }
            String pwd = Constants.EMPTY;
            if (!StringUtil.isEmpty(encryptPwd)) {
                pwd = RSA.decrypt(encryptPwd, key);
            }
            zipFiles = Zipper.unzip(sysConfig.getTempFile() + "/" + Constants.STANDARD_ZIP, pwd);
            return true;
        } catch (Exception e) {
            LogUtil.fatal("解压文件异常:");
            LogUtil.error(e);
        }
        return false;
    }
    private boolean validateFile() {
        Integer count = 0;
        for (File file : zipFiles) {
            if (!file.getParentFile().getName().equals(Constants.CDA_FILE)) {
                count++;
            }
        }
        if (count != 15) {
            LogUtil.fatal("下载标准文件缺失,无法正常更新标准");
            return false;
        }
        return true;
    }
    private void createData(File file, List<String> sqlList) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(file);
            Element root = doc.getRootElement();
            String tableName = root.attributeValue("name");
            if (tableName == null) {
                throw new Exception("错误的标准格式,无表名信息.");
            }
            Element metadata = root.element("metadata");
            if (metadata == null) {
                throw new Exception("错误的标准格式,无表字段信息.");
            }
            HashMap<String, String> colMap = getColMetaData(metadata);
            for (Iterator rowIterator = root.elementIterator("row"); rowIterator.hasNext();) {
                SqlCreate sqlCreate = new SqlCreate();
                sqlCreate.setTableName(tableName);
                Element rowElement = (Element) rowIterator.next();
                createDataSql(rowElement, colMap, sqlList, sqlCreate);
            }
        } catch (Exception e) {
            LogUtil.fatal("生成标准表异常:");
            LogUtil.error(e);
        }
    }
    private HashMap<String, String> getColMetaData(Element rowElem) {
        HashMap<String, String> hashMap = new HashMap<>();
        for (Iterator colIterator = rowElem.elementIterator(); colIterator.hasNext(); ) {
            Element colElement = (Element) colIterator.next();
            String name = colElement.attributeValue("name");
            String type = colElement.attributeValue("type");
            hashMap.put(name, type);
        }
        return hashMap;
    }
    private void createDataSql(Element rowElement, HashMap<String, String> colMap, List<String> sqlList, SqlCreate sqlCreate) {
        if (rowElement == null) {
            return;
        }
        Map<String, String> keyValueMap = new HashMap<>();
        List<String> itemList = new ArrayList<>();
        List<String> itemValueList = new ArrayList<>();
        for (Iterator colIterator = rowElement.elementIterator(); colIterator.hasNext(); ) {
            Element colElement = (Element) colIterator.next();
            if (colElement.getText().equals("")) {
                continue;
            }
            String key = colElement.getName();
            itemList.add(key);
            String type = colMap.get(key);
            if (type == null) {
                LogUtil.fatal("createDataSql无效的类型.");
            }
            String value;
            switch (type) {
                case "N":
                    value = colElement.getText();
                    break;
                case "S":
                    value = "'" + colElement.getText().replace("'","''") + "'";
                    break;
                case "D":
                    value = "'" + colElement.getText() + "'";
                    break;
                default:
                    value = colElement.getText();
            }
            itemValueList.add(value);
            keyValueMap.put(key, value);
            if (key.equals(Constants.TABLE_KEY)) {
                sqlCreate.setTableKey(value);
            }
        }
        sqlCreate.setItemList(itemList);
        sqlCreate.setItemValueList(itemValueList);
        sqlCreate.setKeyValueMap(keyValueMap);
        if (Constants.ADD_TYPE.equals(rowElement.attributeValue("type"))) {
            sqlList.add(sqlCreate.insertData());
        } else if (Constants.UPDATE_TYPE.equals(rowElement.attributeValue("type"))) {
            sqlList.add(sqlCreate.updateDataByTableKey());
            if (sqlCreate.isToAdapter() && sqlCreate.isCodeOrValue()) {
                sqlList.add(sqlCreate.updateAdapterData());
            }
        } else if (Constants.DELETE_TYPE.equals(rowElement.attributeValue("type"))) {
            sqlList.add(sqlCreate.deleteDataByTableKey());
            if (sqlCreate.isToAdapter()) {
                sqlList.add(sqlCreate.deleteAdapterData());
            }
            if (sqlCreate.isToAdapterDataset()) {
                sqlList.add(sqlCreate.deleteAdapterOriginData());
            }
        }
    }
}

+ 189 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/standard/StandardService.java

@ -0,0 +1,189 @@
package com.yihu.ehr.service.standard;
import com.yihu.ehr.common.constants.Constants;
import com.yihu.ehr.dbhelper.jdbc.DBConfig;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.util.log.LogUtil;
import com.yihu.ehr.util.operator.CollectionUtil;
import com.yihu.ehr.util.operator.SqlCreate;
import com.yihu.ehr.util.operator.StringUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONObject;
import java.io.File;
import java.sql.Connection;
import java.util.*;
/**
 * 线程取数据,不走连接池
 */
public class StandardService {
    private DBHelper db = new DBHelper();
    /**
     * 获取当前自版本号
     */
    public synchronized String getCurrentVersion() {
        try {
            String localVersion = "";
            List<JSONObject> list = db.query("select code from std_inner_version order by code desc");
            if (!CollectionUtil.isEmpty(list)) {
                localVersion = list.get(0).getString("code");
            }
            return localVersion;
        }
        catch (Exception e)
        {
            LogUtil.error(e);
            return "";
        }
    }
    /**
     * 读取标准数据
     */
    public synchronized boolean genData(File[] zipFiles) {
        List<String> sqlList = new ArrayList<>();
        List<String> fileNameList = new ArrayList<>();
        List<String> deleteDataList = new ArrayList<>();
        for (File file : zipFiles) {
            if (!file.getName().contains("_cda")) {
                if (file.getName().contains("org_")||file.getName().contains("adapter_")
                        ||file.getName().contains("std_")) {
                    fileNameList.add(StringUtil.substring(file.getName(), 0, file.getName().indexOf(Constants.DOT)));
                }
                if (!file.getParentFile().getName().equals(Constants.CDA_FILE)) {
                    createData(file, sqlList);
                }
            }
        }
        SqlCreate sqlCreate = new SqlCreate();
        for (String fileName : fileNameList) {
            sqlCreate.setTableName(fileName);
            deleteDataList.add(sqlCreate.deleteData());
        }
        String[] deleteArray = new String[deleteDataList.size()];
        deleteDataList.toArray(deleteArray);
        String[] sqlArray = new String[sqlList.size()];
        sqlList.toArray(sqlArray);
        try {
            db.executeBatch(deleteArray);
            db = new DBHelper();
            db.executeBatch(sqlArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    private void createData(File file, List<String> sqlList) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(file);
            Element root = doc.getRootElement();
            String tableName = root.attributeValue("name");
            if (tableName == null) {
                throw new Exception("错误的标准格式,无表名信息.");
            }
            Element metadata = root.element("metadata");
            if (metadata == null) {
                throw new Exception("错误的标准格式,无表字段信息.");
            }
            HashMap<String, String> colMap = getColMetaData(metadata);
            for (Iterator rowIterator = root.elementIterator("row"); rowIterator.hasNext();) {
                SqlCreate sqlCreate = new SqlCreate();
                sqlCreate.setTableName(tableName);
                Element rowElement = (Element) rowIterator.next();
                createDataSql(rowElement, colMap, sqlList, sqlCreate);
            }
        } catch (Exception e) {
            LogUtil.fatal("生成标准表异常:");
            LogUtil.error(e);
        }
    }
    private HashMap<String, String> getColMetaData(Element rowElem) {
        HashMap<String, String> hashMap = new HashMap<>();
        for (Iterator colIterator = rowElem.elementIterator(); colIterator.hasNext(); ) {
            Element colElement = (Element) colIterator.next();
            String name = colElement.attributeValue("name");
            String type = colElement.attributeValue("type");
            hashMap.put(name, type);
        }
        return hashMap;
    }
    private void createDataSql(Element rowElement, HashMap<String, String> colMap, List<String> sqlList, SqlCreate sqlCreate) {
        if (rowElement == null) {
            return;
        }
        Map<String, String> keyValueMap = new HashMap<>();
        List<String> itemList = new ArrayList<>();
        List<String> itemValueList = new ArrayList<>();
        for (Iterator colIterator = rowElement.elementIterator(); colIterator.hasNext(); ) {
            Element colElement = (Element) colIterator.next();
            if (colElement.getText().equals("")) {
                continue;
            }
            String key = colElement.getName();
            itemList.add(key);
            String type = colMap.get(key);
            if (type == null) {
                LogUtil.fatal("createDataSql无效的类型.");
            }
            String value;
            switch (type) {
                case "N":
                    value = colElement.getText();
                    break;
                case "S":
                    value = "'" + colElement.getText().replace("'","''") + "'";
                    break;
                case "D":
                    value = "'" + colElement.getText() + "'";
                    break;
                default:
                    value = colElement.getText();
            }
            itemValueList.add(value);
            keyValueMap.put(key, value);
            if (key.equals(Constants.TABLE_KEY)) {
                sqlCreate.setTableKey(value);
            }
        }
        sqlCreate.setItemList(itemList);
        sqlCreate.setItemValueList(itemValueList);
        sqlCreate.setKeyValueMap(keyValueMap);
        if (Constants.ADD_TYPE.equals(rowElement.attributeValue("type"))) {
            sqlList.add(sqlCreate.insertData());
        } else if (Constants.UPDATE_TYPE.equals(rowElement.attributeValue("type"))) {
            sqlList.add(sqlCreate.updateDataByTableKey());
            if (sqlCreate.isToAdapter() && sqlCreate.isCodeOrValue()) {
                sqlList.add(sqlCreate.updateAdapterData());
            }
        } else if (Constants.DELETE_TYPE.equals(rowElement.attributeValue("type"))) {
            sqlList.add(sqlCreate.deleteDataByTableKey());
            if (sqlCreate.isToAdapter()) {
                sqlList.add(sqlCreate.deleteAdapterData());
            }
            if (sqlCreate.isToAdapterDataset()) {
                sqlList.add(sqlCreate.deleteAdapterOriginData());
            }
        }
    }
}

+ 40 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/thread/CrawlerSupplyThread.java

@ -0,0 +1,40 @@
package com.yihu.ehr.service.thread;
import com.yihu.ehr.common.config.ThreadConfig;
import com.yihu.ehr.service.crawler.CrawlerManager;
import com.yihu.ehr.service.standard.StandardManager;
import com.yihu.ehr.util.log.LogUtil;
public class CrawlerSupplyThread implements Runnable {
    @Override
    public void run() {
        while (ThreadManage.crawlerSupplyIsRunning) {
            try {
                LogUtil.info("补采线程开始");
                CrawlerManager.getInstance().dataCrawlerSupply();
                LogUtil.info("补采线程结束");
                sleep();
            } catch (InterruptedException e) {
                LogUtil.error("休眠中断!");
                LogUtil.error(e);
                continue;
            } catch (Exception e) {
                LogUtil.error("补采线程失败,将重启启动线程!");
                LogUtil.error(e);
                try {
                    sleep();
                } catch (Exception e1) {
                    continue;
                }
                continue;
            }
        }
    }
    private void sleep() throws Exception {
        LogUtil.info("开始睡眠,睡眠时间:" + 1000 * ThreadConfig.CRAWLER_SUPPLY_THREAD_SLEEP_TIME);
        Thread.sleep(1000 * ThreadConfig.CRAWLER_SUPPLY_THREAD_SLEEP_TIME);
    }
}

+ 50 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/thread/CrawlerThread.java

@ -0,0 +1,50 @@
package com.yihu.ehr.service.thread;
import com.yihu.ehr.common.config.ThreadConfig;
import com.yihu.ehr.dbhelper.jdbc.DBConfig;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.service.crawler.CrawlerManager;
import com.yihu.ehr.service.standard.StandardManager;
import com.yihu.ehr.util.log.LogUtil;
public class CrawlerThread implements Runnable {
    DBHelper db = new DBHelper(Thread.currentThread().getName(), DBConfig.get("defaultUri"));
    @Override
    public void run() {
        while (ThreadManage.crawlerIsRunning) {
            try {
                LogUtil.info("采集线程开始");
                CrawlerManager.getInstance().dataCrawlerFrequency();
                LogUtil.info("采集线程结束");
                sleep();
            } catch (InterruptedException e) {
                LogUtil.error("休眠中断!");
                LogUtil.error(e);
                continue;
            } catch (Exception e) {
                LogUtil.error("采集线程失败,将重新启动线程!");
                LogUtil.error(e);
                try {
                    sleep();
                } catch (Exception e1) {
                    continue;
                }
                continue;
            }
        }
    }
    private void sleep() throws Exception {
        if (ThreadConfig.CRAWLER_THREAD_SLEEP_TIME == 0) {
            Object obj = db.scalar("select param_value from system_param where param_key='INTERVAL'");
            if(obj!=null) {
                ThreadConfig.CRAWLER_THREAD_SLEEP_TIME = Integer.parseInt(obj.toString());
            }
        }
        LogUtil.info("开始睡眠,睡眠时间:" + 1000 * ThreadConfig.CRAWLER_THREAD_SLEEP_TIME);
        Thread.sleep(1000 * ThreadConfig.CRAWLER_THREAD_SLEEP_TIME);
    }
}

+ 53 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/thread/StandardUpdateThread.java

@ -0,0 +1,53 @@
package com.yihu.ehr.service.thread;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.common.config.ThreadConfig;
import com.yihu.ehr.dbhelper.jdbc.DBConfig;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.service.standard.StandardManager;
import com.yihu.ehr.util.log.LogUtil;
public class StandardUpdateThread implements Runnable {
    @Override
    public void run() {
        while (ThreadManage.standardUpdateIsRunning) {
            try {
                LogUtil.info("标准更新线程开始");
                if (SysConfig.getInstance().isEmptyOrgCode()) {
                    LogUtil.info("机构代码为空,无法更新标准!");
                } else {
                    StandardManager.getInstance().update();
                }
                LogUtil.info("标准更新线程结束");
                sleep();
            } catch (InterruptedException e) {
                LogUtil.error("采集中断!");
                LogUtil.error(e);
                continue;
            } catch (Exception e) {
                LogUtil.error("更新线程失败,将重新启动线程!");
                LogUtil.error(e);
                try {
                    sleep();
                } catch (Exception e1) {
                    continue;
                }
                continue;
            }
        }
    }
    private void sleep() throws Exception {
        if (ThreadConfig.UPDATE_THREAD_SLEEP_TIME == 0) {
            DBHelper db = new DBHelper();
            Object obj = db.scalar("select param_value from system_param where param_key='UPDATE_INTERVAL'");
            if(obj!=null) {
                ThreadConfig.UPDATE_THREAD_SLEEP_TIME = Integer.parseInt(obj.toString());
            }
        }
        LogUtil.info("开始睡眠,睡眠时间:" + 1000 * ThreadConfig.UPDATE_THREAD_SLEEP_TIME);
        Thread.sleep(1000 * ThreadConfig.UPDATE_THREAD_SLEEP_TIME);
    }
}

+ 65 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/service/thread/ThreadManage.java

@ -0,0 +1,65 @@
package com.yihu.ehr.service.thread;
import com.yihu.ehr.common.config.ThreadConfig;
import com.yihu.ehr.dbhelper.jdbc.DBHelper;
import com.yihu.ehr.util.log.LogUtil;
import com.yihu.ehr.util.operator.StringUtil;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by chenweida on 2016/3/2.
 */
public class ThreadManage {
    public static String CRAWLER_THREAD = "crawlerThread";
    public static String CRAWLER_SUPPLY_THREAD = "crawlerSupplyThread";
    public static String STANDARD_UPDATE_THREAD = "standardUpdateThread";
    public static boolean crawlerIsRunning = true;
    public static boolean crawlerSupplyIsRunning = true;
    public static boolean standardUpdateIsRunning = true;
    private static Map<String, Thread> threadPool = new HashMap<String, Thread>();
    static DBHelper db = new DBHelper();
    public static void add(String threadId, Thread thread) {
        threadPool.put(threadId, thread);
    }
    public static void setCrawlerInterval() {
        JSONObject json = db.load("select param_value from system_param where param_key = 'INTERVAL'");
        if (json == null || json.isNull("param_value")) {
            LogUtil.error("参数INTERVAL未配置,请确认!");
            return;
        }
        String interval = json.getString("param_value");
        if (!StringUtil.isEmpty(interval) && Integer.parseInt(interval) != 0) {
            ThreadConfig.CRAWLER_THREAD_SLEEP_TIME = Integer.parseInt(interval);
        }
    }
    public static void setUpdateInterval() {
        JSONObject json = db.load("select param_value from system_param where param_key = 'UPDATE_INTERVAL'");
        if (json == null || json.isNull("param_value")) {
            LogUtil.error("参数UPDATE_INTERVAL未配置,请确认!");
            return;
        }
        String interval = json.getString("param_value");
        if (!StringUtil.isEmpty(interval) && Integer.parseInt(interval) != 0) {
            ThreadConfig.UPDATE_THREAD_SLEEP_TIME = Integer.parseInt(interval);
        }
    }
    public static Thread get(String threadId) {
        return threadPool.get(threadId);
    }
    //把所有的线程的有效标示设置成false
    public static void stopAllThread() {
        crawlerIsRunning = false;
        crawlerSupplyIsRunning = false;
        standardUpdateIsRunning = false;
    }
}

+ 140 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/compress/ZipUtil.java

@ -0,0 +1,140 @@
package com.yihu.ehr.util.compress;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
/**
 * Created by chenweida on 2016/2/27. 用的是ant解压缩
 */
public class ZipUtil {
    private static final int buffer = 1024;
    private static void createDirectory(String directory, String subDirectory) {
        String dir[];
        File fl = new File(directory);
        try {
            if (subDirectory == "" && fl.exists() != true) {
                fl.mkdir();
            } else if (subDirectory != "") {
                dir = subDirectory.replace('\\', '/').split("/");
                for (int i = 0; i < dir.length; i++) {
                    File subFile = new File(directory + File.separator + dir[i]);
                    if (subFile.exists() == false) {
                        subFile.mkdir();
                    }
                    directory += File.separator + dir[i];
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /**
     * @param zipFilePath     解压的文件
     * @param outputDirectory 解压的文件路径
     * @return
     */
    @SuppressWarnings("unchecked")
    public static boolean unZip(String zipFilePath, String outputDirectory) {
        boolean flag = false;
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            Enumeration e = zipFile.getEntries();
            ZipEntry zipEntry = null;
            createDirectory(outputDirectory, "");
            while (e.hasMoreElements()) {
                zipEntry = (ZipEntry) e.nextElement();
                if (zipEntry.isDirectory()) {
                    String name = zipEntry.getName().trim();
                    name = name.substring(0, name.length() - 1);
                    File f = new File(outputDirectory + File.separator + name);
                    if (!f.exists()) {
                        f.mkdir();
                    }
                } else {
                    String fileName = zipEntry.getName();
                    fileName = fileName.replace('\\', '/');
                    if (fileName.indexOf("/") != -1) {
                        createDirectory(outputDirectory, fileName.substring(0,
                                fileName.lastIndexOf("/")));
                        fileName = fileName
                                .substring(fileName.lastIndexOf("/") + 1);
                    }
                    File f = new File(outputDirectory + File.separator
                            + zipEntry.getName());
                    f.createNewFile();
                    InputStream in = zipFile.getInputStream(zipEntry);
                    FileOutputStream out = new FileOutputStream(f);
                    byte[] by = new byte[buffer];
                    int c;
                    while ((c = in.read(by)) != -1) {
                        out.write(by, 0, c);
                    }
                    in.close();
                    out.close();
                }
            }
            flag = true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return flag;
    }
    /**
     * 压缩
     *
     * @param srcDirName  要压缩的路径
     * @param zipFilePath 压缩的文件名字
     * @return
     */
    public static boolean zip(String srcDirName, String zipFilePath) {
        boolean flag = false;
        try {
            File srcdir = new File(srcDirName);
            if (!srcdir.exists())
                throw new RuntimeException(srcDirName + " is not exist!");
            Project prj = new Project();
            Zip zip_ = new Zip();
            zip_.setProject(prj);
            zip_.setDestFile(new File(zipFilePath));
            FileSet fileSet = new FileSet();
            fileSet.setProject(prj);
            fileSet.setDir(srcdir);
            zip_.addFileset(fileSet);
            zip_.execute();
            flag = true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return flag;
    }
    public static void main(String[] args) {
        try {
            // ZipUtil.zip("C:\\Users\\chenweida\\Desktop\\loadClassSimpleDemo-1.0-SNAPSHOT",
            //       "F:/sss.zip");
            ZipUtil.unZip("F:/sss.zip",
                    "F:/");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

+ 173 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/compress/Zipper.java

@ -0,0 +1,173 @@
package com.yihu.ehr.util.compress;
import com.yihu.ehr.util.operator.StringUtil;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
 * 文件压缩辅助类
 *
 * @created Air 2015/5/26.
 */
public class Zipper {
    /**
     * 使用给定密码解压指定的ZIP压缩文件到指定目录
     * <p>
     * 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出
     *
     * @param zip    指定的ZIP压缩文件
     * @param dest   解压目录
     * @param passwd ZIP文件的密码
     * @return 解压后文件数组
     * @throws ZipException 压缩文件有损坏或者解压缩失败抛出
     */
    public static File[] unzip(String zip, String dest, String passwd) throws ZipException {
        File zipFile = new File(zip);
        return unzip(zipFile, dest, passwd);
    }
    /**
     * 使用给定密码解压指定的ZIP压缩文件到当前目录
     *
     * @param zip    指定的ZIP压缩文件
     * @param passwd ZIP文件的密码
     * @return 解压后文件数组
     * @throws ZipException 压缩文件有损坏或者解压缩失败抛出
     */
    public static File[] unzip(String zip, String passwd) throws ZipException {
        File zipFile = new File(zip);
        File parentDir = zipFile.getParentFile();
        return unzip(zipFile, parentDir.getAbsolutePath(), passwd);
    }
    /**
     * 使用给定密码解压指定的ZIP压缩文件到指定目录
     * <p>
     * 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出
     *
     * @param dest   解压目录
     * @param passwd ZIP文件的密码
     * @return 解压后文件数组
     * @throws ZipException 压缩文件有损坏或者解压缩失败抛出
     */
    public static File[] unzip(File zipFile, String dest, String passwd) throws ZipException {
        ZipFile zFile = new ZipFile(zipFile);
        zFile.setFileNameCharset("GBK");
        if (!zFile.isValidZipFile()) {
            throw new ZipException("压缩文件不合法,可能被损坏.");
        }
        File destDir = new File(dest);
        if (destDir.isDirectory() && !destDir.exists()) {
            destDir.mkdir();
        }
        if (zFile.isEncrypted()) {
            zFile.setPassword(passwd.toCharArray());
        }
        zFile.extractAll(dest);
        List<FileHeader> headerList = zFile.getFileHeaders();
        List<File> extractedFileList = new ArrayList<>();
        for (FileHeader fileHeader : headerList) {
            if (!fileHeader.isDirectory()) {
                extractedFileList.add(new File(destDir, fileHeader.getFileName()));
            }
        }
        File[] extractedFiles = new File[extractedFileList.size()];
        extractedFileList.toArray(extractedFiles);
        return extractedFiles;
    }
    /**
     * @param unzipFile   需要压缩的文件(文件夹)
     * @param zipFileName 压缩后的文件名
     * @return 成功-File 失败-null
     * @throws ZipException
     */
    public File zipFile(File unzipFile, String zipFileName) throws ZipException {
        return zipFile(unzipFile, zipFileName, null);
    }
    /**
     * @param unzipFile   需要压缩的文件(文件夹)
     * @param zipFileName 压缩后的文件名
     * @param pwd         压缩密码
     * @return 成功-File 失败-null
     * @throws ZipException 2015.09.15 airhead modify 压缩文件为文件夹时,压缩从子目录开始,忽略当前目录
     */
    public File zipFile(File unzipFile, String zipFileName, String pwd) throws ZipException {
        //文件不存在时不压缩
        if (!unzipFile.exists()) {
            return null;
        }
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        if (!StringUtil.isEmpty(pwd)) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
            parameters.setPassword(pwd.toCharArray());
        }
        File file = new File(zipFileName);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        ZipFile zipFile = new ZipFile(zipFileName);
        if (unzipFile.isDirectory()) {
//            zipFile.addFolder(unzipFile, parameters);
            File[] files = unzipFile.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    zipFile.addFolder(files[i], parameters);
                } else {
                    zipFile.addFile(files[i], parameters);
                }
            }
        } else {
            zipFile.addFile(unzipFile, parameters);
        }
        return new File(zipFileName);
    }
    /**
     * @param zipFile        需要解压的文件名
     * @param unzipDirectory 解压文件路径
     * @return 成功-File 失败-null
     * @throws ZipException
     */
    public static File unzipFile(File zipFile, String unzipDirectory) throws ZipException {
        return unzipFile(zipFile, unzipDirectory, null);
    }
    /**
     * @param zipFile        需要解压的文件名
     * @param unzipDirectory 解压文件路径
     * @param pwd            解压密码
     * @return 成功-File 失败-null
     * @throws ZipException
     */
    public static File unzipFile(File zipFile, String unzipDirectory, String pwd) throws ZipException {
        ZipFile zFile = new ZipFile(zipFile);
        zFile.setFileNameCharset("GBK");
        if (!zFile.isValidZipFile()) {
            throw new ZipException("无效的压缩文件.");
        }
        if (zFile.isEncrypted()) {
            zFile.setPassword(pwd.toCharArray());
        }
        zFile.extractAll(unzipDirectory);
        return new File(unzipDirectory);
    }
}

+ 138 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/BeanProcessorEx.java

@ -0,0 +1,138 @@
package com.yihu.ehr.util.db;
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * <p>
 * <code>BeanProcessor</code> matches column names to bean property names
 * and converts <code>ResultSet</code> columns into objects for those bean
 * properties.  Subclasses should override the methods in the processing chain
 * to customize behavior.
 * </p>
 * <p>
 * <p>
 * This class is thread-safe.
 * </p>
 *
 * @see BasicRowProcessor
 * @since DbUtils 1.1
 */
public class BeanProcessorEx extends BeanProcessor {
    /**
     * Constructor for BeanProcessor.
     */
    public BeanProcessorEx() {
        this(new HashMap<String, String>());
    }
    /**
     * Constructor for BeanProcessor configured with column to property name overrides.
     *
     * @param columnToPropertyOverrides ResultSet column to bean property name overrides
     * @since 1.5
     */
    public BeanProcessorEx(Map<String, String> columnToPropertyOverrides) {
        super(columnToPropertyOverrides);
    }
    /**
     * Convert a <code>ResultSet</code> column into an object.  Simple
     * implementations could just call <code>rs.getObject(index)</code> while
     * more complex implementations could perform type manipulation to match
     * the column's type to the bean property type.
     * <p>
     * <p>
     * This implementation calls the appropriate <code>ResultSet</code> getter
     * method for the given property type to perform the type conversion.  If
     * the property type doesn't match one of the supported
     * <code>ResultSet</code> types, <code>getObject</code> is called.
     * </p>
     *
     * @param rs       The <code>ResultSet</code> currently being processed.  It is
     *                 positioned on a valid row before being passed into this method.
     * @param index    The current column index being processed.
     * @param propType The bean property type that this column needs to be
     *                 converted into.
     * @return The object from the <code>ResultSet</code> at the given column
     * index after optional type processing or <code>null</code> if the column
     * value was SQL NULL.
     * @throws SQLException if a database access error occurs
     */
    protected Object processColumn(ResultSet rs, int index, Class<?> propType)
            throws SQLException {
        if (!propType.isPrimitive() && rs.getObject(index) == null) {
            return null;
        }
        if (propType.equals(String.class)) {
            return rs.getString(index);
        } else if (
                propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
            return Integer.valueOf(rs.getInt(index));
        } else if (
                propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
            return Boolean.valueOf(rs.getBoolean(index));
        } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
            return Long.valueOf(rs.getLong(index));
        } else if (
                propType.equals(Double.TYPE) || propType.equals(Double.class)) {
            return Double.valueOf(rs.getDouble(index));
        } else if (
                propType.equals(Float.TYPE) || propType.equals(Float.class)) {
            return Float.valueOf(rs.getFloat(index));
        } else if (
                propType.equals(Short.TYPE) || propType.equals(Short.class)) {
            return Short.valueOf(rs.getShort(index));
        } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
            return Byte.valueOf(rs.getByte(index));
        } else if (propType.equals(Timestamp.class)) {
            return rs.getTimestamp(index);
        } else if (propType.equals(SQLXML.class)) {
            return rs.getSQLXML(index);
        } else if (propType.equals(Date.class)) {
            return new Timestamp(rs.getTimestamp(index).getTime());
        } else {
            return rs.getObject(index);
        }
    }
}

+ 387 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/DBSessionFactory.java

@ -0,0 +1,387 @@
package com.yihu.ehr.util.db;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.*;
import org.dom4j.Document;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
/**
 * ���ݿ�������,�򻯲���
 *
 * @created Air on 2015/6/2
 */
public class DBSessionFactory {
    public static final String HOS = "hos-mysql";
    private final static HashMap<String, DataSourcePool> dataSourcePool = new HashMap<>();
    private DataSource dataSource;
    private QueryRunner queryRunner;
    private Connection connection;
    private String driver;
    public DBSessionFactory() {
        DataSourcePool dataSourcePool = DBSessionFactory.dataSourcePool.get(HOS);
        if (dataSourcePool != null) {
            dataSource = dataSourcePool.getDataSource();
            driver = dataSourcePool.getDriver();
        }
        queryRunner = new QueryRunner();
    }
    /**
     * @param dsName ���ݿ����ñ���,���ڱ�ʶ��������ݿ�����
     */
    public DBSessionFactory(String dsName) throws SQLException {
        DataSourcePool dataSourcePool = DBSessionFactory.dataSourcePool.get(dsName);
        if (dataSourcePool != null) {
            dataSource = dataSourcePool.getDataSource();
            connection = dataSource.getConnection();
            driver = dataSourcePool.getDriver();
        }
        queryRunner = new QueryRunner();
    }
    /**
     * ������ݿ�����
     *
     * @param dsName ���ݿ����ñ���,���ڱ�ʶ��������ݿ�����
     * @param uri    ���ݿ����Ӵ�
     */
    public static synchronized void addDataSource(String dsName, String uri) {
        DataSourcePool dataSourcePool = DBSessionFactory.dataSourcePool.get(dsName);
        if (dataSourcePool == null) {
            DBSessionFactory.dataSourcePool.put(dsName, new DataSourcePool(uri));
        }
    }
    /**
     * �ر�Connection
     *
     * @throws SQLException
     */
    public void close() throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }
    /**
     * ʹ��Json��ʽ
     *
     * @param jsonRoot
     * @param arrayList
     * @param sql       SQL�﷨
     * @param params    �����б�
     * @return JSONObject
     * @throws SQLException
     */
    public ObjectNode queryForJson(String jsonRoot, ArrayList<String> arrayList, String sql, Object... params) throws SQLException {
        JsonHandler jsonHandler = new JsonHandler(jsonRoot);
        jsonHandler.setTagList(arrayList);
        return this.query(sql, jsonHandler, params);
    }
    public ObjectNode queryForJson(String jsonRoot, String sql, Object... params) throws SQLException {
        JsonHandler jsonHandler = new JsonHandler(jsonRoot);
        return this.query(sql, jsonHandler, params);
    }
    /**
     * ʹ��XML��ʽ
     *
     * @param sql    SQL�﷨
     * @param params �����б�
     * @return Document XML
     * @throws SQLException
     */
    public Document queryForXml(String sql, Object... params) throws SQLException {
        return null;
    }
    /**
     * �����鷽ʽ���ؽ��
     *
     * @param sql    SQL�﷨
     * @param params �����б�
     * @return Object[]����
     * @throws SQLException
     */
    public Object[] queryForArray(String sql, Object... params) throws SQLException {
        ArrayHandler arrayHandler = new ArrayHandler();
        return this.query(sql, arrayHandler, params);
    }
    /**
     * �����鷽ʽ�б��ؽ��
     *
     * @param sql    SQL�﷨
     * @param params �����б�
     * @return Object[]�б�
     * @throws SQLException
     */
    public List<Object[]> queryForArrayList(String sql, Object... params) throws SQLException {
        ArrayListHandler arrayListHandler = new ArrayListHandler();
        return this.query(sql, arrayListHandler, params);
    }
    /**
     * ��Bean��ʽ�б��ؽ��
     *
     * @param cls    ���ص�������
     * @param sql    SQL�﷨
     * @param params �����б�
     * @param <T>    ���ص���
     * @return T����
     * @throws SQLException
     */
    public <T> T queryForBean(Class<T> cls, String sql, Object... params) throws SQLException {
        BeanHandler<T> beanHandler = new BeanHandler<T>(cls);
        return this.query(sql, beanHandler, params);
    }
    /**
     * ��Bean�б�ʽ�б��ؽ��
     *
     * @param <T>           ���ص���
     * @param cls           ���ص�������
     * @param beanProcessor
     * @param sql           SQL�﷨
     * @param params        �����б�   @return T�����б�   @throws SQLException
     */
    public <T> List<T> queryForBeanList(Class<T> cls, BeanProcessor beanProcessor, String sql, Object... params) throws SQLException {
        BeanListHandler<T> beanListHandler = null;
        if (beanProcessor == null) {
            beanListHandler = new BeanListHandler<T>(cls);
        } else {
            BasicRowProcessor rowProcessor = new BasicRowProcessor(beanProcessor);
            beanListHandler = new BeanListHandler<T>(cls, rowProcessor);
        }
        return this.query(sql, beanListHandler, params);
    }
    /**
     * �����б�ʽ�б��ؽ��
     *
     * @param cls    ���ص�������
     * @param sql    SQL�﷨
     * @param params �����б�
     * @param <T>    ���ص���
     * @return T�����б�
     * @throws SQLException
     */
    public <T> List<T> queryForColumnList(Class<T> cls, String sql, Object... params) throws SQLException {
        ColumnListHandler<T> columnListHandler = new ColumnListHandler<T>(String.valueOf(cls));
        return this.query(sql, columnListHandler, params);
    }
    /**
     * ��Map��ʽ���ضԽ��
     *
     * @param sql    SQL�﷨
     * @param params �����б�
     * @return Map
     * @throws SQLException
     */
    public Map<String, Object> queryForMap(String sql, Object... params) throws SQLException {
        MapHandler mapHandler = new MapHandler();
        return this.query(sql, mapHandler, params);
    }
    /**
     * ��Map�б�ʽ���ضԽ��
     *
     * @param sql    SQL�﷨
     * @param params �����б�
     * @return Map
     * @throws SQLException
     */
    public List<Map<String, Object>> queryForMapList(String sql, Object... params) throws SQLException {
        MapListHandler mapListHandler = new MapListHandler();
        return this.query(sql, mapListHandler, params);
    }
    /**
     * ���ݽ������ʽ��ѯ����
     *
     * @param sql    SQL�﷨
     * @param rsh    ���������
     * @param params �����б�
     * @param <T>    ���ص���
     * @return T����
     * @throws SQLException
     */
    public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
        checkConnection();
        return queryRunner.query(connection, sql, rsh, params);
    }
    /**
     * ���ݽ������ʽ��ѯ����
     *
     * @param sql SQL�﷨
     * @param rsh ���������
     * @param <T> ���ص���
     * @return T����
     * @throws SQLException
     */
    public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        return queryRunner.query(connection, sql, rsh, (Object[]) null);
    }
    public int update(String sql) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        return queryRunner.update(connection, sql, (Object[]) null);
    }
    public int update(String sql, Object param) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        return queryRunner.update(connection, sql, new Object[]{param});
    }
    public int update(String sql, Object... params) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        return queryRunner.update(connection, sql, params);
    }
    public int insert(String sql, Object... params) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(sql, 1);
            queryRunner.fillStatement(stmt, params);
            int result = stmt.executeUpdate();
            return result;
        } catch (SQLException e) {
            throw e;
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
    }
    public <T> T insert(String sql, ResultSetHandler<T> rsh) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        return queryRunner.insert(connection, sql, rsh, (Object[]) null);
    }
    public <T> T insert(String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        return queryRunner.insert(connection, sql, rsh, params);
    }
    /**
     * @param sql    SQL�﷨
     * @param rsh    ���������
     * @param params �����б�
     * @param <T>    ���ص���
     * @return T����
     * @throws SQLException
     */
    public <T> T insertBatch(String sql, ResultSetHandler<T> rsh, Object[][] params) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        return queryRunner.insertBatch(connection, sql, rsh, params);
    }
    /**
     * ����ִ��,insert,update,delete
     *
     * @param sql    SQL�﷨
     * @param params �����б�
     * @return ��Ӱ������
     * @throws SQLException
     */
    public int[] batch(String sql, Object[][] params) throws SQLException {
        checkConnection();
        setTransactionReadCommitted();
        return queryRunner.batch(connection, sql, params);
    }
    /**
     * 时间获取,不使用BeanProcessorEx方法时,只能获取到可能无法获取到时间部分。
     *
     * @return
     * @throws SQLException
     */
    public Date getSystemDateTime() throws SQLException {
        String sql = null;
        if (driver.equals(DataSourcePool.ORACLE_JDBC_DRIVER_ORACLE_DRIVER)) {
            sql = "SELECT sysdate DATE_TIME  FROM dual";
        } else if (driver.equals(DataSourcePool.COM_MICROSOFT_JDBC_SQLSERVER_DRIVER)) {
            sql = "SELECT getdate() AS DATE_TIME";
        } else if (driver.equals(DataSourcePool.COM_MYSQL_JDBC_DRIVER)) {
            sql = "SELECT now() AS DATE_TIME";
        }
        Map<String, String> propertyMap = new HashMap<>();
        propertyMap.put("DATE_TIME", "date");
        BeanProcessorEx beanProcessorEx = new BeanProcessorEx(propertyMap);
        List<SystemDataTime> systemDataTimes = this.queryForBeanList(SystemDataTime.class, beanProcessorEx, sql);
        if (systemDataTimes != null && systemDataTimes.size() != 0) {
            return systemDataTimes.get(0).getDate();
        }
        throw new SQLException("获取数据库系统时间错误.");
    }
    /**
     * �����������
     *
     * @throws SQLException
     */
    private void checkConnection() throws SQLException {
        if (dataSource == null) {
            throw new SQLException("invalid DataSource.");
        }
        if (connection == null || connection.isClosed()) {
            connection = dataSource.getConnection();
        }
        if (connection == null) {
            throw new SQLException("invalid Connection.");
        }
    }
    /**
     * �����������ȼ�Ϊ���ύ�Ķ�ȡ
     *
     * @throws SQLException
     */
    private void setTransactionReadCommitted() throws SQLException {
        connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    }
}

+ 63 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/DataSourcePool.java

@ -0,0 +1,63 @@
package com.yihu.ehr.util.db;
import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
import org.apache.commons.dbcp2.PoolableConnection;
import org.apache.commons.dbcp2.PoolableConnectionFactory;
import org.apache.commons.dbcp2.PoolingDataSource;
import org.apache.commons.pool2.impl.GenericObjectPool;
import javax.sql.DataSource;
/**
 * Created by Air on 2015/5/28.
 */
public class DataSourcePool {
    public static final String JDBC_MYSQL = "jdbc:mysql";
    public static final String JDBC_ORACLE = "jdbc:oracle";
    public static final String JDBC_MICROSOFT_SQLSERVER = "jdbc:microsoft:sqlserver";
    public static final String COM_MYSQL_JDBC_DRIVER = "com.mysql.jdbc.Driver";
    public static final String ORACLE_JDBC_DRIVER_ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
    public static final String COM_MICROSOFT_JDBC_SQLSERVER_DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    private DriverManagerConnectionFactory connectionFactory;
    private PoolableConnectionFactory poolableConnectionFactory;
    private GenericObjectPool<PoolableConnection> connectionPool;
    private String uri;
    public DataSourcePool(String uri) {
        this.uri = uri;
        registerDriver();
        connectionFactory = new DriverManagerConnectionFactory(this.uri, null);
        poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
        connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
        poolableConnectionFactory.setPool(connectionPool);
    }
    public DataSource getDataSource() {
        return new PoolingDataSource<>(connectionPool);
    }
    public void registerDriver() {
        try {
            Class.forName(getDriver());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public String getDriver() {
        if (this.uri.contains(JDBC_MYSQL)) {
            return COM_MYSQL_JDBC_DRIVER;
        } else if (this.uri.contains(JDBC_ORACLE)) {
            return ORACLE_JDBC_DRIVER_ORACLE_DRIVER;
        } else if (this.uri.contains(JDBC_MICROSOFT_SQLSERVER)) {
            return COM_MICROSOFT_JDBC_SQLSERVER_DRIVER;
        }
        return null;
    }
}

+ 77 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/JsonHandler.java

@ -0,0 +1,77 @@
package com.yihu.ehr.util.db;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.ehr.util.operator.DateUtil;
import org.apache.commons.dbutils.ResultSetHandler;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
/**
 * Created by Air on 2015/6/2.
 */
public class JsonHandler implements ResultSetHandler<ObjectNode> {
    public static final String RESULT = "result";
    private String rootTag;
    private ArrayList<String> arrayList;
    public JsonHandler() {
        this(RESULT);
    }
    public JsonHandler(String rootTag) {
        this.rootTag = rootTag;
    }
    public void setTagList(ArrayList<String> arrayList) {
        this.arrayList = arrayList;
    }
    @Override
    public ObjectNode handle(ResultSet resultSet) throws SQLException {
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode result = objectMapper.createObjectNode();
        ArrayNode array = objectMapper.createArrayNode();
        while (resultSet.next()) {
            ObjectNode row = handleRow(resultSet);
            array.add(row);
        }
        result.set(this.rootTag, array);
        return result;
    }
    private ObjectNode handleRow(ResultSet resultSet) throws SQLException {
        final ResultSetMetaData rsmd = resultSet.getMetaData();
        int columnCount = rsmd.getColumnCount();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode row = objectMapper.createObjectNode();
        for (int i = 1; i <= columnCount; i++) {
            String resultSetData = resultSet.getString(i);
            if (rsmd.getColumnType(i) == Types.DATE ||
                    rsmd.getColumnType(i) == Types.TIME ||
                    rsmd.getColumnType(i) == Types.TIMESTAMP
//                    || rsmd.getColumnType(i) == Types.TIME_WITH_TIMEZONE ||
//                    rsmd.getColumnType(i) == Types.TIMESTAMP_WITH_TIMEZONE
                    ) {
                resultSetData = DateUtil.toString(resultSet.getTimestamp(i), DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
            }
            if (arrayList == null) {
                row.put(rsmd.getColumnName(i), resultSetData);
            } else {
                row.put(arrayList.get(i - 1), resultSetData);
            }
        }
        return row;
    }
}

+ 18 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/db/SystemDataTime.java

@ -0,0 +1,18 @@
package com.yihu.ehr.util.db;
import java.util.Date;
/**
 * @created Airhead 2016/1/21.
 */
public class SystemDataTime {
    private Date date;
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
}

+ 129 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encode/Base64.java

@ -0,0 +1,129 @@
package com.yihu.ehr.util.encode;
/**
 * 标准Base64编解码,具体规范请参见相关文档。
 */
public class Base64 {
  /** Base64编码表。*/
  private static char Base64Code[] = {
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/',
  };
  /** Base64解码表。*/
  private static byte Base64Decode[] = {
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  //注意两个63,为兼容SMP,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,63,-1,63,  //“/”和“-”都翻译成63。
    52,53,54,55,56,57,58,59,60,61,-1,-1,-1, 0,-1,-1,
    -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  //注意两个0:
    15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  //“A”和“=”都翻译成0。
    -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
    41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,
  };
  /**
   * 构造方法私有化,防止实例化。
   */
  private Base64() {}
  /**
   * Base64编码。将字节数组中字节3个一组编码成4个可见字符。
   * @param b 需要被编码的字节数据。
   * @return 编码后的Base64字符串。
   */
  public static String encode(byte[] b) {
    int code = 0;
    //按实际编码后长度开辟内存,加快速度
    StringBuffer sb =new StringBuffer(((b.length-1)/3)<<2+4);
    //进行编码
    for (int i=0;i<b.length;i++) {
      code|=(b[i]<<(16-i%3*8)) & (0xff<<(16-i%3*8));
      if (i%3==2 || i==b.length-1) {
        sb.append(Base64Code[(code & 0xfc0000) >>> 18 ]);
        sb.append(Base64Code[(code & 0x3f000)  >>> 12 ]);
        sb.append(Base64Code[(code & 0xfc0)    >>> 6  ]);
        sb.append(Base64Code[ code & 0x3f             ]);
        code=0;
      }
    }
    //对于长度非3的整数倍的字节数组,编码前先补0,编码后结尾处编码用=代替,
    //=的个数和短缺的长度一致,以此来标识出数据实际长度
    if (b.length%3>0) {
      sb.setCharAt(sb.length()-1,'=');
    }
    if (b.length%3==1) {
      sb.setCharAt(sb.length()-2,'=');
    }
    return sb.toString();
  }
  /**
   * Base64解码。
   * @param code 用Base64编码的ASCII字符串
   * @return 解码后的字节数据
   */
  public static byte[] decode(String code) {
    //检查参数合法性
    if (code==null) {
      return null;
    }
    int len = code.length();
    if (len%4!=0) {
      throw new IllegalArgumentException("Base64 string length must be 4*n");
    }
    if (code.length()==0){
      return new byte[0];
    }
    //统计填充的等号个数
    int pad = 0;
    if (code.charAt(len-1)=='=') {
      pad++;
    }
    if (code.charAt(len-2)=='=') {
      pad++;
    }
    //根据填充等号的个数来计算实际数据长度
    int retLen = len/4*3 - pad;
    //分配字节数组空间
    byte[] ret = new byte [retLen];
    //查表解码
    char ch1,ch2,ch3,ch4;
    int i;
    for (i=0;i<len;i+=4) {
      int j=i/4*3;
      ch1 = code.charAt(i);
      ch2 = code.charAt(i+1);
      ch3 = code.charAt(i+2);
      ch4 = code.charAt(i+3);
      int tmp = (Base64Decode[ch1]<<18)|(Base64Decode[ch2]<<12)
                |(Base64Decode[ch3]<<6)|(Base64Decode[ch4]);
      ret[j] = (byte) ((tmp&0xff0000) >> 16);
        if (i<len-4) {
          ret[j+1] = (byte) ((tmp&0x00ff00) >> 8);
          ret[j+2] =(byte) ((tmp&0x0000ff));
        }
        else {
          if(j+1<retLen) {
            ret[j+1] = (byte) ((tmp&0x00ff00) >> 8);
          }
          if(j+2<retLen) {
            ret[j+2] = (byte) ((tmp&0x0000ff));
          }
        }
      }
      return ret;
    }
}

+ 29 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encode/HexEncode.java

@ -0,0 +1,29 @@
package com.yihu.ehr.util.encode;
/**
 * @created Created by Air on 2015/6/2.
 */
public class HexEncode {
    static public String toHexString(byte[] bytes) {
        StringBuilder stringBuffer = new StringBuilder();
        for (byte aByte : bytes) {
            if (Integer.toHexString(0xFF & aByte).length() == 1) {
                stringBuffer.append("0").append(Integer.toHexString(0xFF & aByte));
            } else {
                stringBuffer.append(Integer.toHexString(0xFF & aByte));
            }
        }
        return stringBuffer.toString();
    }
    static public byte[] toBytes(String hexString) {
        byte[] bytes;
        bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }
}

+ 106 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encode/UnicodeReader.java

@ -0,0 +1,106 @@
package com.yihu.ehr.util.encode;
/**
 * UTF-8 编码工具类,解决bom问题
 * Created by HZY on 2015/8/12.
 */
import java.io.*;
/**
 * Generic unicode textreader, which will use BOM mark to identify the encoding
 * to be used. If BOM is not found then use a given default or system encoding.
 */
public class UnicodeReader extends Reader {
	PushbackInputStream internalIn;
	InputStreamReader internalIn2 = null;
	String defaultEnc;
	private static final int BOM_SIZE = 4;
	/**
	 * 
	 * @param in
	 *            inputstream to be read
	 * @param defaultEnc
	 *            default encoding if stream does not have BOM marker. Give NULL
	 *            to use system-level default.
	 */
	public UnicodeReader(InputStream in, String defaultEnc) {
		internalIn = new PushbackInputStream(in, BOM_SIZE);
		this.defaultEnc = defaultEnc;
	}
	public String getDefaultEncoding() {
		return defaultEnc;
	}
	/**
	 * Get stream encoding or NULL if stream is uninitialized. Call init() or
	 * read() method to initialize it.
	 */
	public String getEncoding() {
		if (internalIn2 == null)
			return null;
		return internalIn2.getEncoding();
	}
	/**
	 * Read-ahead four bytes and check for BOM marks. Extra bytes are unread
	 * back to the stream, only BOM bytes are skipped.
	 */
	protected void init() throws IOException {
		if (internalIn2 != null)
			return;
		String encoding;
		byte bom[] = new byte[BOM_SIZE];
		int n, unread;
		n = internalIn.read(bom, 0, bom.length);
		if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
				&& (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
			encoding = "UTF-32BE";
			unread = n - 4;
		} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)
				&& (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
			encoding = "UTF-32LE";
			unread = n - 4;
		} else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB)
				&& (bom[2] == (byte) 0xBF)) {
			encoding = "UTF-8";
			unread = n - 3;
		} else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
			encoding = "UTF-16BE";
			unread = n - 2;
		} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
			encoding = "UTF-16LE";
			unread = n - 2;
		} else {
			// Unicode BOM mark not found, unread all bytes
			encoding = defaultEnc;
			unread = n;
		}
		// System.out.println("read=" + n + ", unread=" + unread);
		if (unread > 0)
			internalIn.unread(bom, (n - unread), unread);
		// Use given encoding
		if (encoding == null) {
			internalIn2 = new InputStreamReader(internalIn);
		} else {
			internalIn2 = new InputStreamReader(internalIn, encoding);
		}
	}
	public void close() throws IOException {
		init();
		internalIn2.close();
	}
	public int read(char[] cbuf, int off, int len) throws IOException {
		init();
		return internalIn2.read(cbuf, off, len);
	}
}

+ 35 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encrypt/DES.java

@ -0,0 +1,35 @@
package com.yihu.ehr.util.encrypt;
import com.yihu.ehr.util.encode.HexEncode;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
 * @created Air 2015/6/2.
 */
public class DES {
    public static String encrypt(String data, String passWord) throws Exception {
        DESKeySpec desKey = new DESKeySpec(passWord.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return HexEncode.toHexString(cipher.doFinal(data.getBytes()));
    }
    public static String decrypt(String data, String passWord) throws Exception {
        DESKeySpec desKey = new DESKeySpec(passWord.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(HexEncode.toBytes(data)));
    }
}

+ 75 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encrypt/MD5.java

@ -0,0 +1,75 @@
package com.yihu.ehr.util.encrypt;
import com.yihu.ehr.util.encode.HexEncode;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.MessageDigest;
import java.security.PrivilegedAction;
/**
 * @created  Air 2015/6/2.
 */
public class MD5 {
    static public String hash(String str) throws Exception {
        MessageDigest messageDigest = null;
        messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(str.getBytes());
        return HexEncode.toHexString(messageDigest.digest());
    }
    public static String getMd5ByFile(File file) throws FileNotFoundException {
        String value = null;
        FileInputStream in = new FileInputStream(file);
        MappedByteBuffer byteBuffer =null;
        try {
            byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
//            BigInteger bi = new BigInteger(1, md5.digest());
//            value = bi.toString(16);
            value= HexEncode.toHexString(md5.digest());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(null != in) {
                try {
                    in.close();
                    clean(byteBuffer);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }
    public static void clean(final Object buffer) throws Exception {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                try {
                    Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
                    getCleanerMethod.setAccessible(true);
                    sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
                    cleaner.clean();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }
}

+ 110 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/encrypt/RSA.java

@ -0,0 +1,110 @@
package com.yihu.ehr.util.encrypt;
import com.yihu.ehr.util.encode.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
/**
 * RSA加密辅助类,采用Base64编码
 *
 * @created Air  2015/6/02.
 */
public class RSA {
    public static final String PUBLIC_KEY = "public";
    public static final String PRIVATE_KEY = "private";
    public static final String KEY_ALGORITHM = "RSA";
    /**
     * 生成公钥和私钥
     *
     * @throws NoSuchAlgorithmException
     */
    public static HashMap<String, Key> generateKeys() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        HashMap<String, Key> map = new HashMap<>();
        map.put(PUBLIC_KEY, publicKey);
        map.put(PRIVATE_KEY, privateKey);
        return map;
    }
    public static String encodeKey(Key key) {
//        return HexEncode.toHexString(key.getEncoded());
        return Base64.encode(key.getEncoded());
    }
    public static Key genPrivateKey(String key) {
//        byte[] bytes = HexEncode.toBytes(key);
        byte[] bytes = Base64.decode(key);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(bytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Key genPublicKey(String key) {
        if (key == null){
            return null;
        }
        byte[] bytes = Base64.decode(key);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePublic(x509KeySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * @param data 明文
     * @param key  密钥
     * @return HexString密文
     * @throws Exception
     */
    public static String encrypt(String data, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
//        return HexEncode.toHexString(cipher.doFinal(data.getBytes()));
        return Base64.encode(cipher.doFinal(data.getBytes()));
    }
    /**
     * @param data HexString密文
     * @param key  密钥
     * @return 明文
     * @throws Exception
     */
    public static String decrypt(String data, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
//        return new String(cipher.doFinal(HexEncode.toBytes(data)));
        return new String(cipher.doFinal(Base64.decode(data)));
    }
}

+ 247 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/file/FileUtil.java

@ -0,0 +1,247 @@
package com.yihu.ehr.util.file;
import java.io.*;
/**
 * @author Air
 * @version 1.0
 * @created 2015.06.25 14:14
 */
public class FileUtil {
    public static boolean writeFile(String filePath, String data, String encoding) throws IOException {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                return false;
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, encoding);
        outputStreamWriter.write(data);
        outputStreamWriter.flush();
        outputStreamWriter.close();
        return true;
    }
    public static boolean writeFile(String filePath, byte[] bytes, String encoding) throws IOException {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                return false;
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] bbuf = new byte[1024];
        InputStream fis = new ByteArrayInputStream(bytes);
        int hasRead = 0;
        //循环从输入流中取出数据
        while ((hasRead = fis.read(bbuf)) > 0) {
            fileOutputStream.write(bbuf, 0, hasRead);
        }
        fileOutputStream.close();
        return true;
    }
    public static boolean writeFile(String filePath, InputStream fis, String encoding) throws IOException {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                return false;
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] bbuf = new byte[1024];
        int hasRead = 0;
        //循环从输入流中取出数据
        while ((hasRead = fis.read(bbuf)) > 0) {
            fileOutputStream.write(bbuf, 0, hasRead);
        }
        fileOutputStream.close();
        return true;
    }
    /**
     * 删除整个目录
     *
     * @param dir 目录
     * @return boolean
     * @created Airhead
     */
    public static boolean deleteDirectory(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDirectory(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }
    /**
     * file转string
     *
     * @param file 文件
     * @return string类型流
     */
    public static String convertFileToString(File file) {
        StringBuilder sb = new StringBuilder();
        if (file.isFile() && file.exists()) {
            InputStreamReader read = null;
            try {
                read = new InputStreamReader(new FileInputStream(file), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            BufferedReader reader = new BufferedReader(read);
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
    /**
     * 清空文件内容
     *
     * @param filePath 文件路径
     * @param content  写入内容
     */
    public static void clearInfoForFile(String filePath, String content) {
        File file = new File(filePath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 记录文件最后读取的位置
     *
     * @param readPath 被读取文件路径
     * @param savePath 保存被读取文件的最后位置 的文件路径
     */
    public static Integer saveFilePos(String readPath, String savePath) {
        boolean result = false;
        File readFile = new File(readPath);
        Integer lenth = null;
        try {
            if (readFile.exists()) {
                InputStream inputStream = new FileInputStream(readPath);
                lenth = inputStream.available();
                clearInfoForFile(savePath, "");//清空内容
                writeFile(savePath, lenth.toString(), "UTF-8");//重新写入标识
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lenth;
    }
    public static Integer getFileSize(String path) {
        Integer size = 0;
        InputStream inputStream = null;
        File file = new File(path);
        if (file.exists()) {
            try {
                inputStream = new FileInputStream(path);
                size = inputStream.available();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return size;
    }
    /**
     * 读取文本文件内容
     *
     * @param file 文件路径
     * @return
     */
    public static String readFileText(File file) {
        StringBuilder stringBuilder = new StringBuilder();
        InputStream in = null;
        BufferedReader br = null;
        try {
            in = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
        return stringBuilder.toString();
    }
    public static File writeFile(String filePathAndName, String fileContent) {
        File f = new File(filePathAndName);
        OutputStreamWriter write =null;
        BufferedWriter writer=null;
        try {
            if (!f.exists()) {
                f.createNewFile();
            }
             write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
             writer = new BufferedWriter(write);
             writer.write(fileContent);
        } catch (Exception e) {
            System.out.println("写文件内容操作出错");
            e.printStackTrace();
        }finally {
            try {
                if(writer!=null){
                    writer.close();
                }
                if(write!=null){
                    write.close();
                }
            }catch (Exception e){
                e.printStackTrace();;
            }
        }
        return f;
    }
}

+ 338 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/EsbHttp.java

@ -0,0 +1,338 @@
package com.yihu.ehr.util.httpclient;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.common.config.SysConfig;
import com.yihu.ehr.common.constants.Constants;
import com.yihu.ehr.model.Patient;
import com.yihu.ehr.service.intf.ISystemManager;
import com.yihu.ehr.util.encrypt.MD5;
import com.yihu.ehr.util.log.LogUtil;
import com.yihu.ehr.util.operator.ConfigureUtil;
import com.yihu.ehr.util.operator.StringUtil;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by hzp on 2016/3/10.
 */
public class EsbHttp {
    @Autowired
    private static ISystemManager system;
    /***************************** 用户接口 *********************************************/
    /**
     * 用户登录验证
     */
    public static Response loginAction(String user,String password) throws Exception{
        String loginAction = HttpHelper.defaultHttpUrl+"/authorizations/users/" + user;
        Map<String,Object> header = new HashMap<>();
        String auth  = new BASE64Encoder().encode((user+":"+password).getBytes());
        header.put("Authorization","Basic "+auth);
        return HttpHelper.put(loginAction, null, header);
    }
    /*
    *   获取用户信息
    * */
    public static Response getUserInfo(String user,String token)
    {
        String url = HttpHelper.defaultHttpUrl+"/users/" + user;
        Map<String,Object> params = new HashMap<>();
        params.put("token",token);
        params.put("user",user);
        return HttpHelper.get(url, params);
    }
    /***************************** 应用接口 *********************************************/
    /**
     * 获取本机指纹
     * @return
     */
    private static String GetFingerprint(){
        try {
            return system.getSystemParam("FINGER_PRINT");
        }
        catch (Exception e)
        {
            System.out.print(e.getMessage());
            return "";
        }
    }
    /**
     * 应用登录验证
     */
    public static String getToken(){
        try {
            String loginAction = HttpHelper.defaultHttpUrl + "/authorizations/clients/" + HttpHelper.clientId;
            Map<String, Object> header = new HashMap<>();
            header.put("Authorization", "Basic " + HttpHelper.clientKey);
            //本地指纹
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("info", "{\"fingerprint\": \"" + GetFingerprint() + "\"}");
            Response response = HttpHelper.put(loginAction, params, header);
            if (response != null && response.getStatusCode() == HttpStatus.SC_OK) {
                JSONObject obj = new JSONObject(response.getBody());
                //判断是否成功
                if (obj.has("token")) {
                    return obj.getString("token");
                } else {
                    LogUtil.info("返回未包含token。");
                    return null;
                }
            } else {
                String msg = "获取Token失败。";
                if (response != null) {
                    msg += "(错误代码:" + response.getStatusCode() + ",错误信息:" + response.getBody() + ")";
                }
                LogUtil.info(msg);
                return null;
            }
        }
        catch (Exception ex)
        {
            LogUtil.info("获取Token失败," + ex.getMessage());
            return null;
        }
    }
    /**
     * 修改远程补传状态
     */
    public static void changeFillMiningStatus(String remoteId,String message, String status){
        try {
            String token = getToken();
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", remoteId);
            paramMap.put("status", status);
            paramMap.put("message", message);
            paramMap.put("token", token);
            String fillMiningMethod = HttpHelper.defaultHttpUrl + "/simplified-esb/changeFillMiningStatus";
            Response response = HttpHelper.post(fillMiningMethod, paramMap);
            if (response != null && response.getStatusCode() == HttpStatus.SC_OK) {
                LogUtil.info("修改远程补传状态成功。");
            }
            else{
                String msg = "修改远程补传状态失败。";
                if (response != null)
                {
                    msg +="(错误代码:"+ response.getStatusCode() + ",错误信息:"+response.getBody()+")";
                }
                LogUtil.info(msg);
            }
        }
        catch (Exception ex)
        {
            LogUtil.info("修改远程补传状态失败." + ex.getMessage());
        }
    }
    /**
     * 获取公钥
     */
    public static String getPublicKey(){
        try {
            String token = getToken();
            if (SysConfig.getInstance().getPublicKey() != null) {
                return SysConfig.getInstance().getPublicKey();
            }
            String orgCode = SysConfig.getInstance().getOrgCode();
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("org_code", orgCode);
            paramMap.put("token", token);
            String publicKeyMethod = HttpHelper.defaultHttpUrl + "/organizations/"+orgCode+"/key";
            Response response = HttpHelper.get(publicKeyMethod, paramMap);
            if (response != null && response.getStatusCode() == HttpStatus.SC_OK) {
                JSONObject json = new JSONObject(response.getBody());
                if(json.has("publicKey"))
                {
                    String key = json.getString("publicKey");
                    SysConfig.getInstance().setPublicKey(key);
                    return key;
                }
                else{
                    LogUtil.info("获取公钥失败,返回未包含publicKey。");
                    return null;
                }
            }
            else{
                String msg = "获取公钥失败。";
                if (response != null)
                {
                    msg +="(错误代码:"+ response.getStatusCode() + ",错误信息:"+response.getBody()+")";
                }
                LogUtil.info(msg);
                return null;
            }
        } catch (Exception e) {
            LogUtil.info(e.getMessage());
            return null;
        }
    }
    /**
     * 获取健康云平台标准版本号
     */
    public static String getRemoteVersion(String orgCode) {
        try {
            String token = getToken();
            String versionMethod = HttpHelper.defaultHttpUrl + "/adaptions/org_plan/version";
            Map<String, Object> params = new HashMap<>();
            params.put("org_code", orgCode);
            params.put("token", token);
            Response response = HttpHelper.get(versionMethod, params);
            if (response != null && response.getStatusCode() == HttpStatus.SC_OK) {
                return response.getBody();
            }
            else{
                String msg = "获取健康云平台标准版本号失败";
                if (response != null)
                {
                    msg +="(错误代码:"+ response.getStatusCode() + ",错误信息:"+response.getBody()+")";
                }
                LogUtil.info(msg);
                return null;
            }
        } catch (Exception e) {
            LogUtil.fatal("获取远程版本号异常");
            LogUtil.error(e);
            return null;
        }
    }
    /**
     * 注册病人
     */
    public static Boolean register(Patient patient, String data, String token) {
        try {
            JSONObject json = new JSONObject(data);
            String colName = SysConfig.registerIdCardNo;
            if(json!=null && json.has("data"))
            {
                JSONObject p = (JSONObject)json.getJSONArray("data").get(0);
                if(!p.has(colName) || p.get(colName).equals(null) || p.getString(colName).length()==0)
                {
                    LogUtil.info("注册病人信息请求失败:身份证号码为空,patient_id=" + patient.getPatientId() + ", event_no=" + patient.getEventNo());
                    return false;
                }
                else{
                    String idCord = p.getString(colName);
                    String registerMethod = HttpHelper.defaultHttpUrl + "/patients/"+idCord;
                    if (StringUtil.isEmpty(data)) {
                        LogUtil.info("注册病人信息请求失败:无具体病人信息,patient_id=" + patient.getPatientId() + ", event_no=" + patient.getEventNo());
                        return false;
                    }
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("demographic_id", idCord);
                    paramMap.put("json", data);
                    paramMap.put("token", token);
                    Response response = HttpHelper.post(registerMethod, paramMap);
                    if (response != null && response.getStatusCode() == HttpStatus.SC_OK) {
                        LogUtil.info("注册病人信息成功。patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo());
                        return true;
                    }
                    else{
                        String msg = "注册病人信息请求失败。patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo();
                        if(response != null)
                        {
                            msg +="(错误代码:"+ response.getStatusCode() + ",错误信息:"+response.getBody()+")";
                        }
                        LogUtil.info(msg);
                        return false;
                    }
                }
            }
            else{
                LogUtil.info("注册病人信息请求失败:传入数据无效,patient_id=" + patient.getPatientId() + ", event_no=" + patient.getEventNo());
                return false;
            }
        }
        catch (Exception e)
        {
            LogUtil.info("注册病人信息请求失败."+e.getMessage());
            return false;
        }
    }
    /**
     * 上传病人档案
     */
    public static boolean upload(Patient patient, File file, String encryptPwd, String token) {
        try {
            String uploadMethod = HttpHelper.defaultHttpUrl + "/packages";
            String fileMd5= MD5.getMd5ByFile(file);
            Map<String, Object> paramMap = new HashMap<>();
            List<NameValuePair> formParams = new ArrayList<>();
            formParams.add(new BasicNameValuePair("md5", fileMd5));
            formParams.add(new BasicNameValuePair("package_crypto", encryptPwd));
            formParams.add(new BasicNameValuePair("org_code", SysConfig.getInstance().getOrgCode()));
            formParams.add(new BasicNameValuePair("token", token));
            Response response = HttpHelper.postFile(uploadMethod, formParams, file.getAbsolutePath());
            if (response != null && response.getStatusCode() == HttpStatus.SC_OK) {
                LogUtil.info("上传病人档案成功,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo());
                return true;
            }
            else {
                String msg = "上传病人档案请求失败,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo();
                if (response != null)
                {
                    msg +="(错误代码:"+ response.getStatusCode() + ",错误信息:"+response.getBody()+")";
                }
                LogUtil.info(msg);
                return false;
            }
        }
        catch (Exception e) {
            LogUtil.fatal("上传病人档案异常,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo());
            LogUtil.error(e);
            return false;
        }
    }
    /**
     * 下载标准包
     */
    public static Response download(String remoteVersion, String orgCode) {
        try {
            String token = getToken();
            String downLoadMethod = HttpHelper.defaultHttpUrl + "/adaptions/"+orgCode+"/source";
            Map<String, Object> params = new HashMap<>();
            params.put("version_code", remoteVersion);
            params.put("org_code", orgCode);
            params.put("token", token);
            Response response = HttpHelper.get(downLoadMethod, params);
            return response;
        } catch (Exception e) {
            LogUtil.fatal("下载标准包异常:");
            LogUtil.error(e);
            return null;
        }
    }
}

+ 22 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/HopHostnameVerifier.java

@ -0,0 +1,22 @@
package com.yihu.ehr.util.httpclient;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
/**
 * @author Air
 * @version 1.0
 * @created 2015.07.02 15:48
 */
public class HopHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
//        if("localhost".equals(hostname)){
//            return true;
//        } else {
//            return false;
//        }
        return true;
    }
}

+ 311 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/HttpClientUtil.java

@ -0,0 +1,311 @@
package com.yihu.ehr.util.httpclient;
import com.yihu.ehr.util.encode.Base64;
import com.yihu.ehr.util.log.LogUtil;
import org.apache.http.*;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2016/3/9.
 */
public class HttpClientUtil {
    /**************************** 私有方法 *****************************************/
    private static CloseableHttpClient getCloseableHttpClient(SSLConnectionSocketFactory ssl) {
        if(ssl == null)
        {
            return HttpClients.createDefault();
        }
        else{
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(ssl)
                    .build();
            return httpClient;
        }
    }
    private static void close(CloseableHttpClient httpClient, CloseableHttpResponse response) {
        try {
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (Exception e) {
            LogUtil.error("关闭httpClient失败");
        }
        try {
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            LogUtil.error("关闭httpClient失败");
        }
    }
    private static HttpRequestBase getRequest(String method,String url,Map<String,Object> params,Map<String,Object> header) throws Exception
    {
        List<BasicNameValuePair> jsonParams = new ArrayList<>();
        //配置参数
        if(params!=null) {
            for (String key : params.keySet()) {
                jsonParams.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
            }
        }
        HttpRequestBase request;
        if(method.equals("POST"))
        {
            request = new HttpPost(url + "?" + URLEncodedUtils.format(jsonParams, Consts.UTF_8));
        }
        else if(method.equals("PUT"))
        {
            request = new HttpPut(url + "?" + URLEncodedUtils.format(jsonParams, Consts.UTF_8));
        }
        else if(method.equals("DELETE"))
        {
            request = new HttpDelete(url + "?" + URLEncodedUtils.format(jsonParams, Consts.UTF_8));
        }
        else
        {
            request = new HttpGet(url + "?" + URLEncodedUtils.format(jsonParams, Consts.UTF_8));
        }
        //配置头部信息
        if(header!=null)
        {
            for (String key : header.keySet()) {
                request.addHeader(key, header.get(key).toString());
            }
        }
        return request;
    }
    /****************************** 公用方法 *******************************************/
    /**
     * get请求
     */
    public static Response request(String method,String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password) {
        Response re = new Response();
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = getCloseableHttpClient(ssl);
        //设置请求信息
        try {
            RequestConfig requestConfig = RequestConfig.custom().
                    setAuthenticationEnabled(true).build();
            HttpRequestBase request = getRequest(method,url,params,header);
            request.setConfig(requestConfig);
            //需要验证
            if (!StringUtils.isEmpty(user) && !StringUtils.isEmpty(password)) {
                HttpClientContext context = HttpClientContext.create();
                //通过http的上下文设置账号密码
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new org.apache.http.auth.AuthScope(org.apache.http.auth.AuthScope.ANY_HOST, org.apache.http.auth.AuthScope.ANY_PORT),new org.apache.http.auth.UsernamePasswordCredentials(user, password));
                context.setCredentialsProvider(credsProvider);
                response = httpclient.execute(request, context);
            } else {
                response = httpclient.execute(request);
            }
            re.setStatusCode(response.getStatusLine().getStatusCode());
            re.setBody(EntityUtils.toString(response.getEntity(), "UTF-8"));
        } catch (Exception e) {
            re.setStatusCode(201);
            re.setBody(e.getMessage());
        } finally {
            close(httpclient, response);
        }
        return re;
    }
    /**
     * 发送文件
     *
     * @param url        路径
     * @param formParams 参数
     * @return
     */
    public static Response postFile(String url,
                                    File file, List<NameValuePair> formParams,SSLConnectionSocketFactory ssl, String username, String password) {
        Response re = new Response();
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = getCloseableHttpClient(ssl);
        try{
            //设置请求信息
            RequestConfig requestConfig = RequestConfig.custom().
                    setAuthenticationEnabled(true).build();
            //创建httppost请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            //新建文件对象并且设置文件
            FileBody bin = new FileBody(file);
            MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
            reqEntity.addPart("file", bin);
            //设置参数
            if (formParams != null && formParams.size() > 0) {
                for (NameValuePair nv : formParams) {
                    reqEntity.addTextBody(nv.getName(), nv.getValue(), ContentType.create("text/plain", Charset.forName(HTTP.UTF_8)));
                }
            }
            httpPost.setEntity(reqEntity.build());
            //设置验证
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                //需要验证
                HttpClientContext context = HttpClientContext.create();
                //通过http的上下文设置账号密码
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new org.apache.http.auth.AuthScope(org.apache.http.auth.AuthScope.ANY_HOST, org.apache.http.auth.AuthScope.ANY_PORT),
                        new org.apache.http.auth.UsernamePasswordCredentials(username, password));
                context.setCredentialsProvider(credsProvider);
                response = httpClient.execute(httpPost, context);
            } else {
                response = httpClient.execute(httpPost);
            }
            re.setStatusCode(response.getStatusLine().getStatusCode());
            re.setBody(EntityUtils.toString(response.getEntity(), "UTF-8"));;
        } catch (Exception e) {
            re.setStatusCode(201);
            re.setBody(e.getMessage());
            System.out.print(e.getMessage());
        } finally {
            close(httpClient, response);
        }
        return re;
    }
    /**
     * 发送File
     */
    public static File downLoadFileByBase64(String filePath, Map<String, Object> params, String url, String username, String password) {
        File file = null;
        CloseableHttpResponse response = null;
        List<BasicNameValuePair> jsonParams = new ArrayList<>();
        CloseableHttpClient httpclient = getCloseableHttpClient(null);
        try {
            HttpPost httpPost = new HttpPost(url);
            //设置请求信息
            RequestConfig requestConfig = RequestConfig.custom().
                    setAuthenticationEnabled(true).build();
            //设置参数
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                formparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            httpPost.setEntity(entity);
            httpPost.setConfig(requestConfig);
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                //需要验证
                HttpClientContext context = HttpClientContext.create();
                //通过http的上下文设置账号密码
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new org.apache.http.auth.AuthScope(org.apache.http.auth.AuthScope.ANY_HOST, org.apache.http.auth.AuthScope.ANY_PORT),
                        new org.apache.http.auth.UsernamePasswordCredentials(username, password));
                context.setCredentialsProvider(credsProvider);
                response = httpclient.execute(httpPost, context);
            } else {
                response = httpclient.execute(httpPost);
            }
            HttpEntity httpEntity = response.getEntity();
            String responString = EntityUtils.toString(httpEntity, "UTF-8");
            file = new File(filePath);
            file.getParentFile().mkdirs();
            InputStream i = new ByteArrayInputStream(Base64.decode(responString));
            FileOutputStream fileout = new FileOutputStream(file);
            /**
             * 根据实际运行效果 设置缓冲区大小
             */
            byte[] buffer = new byte[1024];
            int ch = 0;
            while ((ch = i.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            i.close();
            fileout.flush();
            fileout.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            close(httpclient, response);
        }
        return file;
    }
    /**
     * 下载文件
     */
    public static File downLoadFile(String filePath, String url, String username, String password) {
        File file = null;
        CloseableHttpResponse response = null;
        List<BasicNameValuePair> jsonParams = new ArrayList<>();
        CloseableHttpClient httpclient = getCloseableHttpClient(null);
        try {
            HttpGet httpGet = new HttpGet(url);
            //设置请求信息
            RequestConfig requestConfig = RequestConfig.custom().
                    setAuthenticationEnabled(true).build();
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                //需要验证
                HttpClientContext context = HttpClientContext.create();
                //通过http的上下文设置账号密码
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new org.apache.http.auth.AuthScope(org.apache.http.auth.AuthScope.ANY_HOST, org.apache.http.auth.AuthScope.ANY_PORT),
                        new org.apache.http.auth.UsernamePasswordCredentials(username, password));
                context.setCredentialsProvider(credsProvider);
                response = httpclient.execute(httpGet, context);
            } else {
                response = httpclient.execute(httpGet);
            }
            HttpEntity httpEntity = response.getEntity();
            InputStream is = httpEntity.getContent();
            file = new File(filePath);
            file.getParentFile().mkdirs();
            FileOutputStream fileout = new FileOutputStream(file);
            /**
             * 根据实际运行效果 设置缓冲区大小
             */
            byte[] buffer = new byte[1024];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();
        } catch (Exception e) {
            return null;
        } finally {
            close(httpclient, response);
        }
        return file;
    }
}

+ 246 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/HttpHelper.java

@ -0,0 +1,246 @@
package com.yihu.ehr.util.httpclient;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.ssl.SSLContexts;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class HttpHelper {
    private static String defaultPropertiesPath = "config/http.properties";
    private static SSLConnectionSocketFactory defaultSSL;
    private static String defaultHttpUser;
    private static String defaultHttpPassword;
    public static String defaultHttpUrl;
    public static String clientId;
    public static String clientKey;
    static {
        //默认配置
        try {
            Resource resource = new ClassPathResource(defaultPropertiesPath);
            EncodedResource encRes = new EncodedResource(resource,"UTF-8");
            Properties props = PropertiesLoaderUtils.loadProperties(encRes);
            defaultHttpUrl= props.getProperty("httpUrl");
            defaultHttpUser= props.getProperty("httpUser");
            defaultHttpPassword= props.getProperty("httpPassword");
            clientId = props.getProperty("clientId");
            clientKey = props.getProperty("clientKey");
            String sslKeystore = props.getProperty("sslKeystore");
            String sslPassword = props.getProperty("sslPassword");
            if(sslKeystore!=null && sslKeystore.length()>0 && sslPassword!=null &&sslPassword.length()>0)
            {
                SSLContext sslContext = SSLContexts.custom()
                        .loadTrustMaterial(new File(sslKeystore), sslPassword.toCharArray(),
                                new TrustSelfSignedStrategy())
                        .build();
                defaultSSL = new SSLConnectionSocketFactory(
                        sslContext,
                        new String[]{"TLSv1"},
                        null,
                        new HopHostnameVerifier());
            }
        }
        catch (Exception e) {
            System.out.print(e.getMessage());
        }
    }
    /************************** Get方法 ******************************************/
    public static Response get(String url)
    {
        return get(url,null,null);
    }
    public static Response get(String url,Map<String,Object> params)
    {
        return get(url,params,null);
    }
    public static Response get(String url,Map<String,Object> params,Map<String,Object> header)
    {
        if(url.startsWith("https"))
        {
            return get(url,params,header,defaultSSL);
        }
        else{
            //默认http不走ssl和用户密码
            return get(url, params, header, null, null, null);
        }
    }
    public static Response get(String url,Map<String,Object> params,Map<String,Object> header,Boolean isCheck)
    {
        if(isCheck)
        {
            return get(url, params, header,defaultSSL, defaultHttpUser, defaultHttpPassword);
        }
        else{
            return get(url, params, header, null, null, null);
        }
    }
    public static Response get(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl)
    {
        return get(url, params, header, ssl, defaultHttpUser, defaultHttpPassword);
    }
    public static Response get(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password)
    {
        return HttpClientUtil.request("GET", url, params, header, ssl, user, password);
    }
    /************************** Post方法 ******************************************/
    public static Response post(String url)
    {
        return post(url, null, null);
    }
    public static Response post(String url,Map<String,Object> params)
    {
        return post(url, params, null);
    }
    public static Response post(String url,Map<String,Object> params,Map<String,Object> header)
    {
        if(url.startsWith("https"))
        {
            return post(url, params, header, defaultSSL);
        }
        else{
            //默认http不走ssl和用户密码
            return post(url, params, header, null, null, null);
        }
    }
    public static Response post(String url,Map<String,Object> params,Map<String,Object> header,Boolean isCheck)
    {
        if(isCheck)
        {
            return post(url, params, header, defaultSSL, defaultHttpUser, defaultHttpPassword);
        }
        else{
            return post(url, params, header, null, null, null);
        }
    }
    public static Response post(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl)
    {
        return post(url, params, header, ssl, defaultHttpUser, defaultHttpPassword);
    }
    public static Response post(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password)
    {
        return HttpClientUtil.request("POST",url,params,header,ssl,user,password);
    }
    public static Response postFile(String url, List<NameValuePair> formParams, String filePath)
    {
        File file = new File(filePath);
        if(url.startsWith("https"))
        {
            return HttpClientUtil.postFile(url, file, formParams, defaultSSL,defaultHttpUser,defaultHttpPassword);
        }
        else{
        //默认http不走ssl和用户密码
        return HttpClientUtil.postFile(url, file, formParams, null,defaultHttpUser,defaultHttpPassword);
    }
    }
    public static Response postFile(String url, List<NameValuePair> formParams, File file)
    {
        if(url.startsWith("https"))
        {
            return HttpClientUtil.postFile(url, file, formParams, defaultSSL,defaultHttpUser,defaultHttpPassword);
        }
        else{
            //默认http不走ssl和用户密码
            return HttpClientUtil.postFile(url, file, formParams, null,defaultHttpUser,defaultHttpPassword);
        }
    }
    /************************** Put方法 ******************************************/
    public static Response put(String url)
    {
        return put(url, null, null);
    }
    public static Response put(String url,Map<String,Object> params)
    {
        return put(url, params, null);
    }
    public static Response put(String url,Map<String,Object> params,Map<String,Object> header)
    {
        if(url.startsWith("https"))
        {
            return put(url, params, header, defaultSSL);
        }
        else{
            //默认http不走ssl和用户密码
            return put(url, params, header, null, null, null);
        }
    }
    public static Response put(String url,Map<String,Object> params,Map<String,Object> header,Boolean isCheck)
    {
        if(isCheck)
        {
            return put(url, params, header, defaultSSL, defaultHttpUser, defaultHttpPassword);
        }
        else{
            return put(url, params, header, null, null, null);
        }
    }
    public static Response put(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl)
    {
        return put(url, params, header, ssl, defaultHttpUser, defaultHttpPassword);
    }
    public static Response put(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password)
    {
        return HttpClientUtil.request("PUT",url,params,header,ssl,user,password);
    }
    /************************** Delete方法 **************************************/
    public static Response delete(String url)
    {
        return delete(url, null, null);
    }
    public static Response delete(String url,Map<String,Object> params)
    {
        return delete(url, params, null);
    }
    public static Response delete(String url,Map<String,Object> params,Map<String,Object> header)
    {
        if(url.startsWith("https"))
        {
            return delete(url, params, header, defaultSSL);
        }
        else{
            //默认http不走ssl和用户密码
            return delete(url, params, header, null, null, null);
        }
    }
    public static Response delete(String url,Map<String,Object> params,Map<String,Object> header,Boolean isCheck)
    {
        if(isCheck)
        {
            return delete(url, params, header, defaultSSL, defaultHttpUser, defaultHttpPassword);
        }
        else{
            return delete(url, params, header, null, null, null);
        }
    }
    public static Response delete(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl)
    {
        return delete(url, params, header, ssl, defaultHttpUser, defaultHttpPassword);
    }
    public static Response delete(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password)
    {
        return HttpClientUtil.request("DELETE",url,params,header,ssl,user,password);
    }
    /**************************** 其他方法 ***************************************/
}

+ 36 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/httpclient/Response.java

@ -0,0 +1,36 @@
package com.yihu.ehr.util.httpclient;
/**
 * add by hzp at 2016-3-10
 */
public class Response {
    public Response()
    {
    }
    public Response(int statusCode, String body) {
        this.statusCode = statusCode;
        this.body = body;
    }
    private int statusCode;
    private String body;
    public int getStatusCode() {
        return statusCode;
    }
    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }
    public String getBody() {
        return body;
    }
    public void setBody(String body) {
        this.body = body;
    }
}

+ 35 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/json/JSON.java

@ -0,0 +1,35 @@
package com.yihu.ehr.util.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.util.file.FileUtil;
import net.sf.json.JSONObject;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
 * Created by chenweida on 2016/3/24.
 */
public class JSON {
    public static final String[] key = {"data", "event_no", "patient_id"};
    public static File json2File(Map<String,Object> params) {
        String dataset= (String) params.get("dataset");
        //先转json
        String jsonDataSet = XML2JSON.xml2JSON(dataset);
        JSONObject jo = new JSONObject();
        for(Map.Entry<String,Object> a:params.entrySet()){
            if(!"dataset".equals(a.getKey())){
                jo.put(a.getKey(),a.getValue());
            }
        }
        String jsonString=jo.toString();
        //json转文件
        String home = System.getProperty("catalina.home").replace('\\', '/');
        SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");
        String filePath=home + File.separator +sd.format(new Date());
        return FileUtil.writeFile(filePath,jsonString);
    }
}

+ 37 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/json/XML2JSON.java

@ -0,0 +1,37 @@
package com.yihu.ehr.util.json;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
/**
 * Created by chenweida on 2016/3/24.
 */
public class XML2JSON {
    public static String xml2JSON(String xml) {
        return new XMLSerializer().read(xml).toString();
    }
    public static String json2XML(String json) {
        //json
        JSONObject jobj = JSONObject.fromObject(json);
        String xml = new XMLSerializer().write(jobj);
        return xml;
    }
    public static void main(String[] args) {
        System.out.println(xml2JSON("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Data><PATIENT_ID>病人ID</PATIENT_ID>\n" +
                "\t<EVENT_NO>门诊号(挂号号) / 住院号</EVENT_NO>\n" +
                "\t<HDSD00_05_040>检验报告单号</HDSD00_05_040>\n" +
                "\t<JDSD02_03_02>子项序号</JDSD02_03_02>\n" +
                "\t<JDSD02_03_03>子项的LOINC编码</JDSD02_03_03>\n" +
                "\t<JDSD02_03_13>子项目中文名称</JDSD02_03_13>\n" +
                "\t<JDSD02_03_14>子项目英文名称</JDSD02_03_14>\n" +
                "\t<JDSD02_03_04>结果类型</JDSD02_03_04>\n" +
                "\t<JDSD02_03_05>结果值</JDSD02_03_05>\n" +
                "\t<HDSD00_01_547>单位</HDSD00_01_547>\n" +
                "\t<JDSD02_03_06>正常参考值下限</JDSD02_03_06>\n" +
                "\t<JDSD02_03_07>正常参考值上限</JDSD02_03_07>\n" +
                "\t<JDSD02_03_08>参考值备注</JDSD02_03_08>\n" +
                "\t<JDSD02_03_09>结果值的解释</JDSD02_03_09></Data>"));
    }
}

+ 50 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/log/LogUtil.java

@ -0,0 +1,50 @@
package com.yihu.ehr.util.log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import java.io.File;
public class LogUtil {
    static Logger logger = LogManager.getLogger(LogUtil.class.getName());
    public static void entry() {
        logger.entry();
    }
    public static void trace(String msg) {
        logger.trace(msg);
    }
    public static void info(String msg) {
        logger.info(msg);
    }
    public static void debug(String msg) {
        logger.debug(msg);
    }
    public static void error(String msg) {
        logger.error(msg);
    }
    public static void error(Exception e) {
        for (StackTraceElement msg : e.getStackTrace()) {
            logger.error(msg);
        }
    }
    public static void warn(String msg) {
        logger.warn(msg);
    }
    public static void fatal(String msg) {
        logger.fatal(msg);
    }
    public static void exit() {
        logger.exit();
    }
}

+ 47 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/operator/BeanUtil.java

@ -0,0 +1,47 @@
package com.yihu.ehr.util.operator;
import org.apache.commons.beanutils.PropertyUtils;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * Created by lingfeng on 2015/12/29.
 */
public class BeanUtil {
    public static List objectArray2Bean(List list, Class beanClass){
        Constructor beanConstructor;
        try        {
            beanConstructor =  beanClass.getConstructor(new Class[] {Object[].class});
        }
        catch (Exception e)        {
            return null;
        }
        Iterator it = list.iterator();
        List result = new ArrayList();
        result.clear();
        while (it.hasNext())        {
            Object bean;
            try            {
                bean = beanConstructor.newInstance(new Object[] {it.next()});
            }
            catch (Exception e)            {
                return null;
            }
            result.add(beanClass.cast(bean));
        }
        return result;
    }
    public static Object getPropertyValue(Object o, String name) {
        try {
            return PropertyUtils.getProperty(o, name);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

+ 18 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/operator/CollectionUtil.java

@ -0,0 +1,18 @@
package com.yihu.ehr.util.operator;
import org.apache.commons.collections.CollectionUtils;
import java.util.Collection;
/**
 * Hibernate Criteria utils
 *
 * @since 1.0.6
 */
public class CollectionUtil {
    public static boolean isEmpty(Collection coll) {
        return CollectionUtils.isEmpty(coll);
    }
}

+ 38 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/operator/ConfigureUtil.java

@ -0,0 +1,38 @@
package com.yihu.ehr.util.operator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.util.Properties;
/**
 *  获取配置文件内容滚工具类
 * Created by HZY on 2015/10/29.
 */
public class ConfigureUtil {
    /**
     * 获取.propertiest文件属性值
     * @param filePath  文件路径
     * @param key        属性名:key
     * @return value     属性值:value
     */
    public static String CRAWLER_PROPERTIES = "config/crawler.properties";
    public static String getProValue(String filePath, String key) {
        Resource resource = null;
        Properties props = null;
        String value = null;
        try {
            resource = new ClassPathResource(filePath);
            EncodedResource encRes = new EncodedResource(resource,"UTF-8");
            props = PropertiesLoaderUtils.loadProperties(encRes);
            value= (String) props.get(key);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }
}

+ 0 - 0
Hos-Resource-Cloud/src/main/java/com.yihu.ehr/util/operator/DateUtil.java


Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini