浏览代码

Merge branch 'master' of http://192.168.1.220:10080/esb/esb

lingfeng 9 年之前
父节点
当前提交
fd12be6386
共有 100 个文件被更改,包括 13526 次插入1 次删除
  1. 1 1
      Hos-Resource-Rest/pom.xml
  2. 132 0
      Hos-Resource-WS/Hos-Resource-WS.iml
  3. 331 0
      Hos-Resource-WS/pom.xml
  4. 81 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/ApplicationStart.java
  5. 84 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/CheckLoginFilter.java
  6. 59 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/CommonPageController.java
  7. 87 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/ThreadStart.java
  8. 160 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/config/SysConfig.java
  9. 10 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/config/ThreadConfig.java
  10. 92 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/constants/Constants.java
  11. 9 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/constants/DictDataType.java
  12. 12 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/constants/LogicValues.java
  13. 45 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/constants/MetaDataType.java
  14. 21 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/common/constants/TransformType.java
  15. 21 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/config/ThreadConfig.java
  16. 182 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/controller/DatacollectController.java
  17. 208 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/controller/SystemController.java
  18. 26 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/framework/model/ActionResult.java
  19. 125 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/framework/model/DataGridResult.java
  20. 37 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/framework/model/DictItem.java
  21. 39 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/framework/model/DictionaryResult.java
  22. 56 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/framework/model/Result.java
  23. 100 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/framework/model/SimpleChartItem.java
  24. 65 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/framework/model/TreeResult.java
  25. 35 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/DataSource.java
  26. 103 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/Patient.java
  27. 59 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/PatientIdentity.java
  28. 44 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/SystemParams.java
  29. 45 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/UserInfo.java
  30. 15 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/BaseEntity.java
  31. 157 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDataSet.java
  32. 82 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDataSetT.java
  33. 56 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDict.java
  34. 18 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictItem.java
  35. 93 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictItemT.java
  36. 90 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterDictT.java
  37. 102 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterMetaData.java
  38. 96 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/adapter/AdapterMetaDataT.java
  39. 100 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/origin/OrgDataSetT.java
  40. 54 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/origin/OrgDictItemT.java
  41. 45 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/origin/OrgDictT.java
  42. 145 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/origin/OrgMetaDataT.java
  43. 177 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/standard/StdDataSetT.java
  44. 100 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/standard/StdDictItemT.java
  45. 92 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/standard/StdDictT.java
  46. 93 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/standard/StdInnerVersionT.java
  47. 206 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/standard/StdMetaDataT.java
  48. 20 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/standard/StdVersion.java
  49. 93 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/entity/standard/StdVersionT.java
  50. 29 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/verify/AuthorizationVeryify.java
  51. 15 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/verify/IVerifier.java
  52. 37 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/verify/MetaDataVerify.java
  53. 29 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/model/verify/RegistrationVerify.java
  54. 140 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/DatacollectManager.java
  55. 312 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/SystemManager.java
  56. 227 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/crawler/CrawlerManager.java
  57. 254 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/crawler/DBOrigin.java
  58. 213 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/crawler/DataCollectDispatcher.java
  59. 172 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/crawler/DataSetTransformer.java
  60. 65 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/crawler/OriginDateTimeManager.java
  61. 25 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/intf/IDatacollectManager.java
  62. 27 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/intf/ISystemManager.java
  63. 83 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/patient/PatientCDAIndex.java
  64. 111 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/patient/PatientCDAUpload.java
  65. 326 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/standard/StandardManager.java
  66. 189 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/standard/StandardService.java
  67. 40 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/thread/CrawlerSupplyThread.java
  68. 50 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/thread/CrawlerThread.java
  69. 53 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/thread/StandardUpdateThread.java
  70. 65 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/service/thread/ThreadManage.java
  71. 140 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/compress/ZipUtil.java
  72. 173 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/compress/Zipper.java
  73. 138 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/db/BeanProcessorEx.java
  74. 387 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/db/DBSessionFactory.java
  75. 63 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/db/DataSourcePool.java
  76. 77 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/db/JsonHandler.java
  77. 18 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/db/SystemDataTime.java
  78. 129 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/encode/Base64.java
  79. 29 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/encode/HexEncode.java
  80. 106 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/encode/UnicodeReader.java
  81. 35 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/encrypt/DES.java
  82. 75 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/encrypt/MD5.java
  83. 110 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/encrypt/RSA.java
  84. 247 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/file/FileUtil.java
  85. 338 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/httpclient/EsbHttp.java
  86. 311 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/httpclient/HttpClientUtil.java
  87. 246 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/httpclient/HttpHelper.java
  88. 36 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/httpclient/Response.java
  89. 50 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/log/LogUtil.java
  90. 47 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/BeanUtil.java
  91. 18 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/CollectionUtil.java
  92. 38 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/ConfigureUtil.java
  93. 1492 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/DateUtil.java
  94. 89 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/ListSortUtil.java
  95. 636 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/NumberUtil.java
  96. 29 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/Select2.java
  97. 388 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/SqlCreate.java
  98. 1428 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/StringUtil.java
  99. 88 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/TokenUtil.java
  100. 0 0
      Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/TreeNode.java

+ 1 - 1
Hos-Resource-Rest/pom.xml

@ -135,7 +135,7 @@
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>ehr-dbhelper</artifactId>
            <version>1.1.7</version>
            <version>1.1.8</version>
        </dependency>
        <!--=============httpclient start=============-->
        <dependency>

+ 132 - 0
Hos-Resource-WS/Hos-Resource-WS.iml

@ -0,0 +1,132 @@
<?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.8" 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" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-frontend-jaxws:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: xml-resolver:xml-resolver:1.2" level="project" />
    <orderEntry type="library" name="Maven: asm:asm:3.3.1" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-core:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: org.codehaus.woodstox:woodstox-core-asl:4.3.0" level="project" />
    <orderEntry type="library" name="Maven: org.codehaus.woodstox:stax2-api:3.1.4" level="project" />
    <orderEntry type="library" name="Maven: org.apache.ws.xmlschema:xmlschema-core:2.1.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-bindings-soap:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-wsdl:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: wsdl4j:wsdl4j:1.6.3" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-databinding-jaxb:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-impl:2.2.7" level="project" />
    <orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-core:2.2.7" level="project" />
    <orderEntry type="library" name="Maven: com.sun.istack:istack-commons-runtime:2.16" level="project" />
    <orderEntry type="library" name="Maven: com.sun.xml.fastinfoset:FastInfoset:1.2.12" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-bindings-xml:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-frontend-simple:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-ws-addr:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-ws-policy:3.0.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.neethi:neethi:3.0.3" level="project" />
    <orderEntry type="library" name="Maven: org.apache.cxf:cxf-rt-transports-http:3.0.0" level="project" />
  </component>
</module>

+ 331 - 0
Hos-Resource-WS/pom.xml

@ -0,0 +1,331 @@
<?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-WS</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <aspectj.version>1.8.7</aspectj.version>
        <jackson.version>2.4.6</jackson.version>
        <spring.version>4.1.8.RELEASE</spring.version>
    </properties>
    <pluginRepositories>
        <pluginRepository>
            <id>pluginCentral</id>
            <name>pluginCentral</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/central/</url>
        </pluginRepository>
        <pluginRepository>
            <id>pluginReleases</id>
            <name>pluginReleases</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/releases/</url>
        </pluginRepository>
    </pluginRepositories>
    <!--用于发布到服务器 对应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>
    <repositories>
        <repository>
            <id>repositoryCentral</id>
            <name>repositoryCentral</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/central/</url>
        </repository>
        <repository>
            <id>repositoryReleases</id>
            <name>repositoryReleases</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/releases/</url>
        </repository>
    </repositories>
    <dependencies>
        <!--=============数据库驱动 start =============-->
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>ehr-dbhelper</artifactId>
            <version>1.1.8</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>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.0.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>

+ 81 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/common/ApplicationStart.java

@ -0,0 +1,81 @@
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();
    @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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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";
}

+ 182 - 0
Hos-Resource-WS/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());
        }
    }
}

文件差异内容过多而无法显示
+ 208 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/controller/SystemController.java


+ 26 - 0
Hos-Resource-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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;
    }
}

+ 35 - 0
Hos-Resource-WS/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-WS/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-WS/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;
    }
}

+ 44 - 0
Hos-Resource-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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

+ 140 - 0
Hos-Resource-WS/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);
        }
    }
}

+ 312 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/service/SystemManager.java

@ -0,0 +1,312 @@
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 com.yihu.ehr.ws.SQLWebService;
import org.apache.commons.dbcp2.BasicDataSource;
import org.json.JSONObject;
import org.springframework.jdbc.core.JdbcTemplate;
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)) {
            //更新数据源//jdbc:oracle:thin:hos/hos@//172.19.103.71:1521/orcl
            //jdbc:mysql://172.19.103.71:1521/orcl?user=hos&password=hos&useUnicode=true&characterEncoding=UTF-8
            //jdbc:sqlserver://172.19.103.71:1521/orcl?user=hos&password=hos
            BasicDataSource dasicDataSource = new BasicDataSource();
            if (config.contains("oracle")) {
                //oracle数据库
                dasicDataSource.setUrl(config);
                dasicDataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
                String[] s1 = config.split("@");
                String[] s2 = s1[0].split(":");
                String[] s3 = s2[3].split("/");
                dasicDataSource.setUsername(s3[0]);
                dasicDataSource.setPassword(s3[1]);
                System.out.println(config);
                System.out.println("username:" + s3[0]);
                System.out.println("password:" + s3[1]);
            } else if (config.contains("mysql")) {
                //mysql数据库
                dasicDataSource.setUrl(config);
                dasicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
                String[] s1 = config.split("\\?");
                String[] s2 = s1[1].split("&");
                dasicDataSource.setUsername(s2[0].split("=")[1]);
                dasicDataSource.setPassword(s2[1].split("=")[1]);
                System.out.println(config);
                System.out.println("username:" + s2[0].split("=")[1]);
                System.out.println("password:" + s2[1].split("=")[1]);
            } else if (config.contains("sqlserver")) {
                //sqlserver数据库
                dasicDataSource.setUrl(config);
                dasicDataSource.setDriverClassName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                String[] s1 = config.split("\\?");
                String[] s2 = s1[1].split("&");
                dasicDataSource.setUsername(s2[0].split("=")[1]);
                dasicDataSource.setPassword(s2[1].split("=")[1]);
                System.out.println(config);
                System.out.println("username:" + s2[0].split("=")[1]);
                System.out.println("password:" + s2[1].split("=")[1]);
            }
            SQLWebService.jdbcTemplate = new JdbcTemplate();
            SQLWebService.jdbcTemplate.setDataSource(dasicDataSource);
            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-WS/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-WS/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-WS/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-WS/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-WS/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);
    }
}

+ 25 - 0
Hos-Resource-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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-WS/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;
        }
    }
}

+ 311 - 0
Hos-Resource-WS/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-WS/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,
                        null);
            }
        }
        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-WS/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;
    }
}

+ 50 - 0
Hos-Resource-WS/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-WS/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-WS/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-WS/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;
    }
}

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

@ -0,0 +1,1492 @@
/****************************************************************************
 * Copyright(c) Yamaha Motor Solutions CO.,Ltd. 2010 All Rights Reserved
 * <p>
 * System Name:(smart)Human Resource Management System
 * SubSystem Name:-
 * service for all substystems
 * <p>
 * File Name: DateUtil
 * <p>
 * HISTORY RECORD
 * Ver.   Date           Create User/Update     Comment
 * -------------------------------------------------------------------------
 * 1.0    2010/07/12    tuchengye              New Making
 ***************************************************************************/
package com.yihu.ehr.util.operator;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
public class DateUtil {
    public static final String DEFAULT_DATE_YEAR_FORMAT = "yyyy";
    public static final String DEFAULT_DATE_MONTH_FORMAT = "MM";
    public static final String PRINT_DATE_YM_FORMAT = "MMM., yyyy";
    public static final String PRINT_DATE_YMD_FORMAT = "MMM. d, yyyy";
    public static final Locale PRINT_LOCALE = Locale.ENGLISH;
    public static final String DEFAULT_YEARS = "0.0";
    public static final String DEFAULT_DATE_YMD_FORMAT = "yyyy-MM-dd";
    public static final String DEFAULT_DATE_YM_FORMAT = "yyyyMM";
    public static final String DEFAULT_DATE_MD_FORMAT = "MMdd";
    public static final String DEFAULT_CHAR_DATE_YMD_FORMAT = "yyyyMMdd";
    public static final String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
    public final static String DEFAULT_SIMPLEDATE_FORMAT = "yyyy-MM-dd HH:mm:ss SSS";
    public final static String DEFAULT_YMDHMSDATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    public static final String DEFAULT_NOW_STRING_FORMAT = "yyyyMMddHHmmssSSS";
    public static final String DATE_MDY_FORMAT = "MMddyyyy";
    public static final String DATE_MY_FORMAT = "MMyyyy";
    public static String changeFormat(String changeDate, String beforeFormat, String afterFormat) {
        if (StringUtil.isBlank(changeDate)) {
            return changeDate;
        }
        return formatDate(parseDate(changeDate, beforeFormat), afterFormat);
    }
    public static String changeToYMDFormatForPrint(String changeDate) {
        if (StringUtil.isBlank(changeDate)) {
            return "";
        }
        DateFormat df = new SimpleDateFormat(PRINT_DATE_YMD_FORMAT, Locale.ENGLISH);
        return df.format(parseDate(changeDate, DEFAULT_CHAR_DATE_YMD_FORMAT));
    }
    public static String changeToYMFormatForPrint(String changeDate) {
        if (StringUtil.isBlank(changeDate)) {
            return "";
        }
        DateFormat df = new SimpleDateFormat(PRINT_DATE_YM_FORMAT, Locale.ENGLISH);
        return df.format(parseDate(changeDate, DEFAULT_DATE_YM_FORMAT));
    }
    public static String getFirstDate(String yearMonthStr, String yearMonthFormat, String dateFormat) throws Exception {
        DateFormat dfYearMonth = new SimpleDateFormat(yearMonthFormat);
        DateFormat dfDate = new SimpleDateFormat(dateFormat);
        java.util.Date date;
        if (yearMonthStr == null || yearMonthStr.equals("")) {
            throw new Exception(yearMonthStr + " is invalid.");
        }
        try {
            date = dfYearMonth.parse(yearMonthStr);
        } catch (ParseException e) {
            throw new Exception(yearMonthStr + " is invalid.");
        }
        return dfDate.format(date);
    }
    public static String getLastDate(String dateSource, String dateSourceFormat, String dateFormat) throws Exception {
        DateFormat dsf = new SimpleDateFormat(dateSourceFormat);
        DateFormat df = new SimpleDateFormat(dateFormat);
        java.util.Date date;
        String resultDateString;
        if (dateSource == null || dateSource.equals("")) {
            throw new Exception(dateSource + " is invalid.");
        }
        try {
            date = dsf.parse(dateSource);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            resultDateString = df.format(cal.getTime());
        } catch (ParseException e) {
            throw new Exception(dateSource + " is invalid.");
        }
        return resultDateString;
    }
    public static String getYearFromDBDate(String dateStr) {
        if (dateStr == null || dateStr.length() != DEFAULT_CHAR_DATE_YMD_FORMAT.length()) {
            return null;
        }
        return changeFormat(dateStr, DEFAULT_CHAR_DATE_YMD_FORMAT, DEFAULT_DATE_YEAR_FORMAT);
    }
    public static String getMonthFromDBDate(String dateStr) {
        if (dateStr == null || dateStr.length() != DEFAULT_CHAR_DATE_YMD_FORMAT.length()) {
            return null;
        }
        return changeFormat(dateStr, DEFAULT_CHAR_DATE_YMD_FORMAT, DEFAULT_DATE_MONTH_FORMAT);
    }
    public static String getYMFromDBDate(String dateStr) {
        if (dateStr == null || dateStr.length() != DEFAULT_CHAR_DATE_YMD_FORMAT.length()) {
            return null;
        }
        return changeFormat(dateStr, DEFAULT_CHAR_DATE_YMD_FORMAT, DEFAULT_DATE_YM_FORMAT);
    }
    public static int getDifferenceOfDays(java.util.Date dateFrom, java.util.Date dateTo) {
        return new Long((dateTo.getTime() - dateFrom.getTime()) / 1000 / 60 / 60 / 24).intValue();
    }
    public static int getDifferenceOfDays(String dateFromStr, String dateToStr, String dateFormat) {
        java.util.Date dateFrom = parseDate(dateFromStr, dateFormat);
        java.util.Date dateTo = parseDate(dateToStr, dateFormat);
        return getDifferenceOfDays(dateFrom, dateTo);
    }
    public static int getDifferenceOfDays(String dateFromStr, String dateToStr) {
        return getDifferenceOfDays(dateFromStr, dateToStr, DEFAULT_CHAR_DATE_YMD_FORMAT);
    }
    public static String formatTime(String timeStr) {
        if (timeStr == null || timeStr.length() != 6) {
            return null;
        }
        return StringUtil.substring(timeStr, 0, 2)
                + ":" + StringUtil.substring(timeStr, 2, 4)
                + ":" + StringUtil.substring(timeStr, 4);
    }
    public static String toString(Date date) {
        return toString((java.util.Date) date);
    }
    public static String toString(java.util.Date date) {
        return toString(date, DEFAULT_DATE_YMD_FORMAT);
    }
    public static String toString(Date date, String format) {
        return toString((java.util.Date) date, format);
    }
    public static String toString(java.util.Date date, String format) {
        if (date == null) {
            return null;
        }
        if (format == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }
    public static String formatTimestamp(Timestamp time) {
        return formatTimestamp(time, DEFAULT_TIMESTAMP_FORMAT);
    }
    public static String formatTimestamp(Timestamp time, String format) {
        if (time == null) {
            return null;
        }
        if (format == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(time);
    }
    public static String toString(Time time, String format) {
        if (time == null) {
            return null;
        }
        if (format == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(time);
    }
    public static Date formatCharDateYMD(String str) {
        return formatCharDateYMD(str, DEFAULT_DATE_YMD_FORMAT);
    }
    public static Date formatCharDateYMD(String str, String format) {
        if (str == null || str.trim().length() == 0) {
            return null;
        }
        if (format == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        ParsePosition pos = new ParsePosition(0);
        java.util.Date date = sdf.parse(str, pos);
        if (date == null) {
            return null;
        }
        return new Date(date.getTime());
    }
    public static Date formatCharDateYMD(String yy, String mm, String dd) {
        if (yy == null || mm == null || dd == null || yy.trim().length() == 0 ||
                mm.trim().length() == 0 || dd.trim().length() == 0) {
            return null;
        }
        return formatCharDateYMD(yy + "-" + (mm != null && mm.length() == 1 ? "0" + mm : mm) + "-" +
                (dd != null && dd.length() == 1 ? "0" + dd : dd));
    }
    public static Timestamp toTimestamp(String str) {
        if (str == null) {
            return null;
        }
        try {
            return Timestamp.valueOf(str.trim());
        } catch (IllegalArgumentException iae) {
            return null;
        }
    }
    public static Timestamp toTimestamp(String str, String format) {
        if (str == null) {
            return null;
        }
        try {
            return new Timestamp(parseDate(str, format).getTime());
        } catch (Exception e) {
            return null;
        }
    }
    public static Time toTime(String str) {
        if (str == null) {
            return null;
        }
        try {
            return (str.length() == 5 ? Time.valueOf(str + ":00") : Time.valueOf(str));
        } catch (Exception e) {
            return null;
        }
    }
    public static String toString(Time time) {
        return toString(time, DEFAULT_TIME_FORMAT);
    }
    public static String toYM(String yy, String mm) {
        if (yy == null || mm == null) {
            return null;
        }
        if (yy.trim().length() == 0 && mm.trim().length() != 0 ||
                yy.trim().length() != 0 && mm.trim().length() == 0) {
            return null;
        }
        return yy + (mm != null && mm.length() == 1 ? "0" + mm : mm);
    }
    public static String getNowDate() {
        return getNowDate(DEFAULT_NOW_STRING_FORMAT);
    }
    public static String getNowDate(String format) {
        if (format == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.JAPAN);
        java.util.Date date = Calendar.getInstance().getTime();
        if (date == null) {
            return null;
        }
        return sdf.format(date);
    }
    public static Date getSysDate() {
        return new Date(Calendar.getInstance().getTime().getTime());
    }
    public static java.util.Date getSysDateYMDHMS() {
        Date dSysDateYMD = DateUtil.getSysDate();
        Timestamp ts = formatYMDToYMDHMS(StringUtil.toString(dSysDateYMD));
        return ts;
    }
    public static Timestamp getSysDateTime() {
        return new Timestamp(Calendar.getInstance().getTime().getTime());
    }
    public static Time getSysTime() {
        return new Time(Calendar.getInstance().getTime().getTime());
    }
    public static String toAge(String birthDay) {
        if (birthDay == null || birthDay.length() != 8) {
            return null;
        }
        int birthYear = Integer.parseInt(birthDay.substring(0, 4));
        int birthMonth = Integer.parseInt(birthDay.substring(4, 6));
        int birthDayOfMonth = Integer.parseInt(birthDay.substring(6, 8));
        return toAge(birthYear, birthMonth, birthDayOfMonth);
    }
    public static String toAge(int birthYear, int birthMonth, int birthDayOfMonth) {
        Calendar cl = Calendar.getInstance();
        int year = cl.get(Calendar.YEAR);
        int month = cl.get(Calendar.MONTH) + 1;
        int day = cl.get(Calendar.DAY_OF_MONTH);
        int sa = 0;
        if (month > birthMonth) {
            sa = 0;
        } else if (month == birthMonth && day >= birthDayOfMonth) {
            sa = 0;
        } else {
            sa = 1;
        }
        int age = year - birthYear - sa;
        return Integer.toString(age);
    }
    public static Date addDate(int add, java.util.Date d) {
        return addDate(add, new Date(d.getTime()));
    }
    public static java.util.Date addDateTime(int add, java.util.Date d) {
        return addDateTime(add, new Date(d.getTime()));
    }
    public static Date addDate(int add, Date d) {
        if (d == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime((java.util.Date) d);
        cal.setTimeZone(TimeZone.getDefault());
        cal.add(Calendar.DAY_OF_MONTH, add);
        return new Date(cal.getTime().getTime());
    }
    public static java.util.Date addDateTime(int add, Date d) {
        if (d == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime((java.util.Date) d);
        cal.setTimeZone(TimeZone.getDefault());
        cal.add(Calendar.DAY_OF_MONTH, add);
        return cal.getTime();
    }
    public static String addDate(int add, String sDate) {
        if (sDate.length() < 8) {
            return null;
        }
        return formatDate(addDate(add, formatCharDateYMD(sDate, DEFAULT_CHAR_DATE_YMD_FORMAT)), DEFAULT_CHAR_DATE_YMD_FORMAT);
    }
    public static Date addMonth(int add, java.util.Date d) {
        return addMonth(add, new Date(d.getTime()));
    }
    public static Date addMonth(int add, Date d) {
        if (d == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime((java.util.Date) d);
        cal.setTimeZone(TimeZone.getDefault());
        cal.add(Calendar.MONTH, add);
        return new Date(cal.getTime().getTime());
    }
    public static String addMonth(int add, String sDate) {
        if (sDate.length() < 8) {
            return null;
        }
        return formatDate(addMonth(add, formatCharDateYMD(sDate, DEFAULT_CHAR_DATE_YMD_FORMAT)), DEFAULT_CHAR_DATE_YMD_FORMAT);
    }
    public static Date addYear(int add, java.util.Date d) {
        return addYear(add, new Date(d.getTime()));
    }
    public static Date addYear(int add, Date d) {
        if (d == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime((java.util.Date) d);
        cal.setTimeZone(TimeZone.getDefault());
        cal.add(Calendar.YEAR, add);
        return new Date(cal.getTime().getTime());
    }
    public static String addYear(int add, String sDate) {
        if (sDate.length() < 8) {
            return null;
        }
        return formatDate(addYear(add, formatCharDateYMD(sDate, DEFAULT_CHAR_DATE_YMD_FORMAT)), DEFAULT_CHAR_DATE_YMD_FORMAT);
    }
    public static String getNowDateTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss", Locale.JAPAN);
        df.setTimeZone(TimeZone.getDefault());
        return df.format(new java.util.Date());
    }
    public static String getCurrentString() {
        return getCurrentString(DEFAULT_SIMPLEDATE_FORMAT);
    }
    public static String getCurrentString(String pattern) {
        SimpleDateFormat f = new SimpleDateFormat(pattern);
        return f.format(Calendar.getInstance(TimeZone.getDefault()).getTime());
    }
    public static long compareDate(String pattern, String s1, String s2) {
        SimpleDateFormat f = new SimpleDateFormat(pattern);
        try {
            return f.parse(s1).getTime() - f.parse(s2).getTime();
        } catch (Exception e) {
            return -1;
        }
    }
    public static long compareDate(java.util.Date s1, java.util.Date s2) {
        try {
            return compareDate(DEFAULT_DATE_YMD_FORMAT, toString(s1), toString(s2));
        } catch (Exception e) {
            return -1;
        }
    }
    public static long compareDateTime(java.util.Date s1, java.util.Date s2) {
        return s1.getTime() - s2.getTime();
    }
    public static java.util.Date parseDate(String value, String pattern) {
        try {
            TimeZone tz = TimeZone.getDefault();
            String dateFormat = pattern;
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            sdf.setTimeZone(tz);
            // Parse date
            java.util.Date parsed = null;
            parsed = sdf.parse(value);
            return parsed;
        } catch (ParseException e) {
            return null;
        }
    }
    public static String formatDate(java.util.Date value, String pattern) {
        TimeZone tz = TimeZone.getDefault();
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setTimeZone(tz);
        return sdf.format(value);
    }
    public static int getLastDay(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        return lastDay;
    }
    public static String getYMDFormat(String datePtn) {
        final String[][] DATE_FORMAT_YMD_LIST = {{"1", "yyyy/MM/dd"},
                {"2", "yyyy.MM.dd"},
                {"3", "yyyy-MM-dd"},
                {"4", "MM/dd/yyyy"},
                {"5", "MM.dd.yyyy"},
                {"6", "MM-dd-yyyy"},
                {"7", "dd/MM/yyyy"},
                {"8", "dd.MM.yyyy"},
                {"9", "dd-MM-yyyy"},
                {"A", "dd/MM yyyy"}
        };
        String format = null;
        for (int i = 0; i < DATE_FORMAT_YMD_LIST.length; i++) {
            if (DATE_FORMAT_YMD_LIST[i][0].equals(datePtn)) {
                format = DATE_FORMAT_YMD_LIST[i][1];
                break;
            }
        }
        if (format == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        return format;
    }
    public static String getYMFormat(String datePtn) {
        final String[][] DATE_FORMAT_YM_LIST = {{"1", "yyyy/MM"},
                {"2", "yyyy.MM"},
                {"3", "yyyy-MM"},
                {"4", "MM/yyyy"},
                {"5", "MM.yyyy"},
                {"6", "MM-yyyy"},
                {"7", "MM/yyyy"},
                {"8", "MM.yyyy"},
                {"9", "MM-yyyy"},
                {"A", "MM yyyy"},
                {"B", "yyyyMM"}
        };
        String format = null;
        for (int i = 0; i < DATE_FORMAT_YM_LIST.length; i++) {
            if (DATE_FORMAT_YM_LIST[i][0].equals(datePtn)) {
                format = DATE_FORMAT_YM_LIST[i][1];
                break;
            }
        }
        if (format == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        return format;
    }
    public static String toYMD(Date date, String datePtn) {
        if (date == null) {
            return null;
        }
        return toString(date, getYMDFormat(datePtn));
    }
    public static String formatDateYMD(String str, String datePtn) {
        if (str == null || str.trim().length() == 0) {
            return null;
        }
        return toYMD(formatCharDateYMD(str), datePtn);
    }
    public static String formatDateYMD(String yy, String mm, String dd, String datePtn) {
        if (yy == null || mm == null || dd == null || yy.trim().length() == 0
                || mm.trim().length() == 0 || dd.trim().length() == 0) {
            return null;
        }
        return formatDateYMD(yy + "-" + (mm != null && mm.length() == 1 ? "0" + mm : mm)
                + "-" + (dd != null && dd.length() == 1 ? "0" + dd : dd), datePtn);
    }
    public static String formatDateYM(Date date, String datePtn) {
        if (date == null) {
            return null;
        }
        return toString(date, getYMFormat(datePtn));
    }
    public static String formatDateYM(String str, String datePtn) {
        if (str == null || str.trim().length() == 0) {
            return null;
        }
        return formatDateYM(formatCharDateYMD(str, DEFAULT_DATE_YM_FORMAT), datePtn);
    }
    public static String formatDateYM(String yy, String mm, String datePtn) {
        if (yy == null || mm == null || yy.trim().length() == 0 || mm.trim().length() == 0) {
            return null;
        }
        return formatDateYM(yy + (mm != null && mm.length() == 1 ? "0" + mm : mm), datePtn);
    }
    public static String getTimestampFormat(String dateStyleId) {
        return getYMDFormat(dateStyleId) + " HH:mm:ss";
    }
    public static Date toDateFromTime(String time) {
        try {
            return toDateFromTime(Long.parseLong(time));
        } catch (Exception iae) {
            return null;
        }
    }
    public static Date toDateFromTime(long time) {
        return new Date(time);
    }
    public static Timestamp toTimestampFromTime(String time) {
        try {
            return toTimestampFromTime(Long.parseLong(time));
        } catch (Exception iae) {
            return null;
        }
    }
    public static Timestamp toTimestampFromTime(long time) {
        return new Timestamp(time);
    }
    public static Timestamp toTimestampFromGMT(int yy, int mm, int dd, int hh, int mi, int ss) {
        return toTimestampFromGMT(
                String.valueOf(yy),
                String.valueOf(mm),
                String.valueOf(dd),
                String.valueOf(hh),
                String.valueOf(mi),
                String.valueOf(ss));
    }
    public static Timestamp toTimestampFromGMT(String yy, String mm, String dd,
                                               String hh, String mi, String ss) {
        mm = mm != null && mm.length() == 1 ? "0" + mm : mm;
        dd = dd != null && dd.length() == 1 ? "0" + dd : dd;
        hh = hh != null && hh.length() == 1 ? "0" + hh : hh;
        mi = mi != null && mi.length() == 1 ? "0" + mi : mi;
        ss = ss != null && ss.length() == 1 ? "0" + ss : ss;
        return toTimestampFromGMT(yy + "-" + mm + "-" + dd + " " + hh + ":" + mi + ":" + ss);
    }
    public static Timestamp toTimestampFromGMT(String str) {
        if (str == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_TIMESTAMP_FORMAT);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        ParsePosition pos = new ParsePosition(0);
        java.util.Date date = sdf.parse(str, pos);
        if (date == null) {
            return null;
        }
        return new Timestamp(date.getTime());
    }
    public static Timestamp toTimestampFromGMT(Timestamp time) {
        return toTimestampFromGMT(StringUtil.toString(time));
    }
    public static Timestamp toTimestampFromLocal(String yy, String mm, String dd, String hh,
                                                 String mi, String ss, String differTimeSign,
                                                 String differenceTime, String summerTimeFrom,
                                                 String summerTimeTo, String summerTime) {
        mm = mm != null && mm.length() == 1 ? "0" + mm : mm;
        dd = dd != null && dd.length() == 1 ? "0" + dd : dd;
        hh = hh != null && hh.length() == 1 ? "0" + hh : hh;
        mi = mi != null && mi.length() == 1 ? "0" + mi : mi;
        ss = ss != null && ss.length() == 1 ? "0" + ss : ss;
        return toTimestampFromLocal(
                yy + "-" + mm + "-" + dd + " " + hh + ":" + mi + ":" + ss,
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime);
    }
    public static Timestamp toTimestampFromLocal(String str, String differTimeSign,
                                                 String differenceTime, String summerTimeFrom,
                                                 String summerTimeTo, String summerTime) {
        if (str == null) {
            return null;
        }
        Timestamp time = toTimestamp(str);
        if (time == null) {
            return null;
        }
        long localTime = toGMTTimeFromLocalTime(
                time.getTime(),
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime);
        return toTimestampFromGMT(new Timestamp(localTime));
    }
    public static Timestamp toTimestampFromLocal(Timestamp time, String differTimeSign,
                                                 String differenceTime, String summerTimeFrom,
                                                 String summerTimeTo, String summerTime) {
        return toTimestampFromLocal(
                StringUtil.toString(time),
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime);
    }
    public static long toGMTTime(long local) {
        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_TIMESTAMP_FORMAT);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        ParsePosition pos = new ParsePosition(0);
        java.util.Date date = sdf.parse(StringUtil.toString(new Timestamp(local)), pos);
        if (date == null) {
            return -1;
        }
        return date.getTime();
    }
    public static long toGMTTime(Timestamp local) {
        if (local == null) {
            return -1;
        }
        return toGMTTime(local.getTime());
    }
    public static Timestamp toGMTTimestamp(long local) {
        long time = toGMTTime(local);
        if (time == -1) {
            return null;
        }
        return new Timestamp(time);
    }
    public static Timestamp toGMTTimestamp(Timestamp local) {
        if (local == null) {
            return null;
        }
        return toGMTTimestamp(local.getTime());
    }
    public static String toYMD(String yy, String mm, String dd) {
        if (yy == null || mm == null || dd == null) {
            return null;
        }
        if (yy.trim().length() == 0 || mm.trim().length() == 0) {
            return "";
        }
        mm = mm != null && mm.length() == 1 ? "0" + mm : mm;
        if (dd != null && dd.length() == 0) {
            dd = "  ";
        }
        if (dd != null && dd.length() == 1) {
            dd = "0" + dd;
        }
        return yy + mm + dd;
    }
    public static String getYearFromYM(String ym) {
        if (ym == null || ym.length() != DEFAULT_DATE_YM_FORMAT.length()) {
            return null;
        }
        return ym.substring(0, 4);
    }
    public static String getMonthFromYM(String ym) {
        if (ym == null || ym.length() != DEFAULT_DATE_YM_FORMAT.length()) {
            return null;
        }
        return ym.substring(4, 6);
    }
    public static String getYearFromYMD(Date ymd) {
        return getYearFromYMD(toString(ymd));
    }
    public static String getMonthFromYMD(Date ymd) {
        return getMonthFromYMD(toString(ymd));
    }
    public static String getDateFromYMD(Date ymd) {
        return getDateFromYMD(toString(ymd));
    }
    public static String getYearFromYMD(String ymd) {
        if (ymd == null || ymd.length() != DEFAULT_DATE_YMD_FORMAT.length()) {
            return null;
        }
        return ymd.substring(0, 4);
    }
    public static String getMonthFromYMD(String ymd) {
        if (ymd == null || ymd.length() != DEFAULT_DATE_YMD_FORMAT.length()) {
            return null;
        }
        return ymd.substring(5, 7);
    }
    public static String getDateFromYMD(String ymd) {
        if (ymd == null || ymd.length() != DEFAULT_DATE_YMD_FORMAT.length()) {
            return null;
        }
        return ymd.substring(8, 10);
    }
    public static String getHourFromHMS(String hms) {
        if (hms == null || hms.length() != DEFAULT_TIME_FORMAT.length()) {
            return null;
        }
        return hms.substring(0, 2);
    }
    public static String getMinuteFromHMS(String hms) {
        if (hms == null || hms.length() != DEFAULT_TIME_FORMAT.length()) {
            return null;
        }
        return hms.substring(3, 5);
    }
    public static String getSecondFromHMS(String hms) {
        if (hms == null || hms.length() != DEFAULT_TIME_FORMAT.length()) {
            return null;
        }
        return hms.substring(6, 8);
    }
    public static String formatDateYMD(Date date, String dateStyleId) {
        if (date == null) {
            return null;
        }
        return toString(date, getYMDFormat(dateStyleId));
    }
    public static long getSystemTime() {
        return Calendar.getInstance().getTime().getTime();
    }
    public static Timestamp getSystemTimestamp() {
        return new Timestamp(getSystemTime());
    }
    public static long getSystemTimeGMTToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        Timestamp today = toTimestamp(sdf.format(Calendar.getInstance().getTime()) + " 00:00:00");
        return toGMTTime(today);
    }
    public static Timestamp getSystemTimestampGMTToday() {
        long time = getSystemTimeGMTToday();
        if (time == -1) {
            return null;
        }
        return new Timestamp(time);
    }
    public static Date getSysDateGMTToday() {
        long time = getSystemTimeGMTToday();
        if (time == -1) {
            return null;
        }
        return new Date(getSystemTimeGMTToday());
    }
    public static String formatTimestamp(Timestamp time, String differTimeSign,
                                         String differenceTime, String summerTimeFrom,
                                         String summerTimeTo, String summerTime) {
        if (time == null) {
            return null;
        }
        return toStringFormatLocalTime(
                time.getTime(),
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime,
                DEFAULT_TIMESTAMP_FORMAT);
    }
    public static String formatTimestamp(Timestamp time, String differTimeSign,
                                         String differenceTime, String summerTimeFrom,
                                         String summerTimeTo, String summerTime, String dateStyleId) {
        if (time == null) {
            return null;
        }
        return toStringFormatLocalTime(
                time.getTime(),
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime,
                getTimestampFormat(dateStyleId));
    }
    public static String formatTimestamp(long time, String differTimeSign, String differenceTime,
                                         String summerTimeFrom, String summerTimeTo, String summerTime) {
        return toStringFormatLocalTime(
                time,
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime,
                DEFAULT_TIMESTAMP_FORMAT);
    }
    public static String formatTimestamp(long time, String differTimeSign, String differenceTime,
                                         String summerTimeFrom, String summerTimeTo,
                                         String summerTime, String dateStyleId) {
        return toStringFormatLocalTime(
                time,
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime,
                getTimestampFormat(dateStyleId));
    }
    public static String formatTimestampToDate(Timestamp time, String differTimeSign,
                                               String differenceTime, String summerTimeFrom,
                                               String summerTimeTo, String summerTime) {
        if (time == null) {
            return null;
        }
        return toStringFormatLocalTime(
                time.getTime(),
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime,
                DEFAULT_DATE_YMD_FORMAT);
    }
    public static String formatTimestampToDate(Timestamp time, String differTimeSign,
                                               String differenceTime, String summerTimeFrom,
                                               String summerTimeTo, String summerTime, String dateStyleId) {
        if (time == null) {
            return null;
        }
        return toStringFormatLocalTime(
                time.getTime(),
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime,
                getYMDFormat(dateStyleId));
    }
    public static String formatTimestampToDate(long time, String differTimeSign,
                                               String differenceTime, String summerTimeFrom,
                                               String summerTimeTo, String summerTime) {
        return toStringFormatLocalTime(
                time,
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime,
                DEFAULT_DATE_YMD_FORMAT);
    }
    public static String formatTimestampToDate(long time, String differTimeSign,
                                               String differenceTime, String summerTimeFrom,
                                               String summerTimeTo, String summerTime, String dateStyleId) {
        return toStringFormatLocalTime(
                time,
                differTimeSign,
                differenceTime,
                summerTimeFrom,
                summerTimeTo,
                summerTime,
                getYMDFormat(dateStyleId));
    }
    public static String toStringFormatLocalTime(long time, String differTimeSign,
                                                 String differenceTime, String summerTimeFrom,
                                                 String summerTimeTo, String summerTime, String format) {
        long localTime = time;
        long differenceTimeLong = toDifferenceTimeLong(differenceTime);
        long summerTimeLong = toSummerTimeLong(summerTime);
        if (differTimeSign != null && differTimeSign.equals("+")) {
            localTime += differenceTimeLong;
        } else {
            localTime -= differenceTimeLong;
        }
        if (isSummerTime(time, summerTimeFrom, summerTimeTo)) {
            localTime -= summerTimeLong;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(new java.util.Date(localTime));
    }
    public static long toGMTTimeFromLocalTime(long localTime, String differTimeSign,
                                              String differenceTime, String summerTimeFrom,
                                              String summerTimeTo, String summerTime) {
        long time = localTime;
        long differenceTimeLong = toDifferenceTimeLong(differenceTime);
        long summerTimeLong = toSummerTimeLong(summerTime);
        if (differTimeSign != null && differTimeSign.equals("+")) {
            time -= differenceTimeLong;
        } else {
            time += differenceTimeLong;
        }
        if (isSummerTime(localTime, summerTimeFrom, summerTimeTo)) {
            time += summerTimeLong;
        }
        return time;
    }
    public static long toDifferenceTimeLong(String differenceTime) {
        long differenceTimeLong;
        try {
            long differenceTimeM = Long.parseLong(differenceTime.substring(0, 2));
            long differenceTimeS = Long.parseLong(differenceTime.substring(2, 4));
            differenceTimeLong = (differenceTimeM * 60 * 60 * 1000) + (differenceTimeS * 60 * 1000);
        } catch (Exception e) {
            differenceTimeLong = 0;
        }
        return differenceTimeLong;
    }
    public static long toSummerTimeLong(String summerTime) {
        long summerTimeLong;
        try {
            long summerTimeM = Long.parseLong(summerTime.substring(0, 2));
            long summerTimeS = Long.parseLong(summerTime.substring(2, 4));
            summerTimeLong = (summerTimeM * 60 * 60 * 1000) + (summerTimeS * 60 * 1000);
        } catch (Exception e) {
            summerTimeLong = 0;
        }
        return summerTimeLong;
    }
    public static boolean isSummerTime(long time, String summerTimeFrom, String summerTimeTo) {
        if (summerTimeFrom == null || summerTimeFrom.trim().length() != 4 ||
                summerTimeTo == null || summerTimeTo.trim().length() != 4) {
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_MD_FORMAT);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String md = sdf.format(new java.util.Date(time));
        if (md.compareTo(summerTimeFrom) >= 0 && md.compareTo(summerTimeTo) <= 0) {
            // サマータイム
            return true;
        } else {
            return false;
        }
    }
    public static String formatGMTTimestamp(Timestamp time) {
        return toStringFormatGMTTime(time, DEFAULT_TIMESTAMP_FORMAT);
    }
    public static String formatGMTTimestamp(Timestamp time, String dateStyleId) {
        return toStringFormatGMTTime(time, getTimestampFormat(dateStyleId));
    }
    public static String formatGMTTimestamp(long time) {
        return toStringFormatGMTTime(time, DEFAULT_TIMESTAMP_FORMAT);
    }
    public static String formatGMTTimestamp(long time, String dateStyleId) {
        return toStringFormatGMTTime(time, getTimestampFormat(dateStyleId));
    }
    public static String formatGMTTimestampToDate(Timestamp time) {
        return toStringFormatGMTTime(time, DEFAULT_DATE_YMD_FORMAT);
    }
    public static String formatGMTTimestampToDate(Timestamp time, String dateStyleId) {
        return toStringFormatGMTTime(time, getYMDFormat(dateStyleId));
    }
    public static String formatGMTTimestampToDate(long time) {
        return toStringFormatGMTTime(time, DEFAULT_DATE_YMD_FORMAT);
    }
    public static String formatGMTTimestampToDate(long time, String dateStyleId) {
        return toStringFormatGMTTime(time, getYMDFormat(dateStyleId));
    }
    public static String toStringFormatGMTTime(Timestamp time, String format) {
        if (time == null) {
            return null;
        }
        return toStringFormatGMTTime(time.getTime(), format);
    }
    public static String toStringFormatGMTTime(long time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(new java.util.Date(time));
    }
    public static String toStringFormatTime(long time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new java.util.Date(time));
    }
    public static int getLastDay(int yy, int mm) {
        GregorianCalendar gc = new GregorianCalendar(yy, mm - 1, 1);
        return gc.getActualMaximum(GregorianCalendar.DATE);
    }
    public static String getLocalPattern(Locale locale) {
        SimpleDateFormat f = new SimpleDateFormat();
        f.setCalendar(Calendar.getInstance(locale));
        return f.toLocalizedPattern();
    }
    public static int getYears(java.util.Date date0, java.util.Date date1) {
        Calendar calendar0 = Calendar.getInstance();
        calendar0.setTime(date0);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        int year0 = calendar0.get(Calendar.YEAR);
        int year1 = calendar1.get(Calendar.YEAR);
        int years = year1 - year0;
        return years;
    }
    public static String getDifferenceOfYears(java.util.Date dateFrom, java.util.Date dateTo) {
        String years = DEFAULT_YEARS;
        if (dateFrom == null || dateTo == null) {
            years = DEFAULT_YEARS;
        } else {
            int days = getDifferenceOfDays(dateFrom, dateTo);
            DecimalFormat df = new DecimalFormat("#.0");
            years = df.format(days / 365.0);
        }
        return years;
    }
    public static Date formatCharDateYMDHMS(String str) {
        String format = DEFAULT_YMDHMSDATE_FORMAT;
        if (str == null || str.trim().length() == 0) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        ParsePosition pos = new ParsePosition(0);
        java.util.Date date = sdf.parse(str, pos);
        if (date == null) {
            return null;
        }
        return new Date(date.getTime());
    }
    public static Timestamp formatYMDToYMDHMS(String str) {
        String format = DEFAULT_YMDHMSDATE_FORMAT;
        if (str == null || str.trim().length() == 0) {
            return null;
        }
        str += " 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        ParsePosition pos = new ParsePosition(0);
        java.util.Date date = sdf.parse(str, pos);
        if (date == null) {
            return null;
        }
        Timestamp ts = DateUtil.fromatDateToTimestamp(new Date(date.getTime()));
        return ts;
    }
    public static Timestamp fromatDateToTimestamp(java.util.Date date) {
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        try {
            SimpleDateFormat df = new SimpleDateFormat(DEFAULT_YMDHMSDATE_FORMAT);
            String time = df.format(date);
            ts = Timestamp.valueOf(time);
        } catch (Exception e) {
            return null;
        }
        return ts;
    }
    /**
     * 获取标准时区偏移
     * @return
     */
    public static int geTimeZoneOffset(){
        int offset=0;
        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = cal.getTimeZone();
        offset=timeZone.getRawOffset()/(1000*60*60);
        return offset;
    }
    /**
     *  凌晨0点的时间
     * @param date  时间
     * @param days  正数为 days天后 ,负数为 days天前
     * @return
     */
    public static java.util.Date getTimesmorning(java.util.Date date,int days){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) +(days));
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return  cal.getTime();
    }
    /**
     *  晚上24点的时间
     * @param date  时间
     * @param days  正数为 days天后 ,负数为 days天前
     * @return
     */
    public static java.util.Date getTimesnight(java.util.Date date,int days){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) +(days));
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return  cal.getTime();
    }
    /**
     *  日期加减天数 (可优化)
     * @param date 时间
     * @param days 天数差
     * @return
     */
    public static java.util.Date setDateTime(java.util.Date date,int days){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) +(days));
        return  cal.getTime();
    }
    public static Boolean isExpire(java.util.Date fromDate, java.util.Date endDate, Integer expiresIn){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long diff = (endDate.getTime() - fromDate.getTime())/1000;
        if(diff > expiresIn){
            return true;
        }
        else{
            return false;
        }
    }
}

+ 89 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/ListSortUtil.java

@ -0,0 +1,89 @@
/******************************************************************************/
/* SYSTEM     : Commons                                                       */
/*                                                                            */
/* SUBSYSTEM  : Util                                                          */
/******************************************************************************/
package com.yihu.ehr.util.operator;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.collections.comparators.NullComparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ListSortUtil {
    public static ArrayList sort(ArrayList list, String[] fields) throws IllegalArgumentException {
        if (fields == null) {
            throw new IllegalArgumentException("fields is null.");
        }
        return sort(list, fields, new boolean[fields.length]);
    }
    public static List sort(List list, String[] fields) throws IllegalArgumentException {
        if (fields == null) {
            throw new IllegalArgumentException("fields is null.");
        }
        return sort(list, fields, new boolean[fields.length]);
    }
    public static ArrayList sort(ArrayList list, String[] fields, boolean[] reverses) throws IllegalArgumentException {
        return (ArrayList) sort((List) list, fields, reverses);
    }
    public static List sort(List list, String[] fields, boolean[] reverses) throws IllegalArgumentException {
        if (list == null || list.size() == 0) {
            return list;
        }
        if (fields == null) {
            throw new IllegalArgumentException("fields is null.");
        }
        if (reverses == null) {
            throw new IllegalArgumentException("reverses is null.");
        }
        if (fields.length != reverses.length) {
            throw new IllegalArgumentException("The size of fields and reverses is not in agreement.");
        }
        if (fields.length == 0) {
            return list;
        }
        // マルチカラムソート用のコンパレータ
        ComparatorChain cc = new ComparatorChain();
        for (int i = 0; fields != null && i < fields.length; i++) {
            String field = fields[i];
            boolean reverse = reverses[i];
            if (field.trim().length() == 0) {
                continue;
            }
            cc.addComparator(
                    new BeanComparator(
                            field,
                            new NullComparator(ComparableComparator.getInstance())),
                    reverse);
        }
        if (cc.size() != 0) {
            // ソート
            Collections.sort(list, cc);
        }
        return list;
    }
}

+ 636 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/NumberUtil.java

@ -0,0 +1,636 @@
package com.yihu.ehr.util.operator;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class NumberUtil {
    public static final BigDecimal DEFAULT_NUMBER = BigDecimal.ZERO;
    public static final String DECIMAL_FORMAT = "#,##0.00";
    public static final String INTEGER_FORMAT = "#,##0";
    public static final String DEFAULT_NUM_GROUP_STYLE_ID = "1";
    public static final String DEFAULT_DECIMAL_STYLE_ID = "2";
    public static final String[][] DECIMAL_STYLE_LIST = {
            {"1", ",", "Comma"},
            {"2", ".", "Period"}
    };
    public static final String[][] NUM_GROUP_STYLE_LIST = {
            {"1", ",", "Comma"},
            {"2", ".", "Period"},
            {"3", " ", "Space"}
    };
    protected NumberUtil() {
    }
    public static boolean isDivisible(BigDecimal dividend, BigDecimal divisor) {
        if (dividend == null || divisor == null) {
            return false;
        }
        if (compare(dividend.remainder(divisor), DEFAULT_NUMBER) == 0) {
            return true;
        }
        return false;
    }
    public static String changeToDecimalFormat(Number num) {
        return formatNumber(num, DECIMAL_FORMAT);
    }
    public static String changeToIntegerFormat(Number num) {
        return formatNumber(num, INTEGER_FORMAT);
    }
    public static String formatNumber(Number num, String format) {
        DecimalFormat noFormat = new DecimalFormat(format);
        return noFormat.format(num);
    }
    public static int compare(BigDecimal num1, BigDecimal num2) {
        if (num1 == null) {
            num1 = DEFAULT_NUMBER;
        }
        if (num2 == null) {
            num2 = DEFAULT_NUMBER;
        }
        return num1.compareTo(num2);
    }
    public static boolean gt(BigDecimal num1, BigDecimal num2) {
        if (compare(num1, num2) > 0) {
            return true;
        }
        return false;
    }
    public static boolean ge(BigDecimal num1, BigDecimal num2) {
        return !lt(num1, num2);
    }
    public static boolean lt(BigDecimal num1, BigDecimal num2) {
        if (compare(num1, num2) < 0) {
            return true;
        }
        return false;
    }
    public static boolean le(BigDecimal num1, BigDecimal num2) {
        return !gt(num1, num2);
    }
    public static boolean equals(BigDecimal num1, BigDecimal num2) {
        if (compare(num1, num2) == 0) {
            return true;
        }
        return false;
    }
    public static boolean equals(int num1, int num2) {
        if (compare(new BigDecimal(String.valueOf(num1)), new BigDecimal(String.valueOf(num2))) == 0) {
            return true;
        }
        return false;
    }
    public static boolean isPositive(BigDecimal num) {
        if (num == null) {
            return false;
        }
        if (gt(num, BigDecimal.ZERO)) {
            return true;
        }
        return false;
    }
    public static boolean isZero(BigDecimal num) {
        if (num == null) {
            return false;
        }
        if (equals(num, BigDecimal.ZERO)) {
            return true;
        }
        return false;
    }
    public static BigDecimal subtractBigDecimal(BigDecimal dec1, BigDecimal dec2) {
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).subtract(dec2 != null ? dec2 : DEFAULT_NUMBER);
    }
    public static BigDecimal multiplyBigDecimal(BigDecimal dec1, BigDecimal dec2) {
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).multiply(dec2 != null ? dec2 : DEFAULT_NUMBER);
    }
    public static BigDecimal divideBigDecimal(BigDecimal dec1, BigDecimal dec2) {
        if (dec2 == null || dec2.equals(DEFAULT_NUMBER)) {
            return DEFAULT_NUMBER;
        }
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).divide(dec2, 2, BigDecimal.ROUND_HALF_UP);
    }
    public static BigDecimal divideBigDecimal(BigDecimal dec1, BigDecimal dec2, int scale) {
        if (dec2 == null || dec2.equals(DEFAULT_NUMBER)) {
            return DEFAULT_NUMBER;
        }
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).divide(dec2, scale, BigDecimal.ROUND_HALF_UP);
    }
    public static BigDecimal floorDivideBigDecimal(BigDecimal dec1, BigDecimal dec2) {
        if (dec2 == null || dec2.equals(DEFAULT_NUMBER)) {
            return DEFAULT_NUMBER;
        }
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).divide(dec2, 0, BigDecimal.ROUND_FLOOR);
    }
    public static BigDecimal ceilingDivideBigDecimal(BigDecimal dec1, BigDecimal dec2) {
        if (dec2 == null || dec2.equals(DEFAULT_NUMBER)) {
            return DEFAULT_NUMBER;
        }
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).divide(dec2, 0, BigDecimal.ROUND_CEILING);
    }
    public static BigDecimal toBigDecimal(int num) {
        return toBigDecimal(StringUtil.toString(num));
    }
    public static Integer toInteger(long num) {
        return toInteger(StringUtil.toString(num));
    }
    public static BigDecimal roundBigDecimal(BigDecimal dec1, int scale) {
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).divide(new BigDecimal("1"), scale, BigDecimal.ROUND_HALF_UP);
    }
    public static BigDecimal floorBigDecimal(BigDecimal dec1, int scale) {
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).divide(new BigDecimal("1"), scale, BigDecimal.ROUND_FLOOR);
    }
    public static BigDecimal ceilingBigDecimal(BigDecimal dec1, int scale) {
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).divide(new BigDecimal("1"), scale, BigDecimal.ROUND_CEILING);
    }
    public static Boolean toBoolean(String str) {
        try {
            return new Boolean(str);
        } catch (Exception e) {
            return null;
        }
    }
    public static int toInt(String str) {
        Integer integer = toInteger(str);
        return (integer == null ? 0 : integer.intValue());
    }
    public static int toInt(Integer integer) {
        return (integer == null ? 0 : integer.intValue());
    }
    public static Integer toInteger(String str) {
        if (str == null) {
            return null;
        }
        if (StringUtil.isBlank(str)) {
            return 0;
        }
        try {
            return new Integer(str.trim());
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
    public static Integer toInteger(int i) {
        try {
            return new Integer(i);
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
    public static BigInteger toBigInteger(String str) {
        if (str == null) {
            return null;
        }
        try {
            return new BigInteger(str.trim());
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
    public static BigDecimal toBigDecimal(String str) {
        if (str == null) {
            return null;
        }
        if (StringUtil.isBlank(str)) {
            return BigDecimal.ZERO;
        }
        try {
            return new BigDecimal(str.trim());
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
    public static BigDecimal toBigDecimal(String str, String decPoPtn) {
        return toBigDecimal(formatDecDefault(str, decPoPtn));
    }
    public static Float toFloat(String str) {
        if (str == null) {
            return null;
        }
        try {
            return new Float(str.trim());
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
    public static float totoPrimitiveFloat(String str) {
        return (str == null ? 0 : Float.parseFloat(str));
    }
    public static Long toLong(String str) {
        if (str == null) {
            return null;
        }
        try {
            return new Long(str.trim());
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
    public static long totoPrimitiveLong(String str) {
        return (str == null ? 0 : Long.parseLong(str));
    }
    public static Double toDouble(String str) {
        if (str == null) {
            return null;
        }
        try {
            return new Double(str.trim());
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
    public static double totoPrimitiveDouble(String str) {
        return (str == null ? 0 : Double.parseDouble(str));
    }
    public static String getDecimalStyleName(String decimalStyleId) {
        String value = null;
        for (int i = 0; i < DECIMAL_STYLE_LIST.length; i++) {
            if (DECIMAL_STYLE_LIST[i][0].equals(decimalStyleId)) {
                value = DECIMAL_STYLE_LIST[i][2];
                break;
            }
        }
        if (value == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        return value;
    }
    public static String getDecPo(String decPoPtn) {
        return String.valueOf(getDecimalStyleValue(decPoPtn));
    }
    public static String getDecimalStyleValue(String decimalStyleId) {
        String value = null;
        for (int i = 0; i < DECIMAL_STYLE_LIST.length; i++) {
            if (DECIMAL_STYLE_LIST[i][0].equals(decimalStyleId)) {
                value = DECIMAL_STYLE_LIST[i][1];
                break;
            }
        }
        if (value == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        return value;
    }
    public static char getDecimalStyleValueChar(String decimalStyleId) {
        return getDecimalStyleValue(decimalStyleId).charAt(0);
    }
    public static String formatIntValue(int n) {
        return formatIntValue(new Integer(n));
    }
    public static String formatIntView(int n, String numSepPtn) {
        return formatIntView(new Integer(n), numSepPtn);
    }
    public static String formatIntValue(Integer num) {
        if (num == null) {
            return null;
        }
        String format = "#####0";
        return formatNum(num, format, null, null);
    }
    public static String formatIntView(Integer num, String numGroupStyleId) {
        if (num == null) {
            return null;
        }
        String format = "###,##0";
        return formatNum(num, format, null, numGroupStyleId);
    }
    public static String formatDecValue(BigDecimal dec, String decimalStyleId) {
        return formatDecValue(dec, -1, decimalStyleId);
    }
    public static String formatDecValue(BigDecimal dec, Integer decLength, String decimalStyleId) {
        return formatDecValue(dec, decLength != null ? decLength.intValue() : -1, decimalStyleId);
    }
    public static String formatDecValue(BigDecimal dec, int decLength, String decimalStyleId) {
        if (dec == null) {
            return null;
        }
        String format = "#####0";
        if (decLength > 0) {
            // 小数桁数指定あり
            for (int i = 0; i < decLength; i++) {
                if (i == 0) {
                    format += ".";
                }
                format += "0";
            }
        } else {
            // 小数桁数指定なし
            format += ".##########";
        }
        return formatNum(dec, format, decimalStyleId, null);
    }
    public static String formatDecView(BigDecimal dec, String decimalStyleId, String numGroupStyleId) {
        return formatDecView(dec, -1, decimalStyleId, numGroupStyleId);
    }
    public static String formatDecView(BigDecimal dec, Integer decLength,
                                       String decimalStyleId, String numGroupStyleId) {
        return formatDecView(dec,
                decLength != null ? decLength.intValue() : -1,
                decimalStyleId,
                numGroupStyleId);
    }
    public static String formatDecView(BigDecimal dec, int decLength,
                                       String decimalStyleId, String numGroupStyleId) {
        if (dec == null) {
            return null;
        }
        String format = "###,##0";
        if (decLength > 0) {
            // 小数桁数指定あり
            for (int i = 0; i < decLength; i++) {
                if (i == 0) {
                    format += ".";
                }
                format += "0";
            }
        } else {
            // 小数桁数指定なし
            format += ".##########";
        }
        return formatNum(dec, format, decimalStyleId, numGroupStyleId);
    }
    protected static String formatNum(Object obj, String format, String decimalStyleId, String numGroupStyleId) {
        char decPo = decimalStyleId != null ? getDecimalStyleValueChar(decimalStyleId) : ' ';
        char numSep = numGroupStyleId != null ? getNumGroupStyleValueChar(numGroupStyleId) : ' ';
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        df.applyPattern(format);
        String str = df.format(obj);
        if (str == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == ',') {
                sb.append(numSep);
                continue;
            }
            if (c == '.') {
                sb.append(decPo);
                if (i != str.length()) {
                    sb.append(str.substring(i + 1, str.length()));
                }
                break;
            }
            sb.append(c);
        }
        return sb.toString();
    }
    public static String formatDecDefault(String str, String decPoPtn) {
        if (str == null) {
            return null;
        }
        char decPo = getDecimalStyleValueChar(decPoPtn);
        StringBuffer sb = new StringBuffer(str);
        int idx = sb.toString().indexOf(String.valueOf(decPo));
        if (idx != -1) {
            sb.replace(idx, idx + String.valueOf(decPo).length(), String.valueOf('.'));
        }
        return sb.toString();
    }
    public static String getNumGroupStyleValue(String numGroupStyleId) {
        String value = null;
        for (int i = 0; i < NUM_GROUP_STYLE_LIST.length; i++) {
            if (NUM_GROUP_STYLE_LIST[i][0].equals(numGroupStyleId)) {
                value = NUM_GROUP_STYLE_LIST[i][1];
                break;
            }
        }
        if (value == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        return value;
    }
    public static char getNumGroupStyleValueChar(String numGroupStyleId) {
        return getNumGroupStyleValue(numGroupStyleId).charAt(0);
    }
    public static String getNumGroupStyleName(String numGroupStyleId) {
        String value = null;
        for (int i = 0; i < NUM_GROUP_STYLE_LIST.length; i++) {
            if (NUM_GROUP_STYLE_LIST[i][0].equals(numGroupStyleId)) {
                value = NUM_GROUP_STYLE_LIST[i][2];
                break;
            }
        }
        if (value == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }
        return value;
    }
    public static String roundString(String str) {
        BigDecimal dec = toBigDecimal(str);
        return (dec == null ? str : StringUtil.toString(roundBigDecimal(dec)));
    }
    public static BigDecimal roundBigDecimal(BigDecimal dec) {
        return (dec == null ? dec : dec.divide(new BigDecimal("1"), 0, BigDecimal.ROUND_HALF_UP));
    }
    public static int roundBigDecimal(int num) {
        return toInt(roundString(StringUtil.toString(num)));
    }
    public static String fomatNumber(double amount, String pattern) {
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        DecimalFormat df = (DecimalFormat) nf;
        df.setMinimumFractionDigits(2);
        df.setMaximumFractionDigits(2);
        df.setDecimalSeparatorAlwaysShown(true);
        df.applyPattern(pattern);
        return df.format(amount);
    }
    public static String fomatNumber(long amount, String pattern) {
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        DecimalFormat df = (DecimalFormat) nf;
        df.setMinimumFractionDigits(2);
        df.setMaximumFractionDigits(2);
        df.setDecimalSeparatorAlwaysShown(true);
        df.applyPattern(pattern);
        return df.format(amount);
    }
    public static BigDecimal addBigDecimal(BigDecimal dec1, BigDecimal dec2) {
        return (dec1 != null ? dec1 : new BigDecimal(0)).add(dec2 != null ? dec2 : new BigDecimal(0));
    }
    public static boolean isInteger(String target) {
        if (target == null) {
            return false;
        }
        char[] digit = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        for (int i = 0; i < target.length(); i++) {
            for (int j = 0; j < digit.length; j++) {
                if (target.charAt(i) == digit[j]) {
                    break;
                }
                if (i == 0 && target.charAt(i) == '-') {
                    break;
                }
                if (i == 0 && target.charAt(i) == '+') {
                    break;
                }
                if (j == digit.length - 1) {
                    return false;
                }
            }
        }
        return true;
    }
}

+ 29 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/Select2.java

@ -0,0 +1,29 @@
package com.yihu.ehr.util.operator;
/**
 * select2类
 *
 * @author llh
 */
public class Select2 {
    private String id;
    private String text;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}

+ 388 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/SqlCreate.java

@ -0,0 +1,388 @@
package com.yihu.ehr.util.operator;
import com.yihu.ehr.common.constants.Constants;
import java.util.List;
import java.util.Map;
/**
 * Created by lingfeng on 2015/6/23.
 */
public class SqlCreate {
    private String primaryKey;
    private String tableName;
    private String tableItem;
    private String tableKey;
    private List<String> itemList;
    private List<String> itemValueList;
    private List<String> conditionList;
    private Map<String, String> keyValueMap;
    private static String[] stdTable = {"std_dataset", "std_metadata", "std_dict", "std_dict_item"};
    private static String[] stdDatasetTable = {"std_dataset", "std_metadata"};
    public SqlCreate() {
    }
    public String createTable() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.CREATE_TABLE + tableName + Constants.LEFT_BRACKET);
        for (String item : itemList) {
            sqlBuffer.append(item + Constants.COMMA);
        }
        if (!primaryKey.equals("")) {
            sqlBuffer.append(Constants.PRIMARY_KEY + Constants.LEFT_BRACKET + primaryKey);
            sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
            sqlBuffer.append(Constants.RIGHT_BRACKET);
        } else {
            sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
        }
        sqlBuffer.append(Constants.RIGHT_BRACKET + Constants.ROW_FORMAT_DYNAMIC + Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String insertData() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.INSERT_INTO + tableName + Constants.LEFT_BRACKET);
        for (String item : itemList) {
            sqlBuffer.append(item + Constants.COMMA);
        }
        sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
        sqlBuffer.append(Constants.RIGHT_BRACKET + Constants.VALUES + Constants.LEFT_BRACKET);
        for (String item : itemValueList) {
            sqlBuffer.append(item + Constants.COMMA);
        }
        sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
        sqlBuffer.append(Constants.RIGHT_BRACKET + Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String insertDataByKeyValue() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.INSERT_INTO + this.tableName + Constants.LEFT_BRACKET);
        for (String key : keyValueMap.keySet()) {
            sqlBuffer.append(key + Constants.COMMA);
        }
        sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
        sqlBuffer.append(Constants.RIGHT_BRACKET + Constants.VALUES + Constants.LEFT_BRACKET);
        for (String key : keyValueMap.keySet()) {
            sqlBuffer.append(keyValueMap.get(key) + Constants.COMMA);
        }
        sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
        sqlBuffer.append(Constants.RIGHT_BRACKET + Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String updateDataByTableKey() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.UPDATE + tableName + Constants.SET);
        for (String key : keyValueMap.keySet()) {
            sqlBuffer.append(key + Constants.EQUAL_MARK + keyValueMap.get(key) + Constants.COMMA);
        }
        sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
        sqlBuffer.append(Constants.WHERE + Constants.TABLE_KEY + Constants.EQUAL_MARK + tableKey);
        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String getMaxId() {
        String sql = "select max(id) from " + tableName;
        return sql;
    }
    public Boolean isToAdapter() {
        Boolean flg = false;
        for (String str : stdTable) {
            if (tableName.equals(str)) {
                flg = true;
            }
        }
        return flg;
    }
    public Boolean isToAdapterDataset() {
        Boolean flg = false;
        for (String str : stdDatasetTable) {
            if (tableName.equals(str)) {
                flg = true;
            }
        }
        return flg;
    }
    public Boolean isCodeOrValue() {
        Boolean flg = false;
        for (String key : keyValueMap.keySet()) {
            if (key.equals(Constants.CODE_STR) || key.equals(Constants.VALUE_STR)) {
                flg = true;
            }
        }
        return flg;
    }
    public String updateAdapterData() {
        StringBuilder sqlBuffer = new StringBuilder();
        String adapterTableName = tableName.replace(Constants.STD_PREFIX, Constants.ADAPTER_PREFIX);
        sqlBuffer.append(Constants.UPDATE + adapterTableName + Constants.SET);
        for (String key : keyValueMap.keySet()) {
            if (key.equals(Constants.CODE_STR) || key.equals(Constants.VALUE_STR)) {
                sqlBuffer.append(tableName + Constants.UNDERLINE + key + Constants.EQUAL_MARK
                        + keyValueMap.get(key) + Constants.COMMA);
            }
        }
        sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
        sqlBuffer.append(Constants.WHERE + tableName + Constants.UNDERLINE + Constants.TABLE_KEY
                + Constants.EQUAL_MARK + tableKey);
        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String failureDataByTableKey() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.UPDATE + tableName + Constants.SET);
        sqlBuffer.append(Constants.FAILURE_FLG + Constants.EQUAL_MARK + Constants.NUMBER_ZREO);
        sqlBuffer.append(Constants.WHERE + Constants.TABLE_KEY + Constants.EQUAL_MARK + tableKey);
        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String deleteDataByTableKey() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.DELETE);
        sqlBuffer.append(Constants.FROM + tableName);
        sqlBuffer.append(Constants.WHERE + Constants.TABLE_KEY + Constants.EQUAL_MARK + tableKey);
        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String deleteAdapterData() {
        StringBuilder sqlBuffer = new StringBuilder();
        String adapterTableName = tableName.replace(Constants.STD_PREFIX, Constants.ADAPTER_PREFIX);
        sqlBuffer.append(Constants.DELETE);
        sqlBuffer.append(Constants.FROM + adapterTableName);
        sqlBuffer.append(Constants.WHERE + tableName + Constants.UNDERLINE + Constants.TABLE_KEY
                + Constants.EQUAL_MARK + tableKey);
        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String deleteAdapterOriginData() {
        StringBuilder sqlBuffer = new StringBuilder();
        String adapterOriginTableName = tableName.replace(Constants.STD_PREFIX, Constants.ADAPTER_PREFIX + Constants.ORIGIN_PREFIX);
        String tableKeyStr = tableName.replace(Constants.STD_PREFIX, "") + Constants.UNDERLINE + Constants.TABLE_KEY;
                sqlBuffer.append(Constants.DELETE);
        sqlBuffer.append(Constants.FROM + adapterOriginTableName);
        sqlBuffer.append(Constants.WHERE + tableKeyStr + Constants.EQUAL_MARK + tableKey);
        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String addTableItem() {
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append(Constants.ALTER_TABLE + tableName + Constants.ADD + tableItem + Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String deleteData() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.DELETE);
        sqlBuffer.append(Constants.FROM + tableName);
        if (!CollectionUtil.isEmpty(conditionList)) {
            sqlBuffer.append(Constants.WHERE);
            sqlBuffer.append("1=1" + Constants.AND);
            for (String condition : conditionList) {
                sqlBuffer.append(condition + Constants.AND);
            }
            sqlBuffer.delete(sqlBuffer.length() - 4, sqlBuffer.length() - 1);
        }
//        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String count() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.SELECT);
        sqlBuffer.append(Constants.COUNT);
        sqlBuffer.append(Constants.FROM + tableName);
        if (!CollectionUtil.isEmpty(conditionList)) {
            sqlBuffer.append(Constants.WHERE);
            sqlBuffer.append("1=1" + Constants.AND);
            for (String condition : conditionList) {
                sqlBuffer.append(condition + Constants.AND);
            }
            sqlBuffer.delete(sqlBuffer.length() - 4, sqlBuffer.length() - 1);
        }
        return sqlBuffer.toString();
    }
    public String selectData() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.SELECT);
        for (String item : itemList) {
            sqlBuffer.append(item + Constants.COMMA);
        }
        sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
        sqlBuffer.append(Constants.FROM + tableName);
        if (!CollectionUtil.isEmpty(conditionList)) {
            sqlBuffer.append(Constants.WHERE);
            sqlBuffer.append("1=1" + Constants.AND);
            for (String condition : conditionList) {
                sqlBuffer.append(condition + Constants.AND);
            }
            sqlBuffer.delete(sqlBuffer.length() - 4, sqlBuffer.length() - 1);
        }
//        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String selectAllData() {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(Constants.SELECT);
        sqlBuffer.append(Constants.STAR);
        sqlBuffer.append(Constants.FROM + tableName);
        if (!CollectionUtil.isEmpty(conditionList)) {
            sqlBuffer.append(Constants.WHERE);
            sqlBuffer.append("1=1" + Constants.AND);
            for (String condition : conditionList) {
                sqlBuffer.append(condition + Constants.AND);
            }
            sqlBuffer.delete(sqlBuffer.length() - 4, sqlBuffer.length() - 1);
        }
//        sqlBuffer.append(Constants.SEMICOLON);
        return sqlBuffer.toString();
    }
    public String betweenCondition(String item) {
        String condition = item + Constants.BETWEEN + Constants.QUESTION_MARK + Constants.AND + Constants.QUESTION_MARK;
        return condition;
    }
    public String greaterAndEqualCondition(String item) {
        String condition = item + Constants.GREATER_EQUAL_MARK + Constants.QUESTION_MARK;
        return condition;
    }
    public String greaterCondition(String item) {
        String condition = item + Constants.GREATER_MARK + Constants.QUESTION_MARK;
        return condition;
    }
    public String lessAndEqualCondition(String item) {
        String condition = item + Constants.LESS_EQUAL_MARK + Constants.QUESTION_MARK;
        return condition;
    }
    public String lessCondition(String item) {
        String condition = item + Constants.LESS_MARK + Constants.QUESTION_MARK;
        return condition;
    }
    public String betweenCondition(String item, String value1, String value2) {
        String condition = item + Constants.BETWEEN + value1 + Constants.AND + value2;
        return condition;
    }
    public String equalCondition(String item) {
        String condition = item + Constants.EQUAL_MARK + Constants.QUESTION_MARK;
        return condition;
    }
    public String equalCondition(String item, String value) {
        String condition = item + Constants.EQUAL_MARK + value;
        return condition;
    }
    public String likeCondition(String item) {
        String condition = item + Constants.LIKE + Constants.QUESTION_MARK;
        return condition;
    }
    public String getTableName() {
        return tableName;
    }
    public void setTableName(String tableName) {
        this.tableName = tableName;
    }
    public String getPrimaryKey() {
        return primaryKey;
    }
    public void setPrimaryKey(String primaryKey) {
        this.primaryKey = primaryKey;
    }
    public List<String> getItemList() {
        return itemList;
    }
    public void setItemList(List<String> itemList) {
        this.itemList = itemList;
    }
    public List<String> getItemValueList() {
        return itemValueList;
    }
    public void setItemValueList(List<String> itemValueList) {
        this.itemValueList = itemValueList;
    }
    public String getTableItem() {
        return tableItem;
    }
    public void setTableItem(String tableItem) {
        this.tableItem = tableItem;
    }
    public List<String> getConditionList() {
        return conditionList;
    }
    public void setConditionList(List<String> conditionList) {
        this.conditionList = conditionList;
    }
    public String getTableKey() {
        return tableKey;
    }
    public void setTableKey(String tableKey) {
        this.tableKey = tableKey;
    }
    public Map<String, String> getKeyValueMap() {
        return keyValueMap;
    }
    public void setKeyValueMap(Map<String, String> keyValueMap) {
        this.keyValueMap = keyValueMap;
    }
}

+ 1428 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/StringUtil.java

@ -0,0 +1,1428 @@
package com.yihu.ehr.util.operator;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
public class StringUtil {
    public static String substring(String str, int start) {
        return StringUtils.substring(str, start);
    }
    public static String substring(String str, int start, int end) {
        return StringUtils.substring(str, start, end);
    }
    public static boolean isBlank(String str) {
        return StringUtils.isBlank(str);
    }
    public static String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        return obj.toString();
    }
    public static String trimLeft(String value) {
        if (value == null)
            return "";
        String result = value;
        char ch[] = result.toCharArray();
        int index = -1;
        for (int i = 0; i < ch.length; i++) {
            if (Character.isWhitespace(ch[i])) {
                index = i;
            } else {
                break;
            }
        }
        if (index != -1) {
            result = result.substring(index + 1);
        }
        return result;
    }
    /**
     * �ù���ѹ���ַ������ұ߿ո�
     *
     * @param value ��Դ��
     * @return String src����ַ���
     */
    public static String trimRight(String value) {
        if (value == null)
            return "";
        String result = value;
        char ch[] = result.toCharArray();
        int endIndex = -1;
        for (int i = ch.length - 1; i > -1; i--) {
            if (Character.isWhitespace(ch[i])) {
                endIndex = i;
            } else {
                break;
            }
        }
        if (endIndex != -1) {
            result = result.substring(0, endIndex);
        }
        return result;
    }
    /**
     * ***************************************************** ��
     * �ܣ����ַ���ǰ����Ӷ��"0",���ع̶����� ��ڲ�����param str:��������ַ��� param len�����ع̶����� �� �أ�Stirng
     * <p/> ��д���ڣ� �޸ı�ע�� ******************************************************
     */
    public static String fillHeadCharsLen(String strOri, int len) {
        return fillHeadCharsLen(strOri, "0", len);
    }
    /**
     * ***************************************************** ��
     * �ܣ����ַ���������Ӷ��"0",���ع̶����� ��ڲ�����param str:��������ַ��� param len�����ع̶����� �� �أ�Stirng
     * <p/> ��д���ڣ� �޸ı�ע�� ******************************************************
     */
    public static String fillBackCharsLen(String strOri, int len) {
        return fillBackCharsLen(strOri, "0", len);
    }
    /**
     * ***************************************************** ��
     * �ܣ����ַ���ǰ����Ӷ���ظ��ַ���,���ع̶����� ��ڲ�����param str:��������ַ��� param subStr:�ظ������ַ���
     * param len�����ع̶����� �� �أ�Stirng <p/> ��д���ڣ� �޸ı�ע��
     * ******************************************************
     */
    public static String fillHeadCharsLen(String strOri, String subStr, int len) {
        if (strOri == null || strOri.trim().length() == 0) {
            strOri = "";
        }
        if (subStr == null) {
            subStr = " ";
        }
        String fillStr = "";
        for (int i = 0; i < len; i++) {
            fillStr = fillStr + subStr;
        }
        subStr = fillStr + strOri;
        return (subStr.substring(subStr.length() - len, subStr.length()));
    }
    /**
     * ***************************************************** ��
     * �ܣ����ַ���������Ӷ���ظ��ַ���,���ع̶����� ��ڲ�����param str:��������ַ��� param subStr:�ظ������ַ���
     * param len�����ع̶����� �� �أ�Stirng <p/> ��д���ڣ� �޸ı�ע��
     * ******************************************************
     */
    public static String fillBackCharsLen(String strOri, String subStr, int len) {
        if (strOri == null || strOri.trim().length() == 0) {
            strOri = "";
        }
        if (subStr == null) {
            subStr = " ";
        }
        String fillStr = "";
        for (int i = 0; i < len; i++) {
            fillStr = fillStr + subStr;
        }
        subStr = strOri + fillStr;
        return (subStr.substring(0, len));
    }
    /**
     * ***************************************************** �� �ܣ����ַ���ǰ����Ӷ��"0"
     * ��ڲ�����param str:��������ַ��� param counter���ظ������� �� �أ�Stirng <p/> ��д���ڣ� �޸ı�ע��
     * ******************************************************
     */
    public static String fillHeadChars(String strOri, int counter) {
        return fillHeadChars(strOri, "0", counter);
    }
    /**
     * ***************************************************** �� �ܣ����ַ���������Ӷ��"0"
     * ��ڲ�����param str:��������ַ��� param counter���ظ������� �� �أ�Stirng <p/> ��д���ڣ� �޸ı�ע��
     * ******************************************************
     */
    public static String fillBackChars(String strOri, int counter) {
        return fillBackChars(strOri, "0", counter);
    }
    /**
     * ***************************************************** �� �ܣ����ַ���ǰ����Ӷ���ظ��ַ���
     * ��ڲ�����param str:��������ַ��� param subStr:�ظ������ַ��� param counter���ظ������� ��
     * �أ�Stirng <p/> ��д���ڣ� �޸ı�ע��
     * ******************************************************
     */
    public static String fillHeadChars(String strOri, String subStr, int counter) {
        if (strOri == null || strOri.trim().length() == 0) {
            strOri = "";
        }
        if (counter <= 0 || subStr == null) {
            return strOri;
        }
        String fillStr = "";
        for (int i = 0; i < counter; i++) {
            fillStr = fillStr + subStr;
        }
        return (fillStr + strOri);
    }
    /**
     * ***************************************************** �� �ܣ����ַ���������Ӷ���ظ��ַ���
     * ��ڲ�����param str:��������ַ��� param subStr:�ظ������ַ��� param counter���ظ������� ��
     * �أ�Stirng <p/> ��д���ڣ� �޸ı�ע��
     * ******************************************************
     */
    public static String fillBackChars(String strOri, String subStr, int counter) {
        if (strOri == null || strOri.trim().length() == 0) {
            strOri = "";
        }
        if (counter <= 0 || subStr == null) {
            return strOri;
        }
        String fillStr = "";
        for (int i = 0; i < counter; i++) {
            fillStr = fillStr + subStr;
        }
        return (strOri + fillStr);
    }
    /**
     * ***************************************************** ��
     * �ܣ��ж��ַ����Ƿ�Ϊ�ջ���null(ѹ���ո��) ��ڲ�����param str:��������ַ��� ���ڲ����� �� �أ��գ�null��true;
     * ���գ�false <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean isEmpty(Object strObj) {
        if (strObj == null || strObj.toString().trim().length() < 1) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * ***************************************************** ��
     * �ܣ��ж�һ���ַ����Ƿ�Ϊ��ֵ��null����(ѹ���ո��)�� ��ڲ�����param str:���жϵ��ַ��� ���ڲ����� ��
     * �أ�true���գ�false���ǿ� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean isStrEmpty(String str) {
        if ((str == null) || (str.trim().length() < 1) || "null".endsWith(str.toLowerCase())) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * ***************************************************** ��
     * �ܣ�����һ���ַ���ȥ���ұ߿ո���ֵ�����Ϊnull�򷵻ؿմ� ��ڲ�����param str:��������ַ��� ���ڲ����� ��
     * �أ�ȥ���ұ߿ո����ַ������߿մ� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String getValue(String str) {
        if (str == null) {
            return "";
        }
        if (str.trim().length() <= 0)
            return "";
        str = "H" + str;
        str = str.trim();
        str = str.substring(1);
        return str;
    }
    /**
     * ***************************************************** �� �ܣ��ж�һ���ַ����Ƿ񳬳���������
     * ��ڲ�����param text:���жϵ��ַ�����param len:�����ij��� ���ڲ����� �� �أ�return
     * true��δ������false��Ϊ�ջ��߳��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean chkTextLen(String text, int len) {
        if (text == null || text.length() > len) {
            return false;
        } else {
            return true;
        }
    }
    /**
     * ***************************************************** ��
     * �ܣ��ж�һ���ַ���ȥ���ո��Ƿ񳬳��������� ��ڲ�����param text:���жϵ��ַ�����param len:�����ij��� ���ڲ����� ��
     * �أ�return true��δ������false��Ϊ�ջ��߳��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean chkTextTrimLen(String text, int len) {
        if (text == null || text.trim().length() > len) {
            return false;
        } else {
            return true;
        }
    }
    /**
     * ***************************************************** ��
     * �ܣ��ж�һ���ַ����Ƿ�ֻ��english ��ڲ�����param text:���жϵ��ַ����� ���ڲ����� �� �أ�return
     * true���Ϸ���false:�������Ļ��������Ƿ��ַ� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean isStrEn(String text) {
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) > 127) {
                return false;
            }
        }
        return true;
    }
    /**
     * ***************************************************** �� �ܣ��ж�һ���ַ����Ƿ�����
     * ��ڲ�����param ch:���жϵ��ַ� ���ڲ����� �� �أ�return true�����֣�false:������ <p/>
     * ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean isCharNum(char ch) {
        if (ch > 47 && ch < 58) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * ***************************************************** ��
     * �ܣ��ж�һ���ַ����Ƿ��з����ֵ��ַ� ��ڲ�����param str:���жϵ��ַ��� ���ڲ����� �� �أ�return
     * true��Null���߲�ȫ�����֣�false:ȫ������ <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean isStrNum(String str) {
        if (isStrEmpty(str)) {
            return true;
        }
        boolean notNum = false;
        for (int i = 0; i < str.length(); i++) {
            if (!isCharNum(str.charAt(i))) {
                notNum = true;
            }
        }
        return !notNum;
    }
    /**
     * ***************************************************** ��
     * �ܣ��ж�һ���ַ����Ƿ��з����ֵ��ַ� ��ڲ�����param strSrc:���жϵ��ַ��� ���ڲ����� �� �أ�return
     * true��ȫ�����֣�false:��ȫ������ <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean isNum(String strSrc) throws Exception {
        for (int i = 0; i < strSrc.length(); i++) {
            if (!isCharNum(strSrc.charAt(i)))
                return false;
        }
        return true;
    }
    /**
     * ***************************************************** �� �ܣ��ж�һ���ַ��Ƿ���Ӣ����ĸ
     * ��ڲ�����param ch:���жϵ��ַ� ���ڲ����� �� �أ�return true����Ӣ����ĸ��false:����Ӣ����ĸ <p/>
     * ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean isCharLetter(char ch) {
        if ((ch >= 65 && ch <= 90) && (ch >= 97 && ch <= 122)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * ***************************************************** �� �ܣ��ж�һ���ַ����Ƿ�ȫ��Ӣ����ĸ
     * ��ڲ�����param str:���жϵ��ַ��� ���ڲ����� �� �أ�return true��NULL���з�Ӣ����ĸ��false:ȫ��Ӣ����ĸ
     * <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean isStrLetter(String str) {
        if (isStrEmpty(str))
            return true;
        boolean notLetter = false;
        for (int i = 0; i < str.length(); i++) {
            if (!isCharLetter(str.charAt(i))) {
                notLetter = true;
            }
        }
        return !notLetter;
    }
    /**
     * ***************************************************** ��
     * �ܣ���������ַ���ȡ����һ���ַ����� ��ڲ�����param src:������ַ��� ���ڲ����� �� �أ�return
     * ��������ַ���ȡ����һ���ַ����� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static char strToChar(String src) {
        src = src.trim();
        char result = src.charAt(0);
        return result;
    }
    /**
     * ***************************************************** ��
     * �ܣ���������ַ���ת�ɶ�Ӧ��ASCII�봮 ��ڲ�����param sql:�������sql������ ���ڲ����� �� �أ��������ַ��� <p/>
     * ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String encodeSQL(String sql) {
        StringBuffer tempBuff = new StringBuffer();
        for (int i = 0; i < sql.length(); i++) {
            tempBuff.append(Integer.toHexString(sql.charAt(i)));
        }
        return tempBuff.toString();
    }
    /**
     * ***************************************************** ��
     * �ܣ��������ASCII�봮����Ϊ��Ӧ���ַ��� ��ڲ�����param encoded:��������ַ��� ���ڲ����� �� �أ��������ַ��� <p/>
     * ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String decodeSQL(String encoded) {
        StringBuffer tempBuff = new StringBuffer();
        for (int i = 0; i < encoded.length(); i += 2) {
            tempBuff.append((char) Integer.parseInt(
                    encoded.substring(i, i + 2), 16));
        }
        return tempBuff.toString();
    }
    /**
     * ***************************************************** �� �ܣ���ȡ���·��
     * ��ڲ�����param path1:����·����param context1:������ ���ڲ����� �� �أ�return ���·�� <p/>
     * ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String getAbsolutePath(String path1, String context1) {
        int i1 = path1.indexOf(context1);
        if (i1 < 0) {
            return path1;
        } else {
            return path1.substring(path1.indexOf(context1) + context1.length());
        }
    }
    /**
     * ***************************************************** �� �ܣ���ȡ�Ӵ� ��ڲ�����param
     * str1:��ȡ�Ӵ����ַ�����param sindex:��ʼλ�ã�param eindex:����λ�� ���ڲ����� ��
     * �أ����ش���ʼλ�ÿ�ʼ����λ�ý������Ӵ����������λ��С��0���򷵻ش���ʼλ�ÿ�ʼ���Ӵ� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String getSubString(String str1, int sindex, int eindex) {
        if (str1 == null) {
            return "";
        }
        if (str1.trim().length() <= 0)
            return "";
        if (str1.length() > sindex) {
            if (eindex >= 0)
                return str1.substring(sindex, eindex);
            else if (eindex < 0)
                return str1.substring(sindex);
        }
        return "";
    }
    /**
     * ***************************************************** ��
     * �ܣ����ַ����������䵽ָ���Ĵ�С��������ÿմ����� ��ڲ�����param strs:��������ַ������飬param size1:���������鳤��
     * ���ڲ����� �� �أ�return �������ַ������� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String[] getValues(String[] strs, int size1) {
        String[] strs1 = new String[size1];
        for (int i = 0; i < size1; i++) {
            strs1[i] = "";
        }
        if (strs == null) {
            return strs1;
        } else {
            if (strs.length < size1) {
                for (int i = 0; i < strs.length; i++) {
                    strs1[i] = strs[i];
                }
                return strs1;
            } else {
                return strs;
            }
        }
    }
    /**
     * ***************************************************** �� �ܣ��ַ���ȫ���滻����
     * ��ڲ�����param strSource ���滻���ַ�����param strFrom Դ�ַ�����param strTo Ŀ���ַ��� ���ڲ����� ��
     * �أ��滻����ַ��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String replaceStrAll(String strSource, String strFrom,
                                       String strTo) {
        String strDest = "";
        int intFromLen = strFrom.length();
        int intPos;
        while ((intPos = strSource.indexOf(strFrom)) != -1) {
            strDest = strDest + strSource.substring(0, intPos);
            strDest = strDest + strTo;
            strSource = strSource.substring(intPos + intFromLen);
        }
        strDest = strDest + strSource;
        return strDest;
    }
    public static String replaceStr(String strTarget, String strNew) {
        int iIndex = -1;
        while (true) {
            iIndex = strTarget.indexOf('\n');
            if (iIndex < 0) {
                break;
            }
            String strTemp = null;
            strTemp = strTarget.substring(0, iIndex);
            strTarget = strTemp + strNew + strTarget.substring(iIndex + 1);
        }
        return strTarget;
    }
    /**
     * ***************************************************** ��
     * �ܣ��ж��ַ����������Ƿ��и��ַ��� ��ڲ�����param str1 ��Ѱ�ҵ��ַ�����param strarray ��Ѱ�ҵ��ַ������飬
     * ���ڲ����� �� �أ�return true������;false��δ���� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static boolean includestr(String str1, String[] strarray) {
        if (strarray == null || strarray.length <= 0)
            return false;
        for (int i = 0; i < strarray.length; i++) {
            if (strarray[i] == null) {
                if (str1 == null)
                    return true;
                else
                    continue;
            }
            if (strarray[i].trim().equals(str1)) {
                return true;
            }
        }
        return false;
    }
    /**
     * ***************************************************** ��
     * �ܣ���\n��Ϊ�ָ��������ַ����ָ������飬��ȥ��\r ��ڲ�����param fvalue ��ת�����ַ��� ���ڲ����� �� �أ�return
     * ת��������� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String[] getAreaValues(String fvalue) {
        String tmpstr = fvalue;
        int i = 0;
        if (tmpstr == null)
            return null;
        if (tmpstr.trim().equals(""))
            return null;
        while (tmpstr.indexOf("\n") >= 0) {
            i++;
            tmpstr = tmpstr.substring(tmpstr.indexOf("\n") + 1);
        }
        if (tmpstr.trim().equals("")) {
            i--;
        }
        String[] fvalues = new String[i + 1];
        tmpstr = fvalue;
        i = 0;
        while (tmpstr.indexOf("\n") >= 0) {
            fvalues[i] = tmpstr.substring(0, tmpstr.indexOf("\n"));
            if (fvalues[i].indexOf("\r") >= 0)
                fvalues[i] = fvalues[i].substring(0, fvalues[i].indexOf("\r"));
            i++;
            tmpstr = tmpstr.substring(tmpstr.indexOf("\n") + 1);
        }
        if (!tmpstr.trim().equals(""))
            fvalues[i] = tmpstr;
        return fvalues;
    }
    /**
     * ***************************************************** �� �ܣ����ַ����е�|ת�ɴ�\n
     * ��ڲ�����param fvalue ��ת�����ַ��� ���ڲ����� �� �أ�ת������ַ��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String getrealAreaValues(String fvalue) {
        String tmpstr = fvalue;
        String returnstr = "";
        if (tmpstr == null)
            return null;
        if (tmpstr.trim().equals(""))
            return "";
        while (tmpstr.indexOf("|") > 0) {
            returnstr += tmpstr.substring(0, tmpstr.indexOf("|")) + "\n";
            tmpstr = tmpstr.substring(tmpstr.indexOf("|") + 1);
        }
        return returnstr;
    }
    /**
     * ***************************************************** ��
     * �ܣ������ַ����к��е�ָ���ַ��ĸ��� ��ڲ�����param strInput ��������ַ�����param chr ��Ѱ�ҵ��ַ� ���ڲ����� ��
     * �أ�return ������ַ����� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static int countChar(String strInput, char chr) {
        int iCount = 0;
        char chrTmp = ' ';
        if (strInput.trim().length() == 0)
            return 0;
        // ����ָ�����ٸ��ַ���
        for (int i = 0; i < strInput.length(); i++) {
            chrTmp = strInput.charAt(i);
            if (chrTmp == chr) {
                iCount++;
            }
        }
        return iCount;
    }
    /**
     * ***************************************************** �� �ܣ�����ά����ת��һ���ַ����ͳ�
     * ��ڲ�����param strs ��ת�����ַ������� ���ڲ����� �� �أ��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String strArrayToStr(String[] strs) {
        return strArrayToStr(strs, null);
    }
    /**
     * ***************************************************** �� �ܣ����еĴ�ӡ���ַ������������
     * ��ڲ�����param strs ����ӡ���ַ������� ���ڲ����� �� �أ��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static void printStrs(String[] strs) {
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
    }
    /**
     * ***************************************************** ��
     * �ܣ���ά�����У�һά���еĴ�ӡ���ַ������������ ��ڲ�����param strs ����ӡ�Ķ�ά�ַ������� ���ڲ����� �� �أ��� <p/>
     * ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static void printDualStr(String[][] dualStr) {
        for (int i = 0; i < dualStr.length; i++) {
            for (int j = 0; j < dualStr[i].length; j++) {
                System.out.print(dualStr[i][j] + " ");
            }
            System.out.println();
        }
    }
    /**
     * ***************************************************** ��
     * �ܣ�����ά��������ߵ������б�Ϊ�У����б�Ϊ�� ��ڲ�����param dualStr ����Ķ�ά���� ���ڲ����� �� �أ�return
     * �ߵ���Ķ�ά���� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String[][] rowToColumn(String[][] dualStr) {
        String[][] returnDualStr = null;
        if (dualStr != null) {
            returnDualStr = new String[dualStr[0].length][dualStr.length];
            for (int i = 0; i < dualStr.length; i++)
                for (int j = 0; j < dualStr[0].length; j++)
                    returnDualStr[j][i] = dualStr[i][j];
        }
        return returnDualStr;
    }
    /**
     * ***************************************************** ��
     * �ܣ���Ҫ��ֵ��ҳ����ʾ���String�����е������ַ�����ת��� ��ڲ�����param inStr ������ַ��� ���ڲ����� �� �أ�return
     * ���ת�������ַ��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String latinString(String inStr) {
        String res = inStr;
        if (null == res)
            return null;
        res = replaceStrAll(res, "\"", "\\\"");
        res = replaceStrAll(res, "'", "\\'");
        return res;
    }
    /**
     * ***************************************************** �� �ܣ����ַ������пո��滻��ָ����
     * ��ڲ�����param String strTarget, String strNew ���ڲ����� �� �أ�return String
     * �����ѱ��滻���ִ� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String replaceWhiteSpace(String strTarget, String strNew) {
        int iIndex = -1;
        while (true) {
            char cRep = 32;
            iIndex = strTarget.indexOf(cRep);
            if (iIndex < 0) {
                break;
            }
            String strTemp = null;
            strTemp = strTarget.substring(0, iIndex);
            strTarget = strTemp + strNew + strTarget.substring(iIndex + 1);
        }
        return strTarget;
    }
    /**
     * ***************************************************** ��
     * �ܣ�������д�ɷ���Ҫ���С����λ����ֻȥ�������С����λ��������չλ���� ��ڲ�����param amount ����Ľ��, param
     * length ָ����С��λ���� ���ڲ����� �� �أ�return ���ת�������ַ��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String double2str(double amount, int length) {
        String strAmt = Double.toString(amount);
        int pos = strAmt.indexOf('.');
        if (pos != -1 && strAmt.length() > length + pos + 1)
            strAmt = strAmt.substring(0, pos + length + 1);
        return strAmt;
    }
    /**
     * ***************************************************** ��
     * �ܣ�����chr�ָ��ַ�������ΪString���Դ���split��֧����"|"Ϊ�ָ���� ��ڲ�����param str ��Ҫ���ָ�Ĵ�,param
     * chr �ָ���� ���ڲ����� �� �أ�return String[] �ָ����ַ�������,���������һ��|������ַ��� <p/>
     * ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String[] doSplit(String str, char chr) {
        int iCount = 0;
        char chrTmp = ' ';
        // ����ָ�����ٸ��ַ���
        for (int i = 0; i < str.length(); i++) {
            chrTmp = str.charAt(i);
            if (chrTmp == chr) {
                iCount++;
            }
        }
        String[] strArray = new String[iCount];
        for (int i = 0; i < iCount; i++) {
            int iPos = str.indexOf(chr);
            if (iPos == 0) {
                strArray[i] = "";
            } else {
                strArray[i] = str.substring(0, iPos);
            }
            str = str.substring(iPos + 1); // ��iPos+1������,str��������С
        }
        return strArray;
    }
    /**
     * ***************************************************** ��
     * �ܣ�����s�ָ��ַ�������ΪString���Դ���split��֧����"|"Ϊ�ָ���� ��ڲ�����param str ��Ҫ���ָ�Ĵ�,param s
     * �ָ��ַ��� ���ڲ����� �� �أ�return String[] �ָ����ַ�������,�������һ��|������ַ��� <p/>
     * ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String[] strSplit(String src, String splitchar) {
        int resultSize = 0;
        int len = src.length();
        int idx = 0;
        String strTemp = "";
        for (int i = 0; i < len; i++) {
            if (src.substring(i, i + 1).equals(splitchar)) {
                resultSize++;
            }
        }
        if ((len > 1) & (!src.substring(len - 1, len).equals(splitchar))) {
            resultSize++;
        }
        String result[] = new String[resultSize];
        for (int i = 0; i < len; i++) {
            if (src.substring(i, i + 1).equals(splitchar)) {
                result[idx] = strTemp;
                idx++;
                strTemp = "";
            } else {
                strTemp = String.valueOf(strTemp)
                        + String.valueOf(src.charAt(i));
            }
        }
        if (!strTemp.equals("")) {
            result[idx] = strTemp;
        }
        return result;
    }
    /**
     * ***************************************************** ��
     * �ܣ�����strSeparator�ָ��ַ�����ֻ�ָ���ָ����С���ַ��� ��ڲ�����param strToSplit ��Ҫ���ָ�Ĵ�,param
     * strSeparator �ָ��ַ���,param iLimit ָ����С ���ڲ����� �� �أ�return String[] �ָ����ַ�������
     * <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String[] split(String strToSplit, String strSeparator,
                                 int iLimit) {
        ArrayList tmpList = new ArrayList();
        int iFromIndex = 0;
        int iCurIndex = strToSplit.length();
        String strUnitInfo = "";
        int iCurCounts = 0;
        while ((iCurIndex != -1) && (iFromIndex < strToSplit.length())
                && (iCurCounts < iLimit)) {
            iCurIndex = strToSplit.indexOf(strSeparator, iFromIndex);
            if (iCurIndex == -1) {
                strUnitInfo = strToSplit.substring(iFromIndex, strToSplit
                        .length());
            } else {
                strUnitInfo = strToSplit.substring(iFromIndex, iCurIndex);
                iFromIndex = iCurIndex + 1;
            }
            tmpList.add(strUnitInfo);
            iCurCounts++;
        }
        int iCounts = tmpList.size();
        String tmpArray[] = new String[iCounts];
        for (int i = 0; i < iCounts; i++) {
            tmpArray[i] = (String) tmpList.get(i);
        }
        return tmpArray;
    }
    /**
     * ***************************************************** ��
     * �ܣ����ַ�����С��ָ�����ȣ�����IJ�����...���� ��ڲ�����param src ��Ҫ������Ĵ�,param len ָ����С ���ڲ����� ��
     * �أ�return String ��С��ָ�����ȣ�����IJ�����...�������ַ��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String strIntercept(String src, int len) {
        if (src == null) {
            return "";
        }
        if (src.length() > len) {
            src = String.valueOf(String.valueOf(src.substring(0, len))).concat(
                    "...");
        }
        return src;
    }
    /**
     * ***************************************************** ��
     * �ܣ����ַ���ת��ISO8859_1���� ��ڲ�����param str_in Ҫ��������ַ����� ���ڲ����� �� �أ�return String
     * ת������ַ����� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public static String strtochn(String str_in) {
        try {
            String temp_p = str_in;
            if (temp_p == null) {
                temp_p = "";
            }
            String temp = "";
            if (!temp_p.equals("")) {
                byte[] byte1 = temp_p.getBytes("ISO8859_1");
                temp = new String(byte1);
            }
            return temp;
        } catch (Exception e) {
        }
        return "null";
    }
    /**
     * ***************************************************** ��
     * �ܣ���ISO8859_1�ַ���ת��GBK���� ��ڲ�����param strvalue Ҫ��������ַ����� ���ڲ����� �� �أ�return
     * String ת������ַ����� �޸ı�ע��
     * ******************************************************
     */
    public static String ISO2GBK(String strvalue) {
        try {
            if (strvalue == null)
                return null;
            else {
                strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");
                return strvalue;
            }
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * ***************************************************** ��
     * �ܣ���ҳ��Ҫ��ʾ���Ķ�����б���ת�� ��ڲ�����param str Ҫ��������ַ����� ���ڲ����� �� �أ�return String
     * ת������ַ����� �޸ı�ע�� ******************************************************
     */
    public static String cnCodeTrans(String str) {
        String s = "";
        try {
            s = new String(str.getBytes("GB2312"), "8859_1");
        } catch (UnsupportedEncodingException a) {
            System.out.print("chinese thansform exception");
        }
        return s;
    }
    /**
     * ***************************************************** ��
     * �ܣ��ж�Դ���Ƿ���Ϲ�������STaaaa����ST****** ��ڲ�����param strSourceҪ��������ַ�����param
     * strRule���� ���ڲ����� �� �أ�return false:Դ����ƥ�����true:Դ��ƥ����� �޸ı�ע��
     * ******************************************************
     */
    public static boolean judgeMatch(String strSource, String strRule) {
        int i = 0;
        // Դ�������ж�
        if ((null == strSource) || (strSource.length() == 0))
            return false;
        // ���򴮳����ж�
        if ((null == strRule) || (strRule.length() == 0))
            return false;
        // ���Ȳ��ɳ���
        if (strSource.length() > strRule.length())
            return false;
        // ÿһλ���ж�
        for (i = 0; i < strRule.length(); i++) {
            // Դ���ȹ��򴮶�
            if (strSource.length() < i + 1) {
                break;
            }
            if ((strRule.charAt(i) != '*')
                    && (strSource.charAt(i) != strRule.charAt(i))) {
                return false;
            }
        }
        // ����Դ���ȹ��򴮶̵�����������򴮺��Ǿ�Ϊ'*'����ƥ�䲻��
        for (; i < strRule.length(); i++) {
            if (strRule.charAt(i) != '*')
                return false;
        }
        return true;
    }
    public static String column2Property(String column) {
        column = column.toLowerCase();
        int i = column.indexOf("_");
        while (i != -1) {
            if (i != column.length() - 1) {
                char temp = column.charAt(i + 1);
                String strTemp = String.valueOf(temp);
                column = column.replaceFirst("_" + strTemp, strTemp
                        .toUpperCase());
                i = column.indexOf("_");
            } else {
                break;
            }
        }
        return column;
    }
    public static String strArrayToStr(String[] strs, String separator) {
        StringBuffer returnstr = new StringBuffer("");
        if (strs == null)
            return "";
        if (separator == null)
            separator = "";
        for (int i = 0; i < strs.length; i++) {
            returnstr.append(strs[i]);
            if (i < strs.length - 1)
                returnstr.append(separator);
        }
        return returnstr.toString();
    }
    public static String objectArrayToStr(Object[] objects, String separator) {
        StringBuffer returnstr = new StringBuffer("");
        if (objects == null)
            return "";
        if (separator == null)
            separator = "";
        for (int i = 0; i < objects.length; i++) {
            returnstr.append(String.valueOf(objects[i]));
            if (i < objects.length - 1)
                returnstr.append(separator);
        }
        return returnstr.toString();
    }
    public static String listToStr(List element, String separator) {
        StringBuffer returnstr = new StringBuffer("");
        if (element == null)
            return "";
        if (separator == null)
            separator = "";
        Iterator it = element.iterator();
        while (it.hasNext()) {
            returnstr.append(String.valueOf(it.next()));
            if (it.hasNext())
                returnstr.append(separator);
        }
        return returnstr.toString();
    }
    public static String[] listToStrArray(List element) {
        if (element == null || element.size() == 0)
            return null;
        Iterator it = element.iterator();
        String[] strArray = new String[element.size()];
        int i = 0;
        while (it.hasNext()) {
            strArray[i] = String.valueOf(it.next());
            i++;
        }
        return strArray;
    }
    public static List strToList(String str, String separator) {
        if (str == null || str.equals(""))
            return null;
        if (separator == null)
            separator = "";
        String[] strArr = str.split(separator);
        int size = strArr.length;
        List list = new ArrayList();
        for (int i = 0; i < size; i++) {
            list.add(strArr[i]);
        }
        return list;
    }
    public static StringBuffer populate(StringBuffer bf, String value,
                                        boolean isNotLast) {
        if (value == null) {
            return bf;
        }
        // ���ַ�����ÿ���������滻�����������ţ�ע�⣺����˫���ţ�����SQL����ѯ������
        System.out.println(value.replaceAll("'", "''"));
        bf.append("'").append(value.replaceAll("'", "''")).append("'");
        if (isNotLast)
            bf.append(",");
        return bf;
    }
    public static boolean isExist(String str, String substr, String sepatator) {
        if (str == null || str.trim().equals(""))
            return false;
        if (substr == null || substr.trim().equals(""))
            return false;
        String[] strArr = str.split(sepatator);
        int size = strArr.length;
        for (int i = 0; i < size; i++) {
            if (strArr[i].equals(substr))
                return true;
        }
        return false;
    }
    public static boolean isExist(String str, String substr) {
        return isExist(str, substr, ",");
    }
    public static String leftInclude(String str) {
        if (str == null || str.equals(""))
            return str;
        return str + "%";
    }
    public static String rightInclude(String str) {
        if (str == null || str.equals(""))
            return str;
        return "%" + str;
    }
    public static String include(String str) {
        if (str == null || str.equals(""))
            return str;
        return "%" + str + "%";
    }
    /**
     * ���һ���ַ���Ϊ�գ���ת��Ϊָ�����ַ���
     *
     * @param source String ԭ����
     * @param target String ת�������
     * @return String ���
     */
    public static String nvl(Object source, Object target) {
        return source != null ? String.valueOf(source)
                : (target != null ? String.valueOf(target) : null);
    }
    /**
     * ��clob�ֶ�ֵ����Ϊ�ַ���
     *
     * @param clobValue
     * @return
     * @throws SQLException
     */
    public static String clob2Str(Object clobValue) throws SQLException {
        return ((Clob) clobValue).getSubString(1, (int) ((Clob) clobValue)
                .length());
    }
    /**
     * ��ȡweb�ͻ�����ʵIp
     *
     * @param request
     * @return
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    public static String hideFlowStr(String str, int maxLen) {
        if (str == null || maxLen == 0) {
            return "";
        }
        if (str.length() > maxLen) {
            str = str.substring(0, maxLen) + "...";
        }
        return str;
    }
    /**
     * ���������Ƿ�����
     *
     * @param str
     * @return
     */
    public static String escapeLuceneSpecialCharacters(String str) {
        if (str == null) {
            return null;
        }
        try {
            StringWriter writer = new StringWriter(str.length() * 2);
            escapeLuceneSpecialCharacterString(writer, str);
            return writer.toString();
        } catch (IOException ioe) {
            // this should never ever happen while writing to a StringWriter
            ioe.printStackTrace();
            return null;
        }
    }
    private static void escapeLuceneSpecialCharacterString(Writer out,
                                                           String str) throws IOException {
        if (str == null) {
            return;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            char ch = str.charAt(i);
            /*
             * Reference link:
			 * http://lucene.apache.org/java/docs/queryparsersyntax.html Lucene
			 * supports escaping special characters that are part of the query
			 * syntax. The current list special characters are: + - && || ! ( ) { } [ ] ^ " ~ * ? : \
			 * To escape these character use the \ before the character.
			 */
            switch (ch) {
                case '+':
                case '-':
                case '!':
                case '(':
                case ')':
                case '{':
                case '}':
                case '[':
                case ']':
                case '^':
                case '\"':
                case '~':
                case '*':
                case '?':
                case ':':
                case '\\':
                    out.write('\\');
                    out.write(ch);
                    break;
                case '&':
                case '|':
                    // check if it is '&&' or '||' ~ check if the next char is '&'
                    // or '|'
                    if ((i + 1) < sz && str.charAt(i + 1) == ch) {
                        out.write('\\');
                        out.write(ch);
                        i++;
                    }
                    out.write(ch);
                    break;
                default:
                    out.write(ch);
                    break;
            }
        }
    }
    /**
     * ȡ�ø������ֵ�����ĸ������ĸ
     */
    public static String getFirstLetter(String chinese) {
        /**
         * ��ĸ
         */
        final int[] li_SecPosValue = {1601, 1637, 1833, 2078, 2274, 2302,
                2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858,
                4027, 4086, 4390, 4558, 4684, 4925, 5249, 5590};
        final String[] lc_FirstLetter = {"A", "B", "C", "D", "E", "F", "G",
                "H", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
                "W", "X", "Y", "Z"};
        if (chinese == null || chinese.trim().length() == 0) {
            return "";
        }
        chinese = conversionStr(chinese, "GB2312", "ISO8859-1");
        if (chinese.length() > 1) { // �ж��Dz��Ǻ���
            int li_SectorCode = (int) chinese.charAt(0); // ��������
            int li_PositionCode = (int) chinese.charAt(1); // �����
            li_SectorCode = li_SectorCode - 160;
            li_PositionCode = li_PositionCode - 160;
            int li_SecPosCode = li_SectorCode * 100 + li_PositionCode;// �������
            if (li_SecPosCode > 1600 && li_SecPosCode < 5590) {
                for (int i = 0; i < 23; i++) {
                    if (li_SecPosCode >= li_SecPosValue[i]
                            && li_SecPosCode < li_SecPosValue[i + 1]) {
                        chinese = lc_FirstLetter[i];
                        break;
                    }
                }
            } else {
                chinese = conversionStr(chinese, "ISO8859-1", "GB2312");
                chinese = chinese.substring(0, 1);
            }
        }
        return chinese;
    }
    private static String conversionStr(String str, String charsetName,
                                        String toCharsetName) {
        try {
            str = new String(str.getBytes(charsetName), toCharsetName);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return str;
    }
    /**
     * �ı��༭���˷���
     *
     * @param html
     * @return
     */
    public static String checkStr(String html) {
        try {
            html = html.replaceAll("\r", "");
            html = html.replaceAll("\n", "");
            html = html.replaceAll("\"", "'");
            html = html.replaceAll("\t", " ");
            Pattern p_script;
            java.util.regex.Matcher m_script;
            Pattern p_href;
            java.util.regex.Matcher m_href;
            Pattern p_a;
            java.util.regex.Matcher m_a;
            Pattern p_on;
            java.util.regex.Matcher m_on;
            Pattern p_iframe;
            java.util.regex.Matcher m_iframe;
            Pattern p_frameset;
            java.util.regex.Matcher m_frameset;
            Pattern p_img;
            java.util.regex.Matcher m_img;
            Pattern p_p1;
            java.util.regex.Matcher m_p1;
            Pattern p_p2;
            java.util.regex.Matcher m_p2;
            String stript_str = "<script[\\s\\S]+</script *>";
            String href_str = " href *= *[\\s\\S]*script *:";
            String on_str = " on[\\s\\S]*=";
            String iframe_str = "<iframe[\\s\\S]+</iframe *>";
            String frameset_str = "<frameset[\\s\\S]+</frameset *>";
            String a_str = "<a ([^>])*>.*?</a([^>])*>";
            //String img_str = "\\<img[^\\>]+\\>";
            String p_str1 = "</p>";
            String p_str2 = "<p>";
            p_script = Pattern.compile(stript_str, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(html);
            html = m_script.replaceAll(""); // ����script��ǩ
            p_href = Pattern.compile(href_str, Pattern.CASE_INSENSITIVE);
            m_href = p_href.matcher(html);
            html = m_href.replaceAll(""); // ����script��ǩ
            p_a = Pattern.compile(a_str, Pattern.CASE_INSENSITIVE);
            m_a = p_a.matcher(html);
            html = m_a.replaceAll(""); // ����script��ǩ
            p_on = Pattern.compile(on_str, Pattern.CASE_INSENSITIVE);
            m_on = p_on.matcher(html);
            html = m_on.replaceAll(""); // ����script��ǩ
            p_iframe = Pattern.compile(iframe_str, Pattern.CASE_INSENSITIVE);
            m_iframe = p_iframe.matcher(html);
            html = m_iframe.replaceAll(""); // ����script��ǩ
            p_frameset = Pattern
                    .compile(frameset_str, Pattern.CASE_INSENSITIVE);
            m_frameset = p_frameset.matcher(html);
            html = m_frameset.replaceAll(""); // ����script��ǩ
            // p_img = Pattern.compile(img_str, Pattern.CASE_INSENSITIVE);
            // m_img = p_img.matcher(html);
            // html = m_img.replaceAll(""); // ����script��ǩ
            p_p1 = Pattern.compile(p_str1, Pattern.CASE_INSENSITIVE);
            m_p1 = p_p1.matcher(html);
            html = m_p1.replaceAll(""); // ����script��ǩ
            p_p2 = Pattern.compile(p_str2, Pattern.CASE_INSENSITIVE);
            m_p2 = p_p2.matcher(html);
            html = m_p2.replaceAll(""); // ����script��ǩ
        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }
        return html;
    }
    public static String substr(String value, int maxlength, String postfix) {
        int k = 0;
        int l = 0;
        for (int i = 0; i < value.length() && maxlength > l * 2 + k; i++) {
            if (value.charAt(i) > '\200') {
                l++;
            } else {
                k++;
            }
        }
        // value����������Ϊ�����ַ���
        if (l + k >= value.length()) {
            return value;
        } else if (maxlength >= l * 2 + k && l + k > 0) {
            value = value.substring(0, l + k);
        } else if (l + k > 0) {
            value = value.substring(0, (l + k) - 1);
        } else {
            return value;
        }
        // ��ָ���޶���ʾ����ʱ����ȡָ�����ȵ��ַ�����Ϊ���
        if (!StringUtils.isEmpty(postfix)) {
            value += postfix;
        }
        return value;
    }
    public static void main(String[] args) {
        String str = "���!";
    }
    /**
     * ***************************************************** ��
     * �ܣ����紫����ַ�����null��ת�ɿմ������򷵻�ԭ�ַ��� ��ڲ�����param Content:��ת�����ַ��� ���ڲ����� ��
     * �أ�����ַ�����null��ת�ɿմ������򷵻�ԭ�ַ��� <p/> ��д���ڣ�20051220 �޸ı�ע��
     * ******************************************************
     */
    public String nullToSpace(String Content) {
        if (Content == null) {
            Content = "";
        }
        return Content;
    }
    /**
     * ***************************************************** ��
     * �ܣ���GBK�ַ���ת��ISO8859_1���� ��ڲ�����param strvalue Ҫ��������ַ����� ���ڲ����� �� �أ�return
     * String ת������ַ����� �޸ı�ע��
     * ******************************************************
     */
    public String GBK2ISO(String strvalue) throws Exception {
        try {
            if (strvalue == null)
                return null;
            else {
                strvalue = new String(strvalue.getBytes("GBK"), "ISO8859_1");
                return strvalue;
            }
        } catch (Exception e) {
            return null;
        }
    }
}

+ 88 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/TokenUtil.java

@ -0,0 +1,88 @@
package com.yihu.ehr.util.operator;
import com.yihu.ehr.util.encrypt.DES;
import com.yihu.ehr.util.encrypt.MD5;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
 * Created by Administrator on 2015/7/31.
 */
public class TokenUtil {
    private final static String NUM_CHAR = "0123456789";
    private static int charLen = NUM_CHAR.length();
    public static final String PASS_WORD = "ehrvanguardpassword";
    public static String getRandomNumberSeed(int randomNumberDigit) {
        long seed = System.currentTimeMillis();
        StringBuffer sb = new StringBuffer();
        Random random = new Random(seed);
        for (int i = 0; i < randomNumberDigit; i++) {
            sb.append(NUM_CHAR.charAt(random.nextInt(charLen)));
        }
        return sb.toString();
    }
    /**
     * 1. ������Ȩ�� (������������������MD5����)
     *
     * @throws Exception
     */
    public static String genToken() throws Exception {
        String seed  = getRandomNumberSeed(16);
        String token = MD5.hash(seed);
        return token;
    }
    public static String tokenEncrypt(String userId, String appId, Date createDate, long expiresIn) throws Exception {
        long seed = createDate.getTime();
        String expiredTime = String.valueOf(seed + (expiresIn * 1000));
        String[] arrTmp = {userId, appId, expiredTime};
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arrTmp.length; i++) {
            if (i == 0) {
                sb.append(arrTmp[i]);
            } else {
                sb.append("," + arrTmp[i]);
            }
        }
        String token = DES.encrypt(sb.toString(), PASS_WORD);
        return token;
    }
    public static Map tokenDecrypt(String token) throws Exception {
        Map map = new HashMap<>();
        String tokenStr = DES.decrypt(token, PASS_WORD);
        String[] tokenInfo = tokenStr.split(",");
        String userId = tokenInfo[0].toString();
        String appId = tokenInfo[1].toString();
        long expriedTime = Long.valueOf(tokenInfo[2].toString()).longValue();
        Date expriedDate = new Date(expriedTime);
        map.put("userId", userId);
        map.put("appId", appId);
        map.put("expriedTime", expriedDate.toString());
        return map;
    }
}

+ 0 - 0
Hos-Resource-WS/src/main/java/com.yihu.ehr/util/operator/TreeNode.java


部分文件因为文件数量过多而无法显示